Merge inbound to m-c
authorWes Kocher <wkocher@mozilla.com>
Mon, 03 Mar 2014 20:25:51 -0800
changeset 188844 529b86b92b1d047023da27a94e7dc841496ebeff
parent 188814 99388d562e9aad129f32ea40073288420d9d2494 (current diff)
parent 188843 025d98ea7f499e572e198eb581b045af59d29ea4 (diff)
child 188866 af11210cba85352eb81d61f3d20db3a3d88a73ce
child 188886 3fbb1b49067ac0429840dbe2c218ce62135f8ef0
child 188897 9b0d8f906b9a513d3fc8f513d7d2ce4e897fc0ca
push id3503
push userraliiev@mozilla.com
push dateMon, 28 Apr 2014 18:51:11 +0000
treeherdermozilla-beta@c95ac01e332e [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone30.0a1
first release with
nightly linux32
529b86b92b1d / 30.0a1 / 20140304030204 / files
nightly linux64
529b86b92b1d / 30.0a1 / 20140304030204 / files
nightly mac
529b86b92b1d / 30.0a1 / 20140304030204 / files
nightly win32
529b86b92b1d / 30.0a1 / 20140304030204 / files
nightly win64
529b86b92b1d / 30.0a1 / 20140304030204 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge inbound to m-c
testing/mozbase/mozprocess/tests/test_mozprocess_nonewline.py
--- a/browser/locales/en-US/searchplugins/bing.xml
+++ b/browser/locales/en-US/searchplugins/bing.xml
@@ -10,13 +10,15 @@
     <Url type="application/x-suggestions+json" template="http://api.bing.com/osjson.aspx">
         <Param name="query" value="{searchTerms}"/>
         <Param name="form" value="OSDJAS"/>
         <Param name="language" value="{moz:locale}"/>
     </Url>
     <Url type="text/html" method="GET" template="http://www.bing.com/search">
         <Param name="q" value="{searchTerms}"/>
         <MozParam name="pc" condition="pref" pref="ms-pc"/>
-        <MozParam name="form" condition="purpose" purpose="" value="MOZSBR"/>
+        <MozParam name="form" condition="purpose" purpose="contextmenu" value="MOZSBR"/>
+        <MozParam name="form" condition="purpose" purpose="searchbar" value="MOZSBR"/>
+        <MozParam name="form" condition="purpose" purpose="homepage" value="MOZSPG"/>
         <MozParam name="form" condition="purpose" purpose="keyword" value="MOZLBR"/>
     </Url>
     <SearchForm>http://www.bing.com/search</SearchForm>
 </SearchPlugin>
--- a/configure.in
+++ b/configure.in
@@ -8038,19 +8038,16 @@ AC_SUBST(MOZ_TREE_PIXMAN)
 dnl ========================================================
 dnl Skia
 dnl ========================================================
 if test "$MOZ_ENABLE_SKIA"; then
   AC_DEFINE(MOZ_ENABLE_SKIA)
   AC_DEFINE(USE_SKIA)
   if test "${MOZ_WIDGET_TOOLKIT}" = "android" -o x"$MOZ_WIDGET_TOOLKIT" = x"gonk"; then
     AC_DEFINE(SK_BUILD_FOR_ANDROID_NDK)
-  elif test "$OS_ARCH" = "WINNT"; then
-    AC_DEFINE(SKIA_DLL)
-    AC_DEFINE(GR_DLL)
   fi
 
   if test "${CPU_ARCH}" != "ppc" -a "${CPU_ARCH}" != "ppc64"; then
     MOZ_ENABLE_SKIA_GPU=1
     AC_DEFINE(USE_SKIA_GPU)
     AC_SUBST(MOZ_ENABLE_SKIA_GPU)
   fi
 fi
--- a/content/base/public/nsDOMFile.h
+++ b/content/base/public/nsDOMFile.h
@@ -375,16 +375,18 @@ public:
     : nsDOMFile(aContentType, aLength),
       mDataOwner(new DataOwner(aMemoryBuffer, aLength))
   {
     NS_ASSERTION(mDataOwner && mDataOwner->mData, "must have data");
   }
 
   NS_IMETHOD GetInternalStream(nsIInputStream**) MOZ_OVERRIDE;
 
+  NS_IMETHOD_(bool) IsMemoryFile(void) MOZ_OVERRIDE;
+
 protected:
   // Create slice
   nsDOMMemoryFile(const nsDOMMemoryFile* aOther, uint64_t aStart,
                   uint64_t aLength, const nsAString& aContentType)
     : nsDOMFile(aContentType, aOther->mStart + aStart, aLength),
       mDataOwner(aOther->mDataOwner)
   {
     NS_ASSERTION(mDataOwner && mDataOwner->mData, "must have data");
--- a/content/base/public/nsHostObjectProtocolHandler.h
+++ b/content/base/public/nsHostObjectProtocolHandler.h
@@ -49,16 +49,19 @@ public:
   // AddDataEntry creates the URI with the given scheme and returns it in aUri
   static nsresult AddDataEntry(const nsACString& aScheme,
                                nsISupports* aObject,
                                nsIPrincipal* aPrincipal,
                                nsACString& aUri);
   static void RemoveDataEntry(const nsACString& aUri);
   static nsIPrincipal* GetDataEntryPrincipal(const nsACString& aUri);
   static void Traverse(const nsACString& aUri, nsCycleCollectionTraversalCallback& aCallback);
+
+private:
+  static void Init(void);
 };
 
 class nsBlobProtocolHandler : public nsHostObjectProtocolHandler
 {
 public:
   NS_IMETHOD GetScheme(nsACString &result) MOZ_OVERRIDE;
 };
 
--- a/content/base/public/nsIDOMFile.idl
+++ b/content/base/public/nsIDOMFile.idl
@@ -21,17 +21,17 @@ class FileManager;
 [ptr] native FileManager(mozilla::dom::indexedDB::FileManager);
 
 interface nsIDOMFileError;
 interface nsIInputStream;
 interface nsIURI;
 interface nsIPrincipal;
 interface nsIDOMBlob;
 
-[scriptable, builtinclass, uuid(52d22585-7737-460e-9731-c658df03304a)]
+[scriptable, builtinclass, uuid(b1723fac-4814-4429-82cb-dc54ba0d46d6)]
 interface nsIDOMBlob : nsISupports
 {
   readonly attribute unsigned long long size;
   readonly attribute DOMString type;
 
   [noscript] readonly attribute nsIInputStream internalStream;
   // The caller is responsible for releasing the internalUrl from the
   // blob: protocol handler
@@ -52,19 +52,22 @@ interface nsIDOMBlob : nsISupports
 
   // Called when the blob was successfully stored in a database or when
   // the blob is initialized from a database. It can be called on any thread.
   [notxpcom] void addFileInfo(in FileInfo aFileInfo);
 
   // Called before the blob is stored in a database to decide if it can be
   // shared or needs to be copied. It can be called on any thread.
   [notxpcom] FileInfo getFileInfo(in FileManager aFileManager);
+
+  // Return true if this blob is a memory file.
+  [notxpcom] bool isMemoryFile();
 };
 
-[scriptable, builtinclass, uuid(0acb4135-9f79-4516-ba92-b5fba5203620)]
+[scriptable, builtinclass, uuid(4e7d1a8b-e2d5-4304-a753-4affb731660c)]
 interface nsIDOMFile : nsIDOMBlob
 {
   readonly attribute DOMString name;
 
   readonly attribute DOMString path;
 
   [implicit_jscontext]
   readonly attribute jsval lastModifiedDate;
--- a/content/base/src/Link.cpp
+++ b/content/base/src/Link.cpp
@@ -212,19 +212,17 @@ Link::SetPathname(const nsAString &aPath
   (void)url->SetFilePath(NS_ConvertUTF16toUTF8(aPathname));
   SetHrefAttribute(uri);
 }
 
 void
 Link::SetSearch(const nsAString& aSearch)
 {
   SetSearchInternal(aSearch);
-  if (mSearchParams) {
-    mSearchParams->Invalidate();
-  }
+  UpdateURLSearchParams();
 }
 
 void
 Link::SetSearchInternal(const nsAString& aSearch)
 {
   nsCOMPtr<nsIURI> uri(GetURIToMutate());
   nsCOMPtr<nsIURL> url(do_QueryInterface(uri));
   if (!url) {
@@ -482,19 +480,17 @@ Link::ResetLinkState(bool aNotify, bool 
     UnregisterFromHistory();
   }
 
   // If we have an href, we should register with the history.
   mNeedsRegistration = aHasHref;
 
   // If we've cached the URI, reset always invalidates it.
   mCachedURI = nullptr;
-  if (mSearchParams) {
-    mSearchParams->Invalidate();
-  }
+  UpdateURLSearchParams();
 
   // Update our state back to the default.
   mLinkState = defaultState;
 
   // We have to be very careful here: if aNotify is false we do NOT
   // want to call UpdateState, because that will call into LinkState()
   // and try to start off loads, etc.  But ResetLinkState is called
   // with aNotify false when things are in inconsistent states, so
@@ -584,73 +580,75 @@ Link::GetSearchParams()
 
 void
 Link::SetSearchParams(URLSearchParams* aSearchParams)
 {
   if (!aSearchParams) {
     return;
   }
 
-  if (!aSearchParams->HasURLAssociated()) {
-    MOZ_ASSERT(aSearchParams->IsValid());
+  if (mSearchParams) {
+    mSearchParams->RemoveObserver(this);
+  }
 
-    mSearchParams = aSearchParams;
-    mSearchParams->SetObserver(this);
-  } else {
-    CreateSearchParamsIfNeeded();
-    mSearchParams->CopyFromURLSearchParams(*aSearchParams);
-  }
+  mSearchParams = aSearchParams;
+  mSearchParams->AddObserver(this);
 
   nsAutoString search;
   mSearchParams->Serialize(search);
   SetSearchInternal(search);
 }
 
 void
 Link::URLSearchParamsUpdated()
 {
-  MOZ_ASSERT(mSearchParams && mSearchParams->IsValid());
+  MOZ_ASSERT(mSearchParams);
 
   nsString search;
   mSearchParams->Serialize(search);
   SetSearchInternal(search);
 }
 
 void
-Link::URLSearchParamsNeedsUpdates()
+Link::UpdateURLSearchParams()
 {
-  MOZ_ASSERT(mSearchParams);
+  if (!mSearchParams) {
+    return;
+  }
 
   nsAutoCString search;
   nsCOMPtr<nsIURI> uri(GetURI());
   nsCOMPtr<nsIURL> url(do_QueryInterface(uri));
   if (url) {
     nsresult rv = url->GetQuery(search);
     if (NS_FAILED(rv)) {
       NS_WARNING("Failed to get the query from a nsIURL.");
     }
   }
 
-  mSearchParams->ParseInput(search);
+  mSearchParams->ParseInput(search, this);
 }
 
 void
 Link::CreateSearchParamsIfNeeded()
 {
   if (!mSearchParams) {
     mSearchParams = new URLSearchParams();
-    mSearchParams->SetObserver(this);
-    mSearchParams->Invalidate();
+    mSearchParams->AddObserver(this);
+    UpdateURLSearchParams();
   }
 }
 
 void
 Link::Unlink()
 {
-  mSearchParams = nullptr;
+  if (mSearchParams) {
+    mSearchParams->RemoveObserver(this);
+    mSearchParams = nullptr;
+  }
 }
 
 void
 Link::Traverse(nsCycleCollectionTraversalCallback &cb)
 {
   Link* tmp = this;
   NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSearchParams);
 }
--- a/content/base/src/Link.h
+++ b/content/base/src/Link.h
@@ -109,17 +109,16 @@ public:
 
   virtual size_t
     SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const;
 
   bool ElementHasHref() const;
 
   // URLSearchParamsObserver
   void URLSearchParamsUpdated() MOZ_OVERRIDE;
-  void URLSearchParamsNeedsUpdates() MOZ_OVERRIDE;
 
 protected:
   virtual ~Link();
 
   /**
    * Return true if the link has associated URI.
    */
   bool HasURI() const
@@ -129,16 +128,18 @@ protected:
     }
 
     return !!GetURI();
   }
 
   nsIURI* GetCachedURI() const { return mCachedURI; }
   bool HasCachedURI() const { return !!mCachedURI; }
 
+  void UpdateURLSearchParams();
+
   // CC methods
   void Unlink();
   void Traverse(nsCycleCollectionTraversalCallback &cb);
 
 private:
   /**
    * Unregisters from History so this node no longer gets notifications about
    * changes to visitedness.
--- a/content/base/src/nsDOMFile.cpp
+++ b/content/base/src/nsDOMFile.cpp
@@ -438,16 +438,22 @@ nsDOMFileBase::SetMutable(bool aMutable)
     rv = this->GetSize(&dummyInt);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   mImmutable = !aMutable;
   return rv;
 }
 
+NS_IMETHODIMP_(bool)
+nsDOMFileBase::IsMemoryFile(void)
+{
+  return false;
+}
+
 ////////////////////////////////////////////////////////////////////////////
 // nsDOMFile implementation
 
 DOMCI_DATA(File, nsDOMFile)
 DOMCI_DATA(Blob, nsDOMFile)
 
 NS_INTERFACE_MAP_BEGIN(nsDOMFile)
   NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDOMFile)
@@ -631,16 +637,22 @@ NS_IMETHODIMP
 nsDOMMemoryFile::GetInternalStream(nsIInputStream **aStream)
 {
   if (mLength > INT32_MAX)
     return NS_ERROR_FAILURE;
 
   return DataOwnerAdapter::Create(mDataOwner, mStart, mLength, aStream);
 }
 
+NS_IMETHODIMP_(bool)
+nsDOMMemoryFile::IsMemoryFile(void)
+{
+  return true;
+}
+
 /* static */ StaticMutex
 nsDOMMemoryFile::DataOwner::sDataOwnerMutex;
 
 /* static */ StaticAutoPtr<LinkedList<nsDOMMemoryFile::DataOwner> >
 nsDOMMemoryFile::DataOwner::sDataOwners;
 
 /* static */ bool
 nsDOMMemoryFile::DataOwner::sMemoryReporterRegistered;
--- a/content/base/src/nsDocument.cpp
+++ b/content/base/src/nsDocument.cpp
@@ -9362,16 +9362,22 @@ nsDocument::GetTemplateContentsOwner()
                                     scriptObject, // aEventObject
                                     DocumentFlavorHTML);
     NS_ENSURE_SUCCESS(rv, nullptr);
 
     mTemplateContentsOwner = do_QueryInterface(domDocument);
     NS_ENSURE_TRUE(mTemplateContentsOwner, nullptr);
 
     mTemplateContentsOwner->SetScriptHandlingObject(scriptObject);
+
+    // Set |doc| as the template contents owner of itself so that
+    // |doc| is the template contents owner of template elements created
+    // by |doc|.
+    nsDocument* doc = static_cast<nsDocument*>(mTemplateContentsOwner.get());
+    doc->mTemplateContentsOwner = doc;
   }
 
   return mTemplateContentsOwner;
 }
 
 void
 nsDocument::RegisterHostObjectUri(const nsACString& aUri)
 {
--- a/content/base/src/nsFrameMessageManager.cpp
+++ b/content/base/src/nsFrameMessageManager.cpp
@@ -698,22 +698,22 @@ nsFrameMessageManager::BroadcastAsyncMes
 {
   return DispatchAsyncMessage(aMessageName, aJSON, aObjects, nullptr, aCx,
                               aArgc);
 }
 
 NS_IMETHODIMP
 nsFrameMessageManager::GetChildCount(uint32_t* aChildCount)
 {
-  *aChildCount = static_cast<uint32_t>(mChildManagers.Count()); 
+  *aChildCount = static_cast<uint32_t>(mChildManagers.Count());
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsFrameMessageManager::GetChildAt(uint32_t aIndex, 
+nsFrameMessageManager::GetChildAt(uint32_t aIndex,
                                   nsIMessageListenerManager** aMM)
 {
   *aMM = nullptr;
   nsCOMPtr<nsIMessageListenerManager> mm =
     do_QueryInterface(mChildManagers.SafeObjectAt(static_cast<uint32_t>(aIndex)));
   mm.swap(*aMM);
   return NS_OK;
 }
@@ -1424,17 +1424,18 @@ nsFrameScriptExecutor::LoadFrameScriptIn
     bool ok = true;
     if (funobj) {
       JS::Rooted<JSObject*> method(cx, JS_CloneFunctionObject(cx, funobj, global));
       if (!method) {
         return;
       }
       JS::Rooted<JS::Value> rval(cx);
       JS::Rooted<JS::Value> methodVal(cx, JS::ObjectValue(*method));
-      ok = JS_CallFunctionValue(cx, global, methodVal, JS::EmptyValueArray, &rval);
+      ok = JS_CallFunctionValue(cx, global, methodVal,
+                                JS::HandleValueArray::empty(), &rval);
     } else if (script) {
       ok = JS_ExecuteScript(cx, global, script, nullptr);
     }
 
     if (!ok) {
       nsJSUtils::ReportPendingException(cx);
     }
   }
--- a/content/base/src/nsHostObjectProtocolHandler.cpp
+++ b/content/base/src/nsHostObjectProtocolHandler.cpp
@@ -161,29 +161,33 @@ class BlobURLsReporter MOZ_FINAL : publi
     blob = do_QueryInterface(aInfo->mObject);
     if (blob) {
       NS_NAMED_LITERAL_CSTRING
         (desc, "A blob URL allocated with URL.createObjectURL; the referenced "
          "blob cannot be freed until all URLs for it have been explicitly "
          "invalidated with URL.revokeObjectURL.");
       nsAutoCString path, url, owner, specialDesc;
       nsCOMPtr<nsIURI> principalURI;
-      uint64_t size;
+      uint64_t size = 0;
       uint32_t refCount = 1;
       DebugOnly<bool> blobWasCounted;
 
       blobWasCounted = envp->mRefCounts.Get(blob, &refCount);
       MOZ_ASSERT(blobWasCounted);
       MOZ_ASSERT(refCount > 0);
 
-      if (NS_FAILED(blob->GetSize(&size))) {
-        size = 0;
+      bool isMemoryFile = blob->IsMemoryFile();
+
+      if (isMemoryFile) {
+        if (NS_FAILED(blob->GetSize(&size))) {
+          size = 0;
+        }
       }
 
-      path = "blob-urls/";
+      path = isMemoryFile ? "memory-blob-urls/" : "file-blob-urls/";
       if (NS_SUCCEEDED(aInfo->mPrincipal->GetURI(getter_AddRefs(principalURI))) &&
           principalURI != nullptr &&
           NS_SUCCEEDED(principalURI->GetSpec(owner)) &&
           !owner.IsEmpty()) {
         owner.ReplaceChar('/', '\\');
         path += "owner(";
         path += owner;
         path += ")";
@@ -206,56 +210,79 @@ class BlobURLsReporter MOZ_FINAL : publi
         path += "@";
         path += addrStr;
 
         specialDesc = desc;
         specialDesc += "\n\nNOTE: This blob (address ";
         specialDesc += addrStr;
         specialDesc += ") has ";
         specialDesc.AppendInt(refCount);
-        specialDesc += " URLs; its size is divided ";
-        specialDesc += refCount > 2 ? "among" : "between";
-        specialDesc += " them in this report.";
+        specialDesc += " URLs.";
+        if (isMemoryFile) {
+          specialDesc += " Its size is divided ";
+          specialDesc += refCount > 2 ? "among" : "between";
+          specialDesc += " them in this report.";
+        }
       }
-      envp->mCallback->Callback(EmptyCString(),
-                                path,
-                                KIND_OTHER,
-                                UNITS_BYTES,
-                                size / refCount,
-                                (specialDesc.IsEmpty()
-                                 ? static_cast<const nsACString&>(desc)
-                                 : static_cast<const nsACString&>(specialDesc)),
-                                envp->mData);
+
+      const nsACString& descString = specialDesc.IsEmpty()
+          ? static_cast<const nsACString&>(desc)
+          : static_cast<const nsACString&>(specialDesc);
+      if (isMemoryFile) {
+        envp->mCallback->Callback(EmptyCString(),
+            path,
+            KIND_OTHER,
+            UNITS_BYTES,
+            size / refCount,
+            descString,
+            envp->mData);
+      }
+      else {
+        envp->mCallback->Callback(EmptyCString(),
+            path,
+            KIND_OTHER,
+            UNITS_COUNT,
+            1,
+            descString,
+            envp->mData);
+      }
     }
     return PL_DHASH_NEXT;
   }
 };
 
 NS_IMPL_ISUPPORTS1(BlobURLsReporter, nsIMemoryReporter)
 
 }
 
-nsHostObjectProtocolHandler::nsHostObjectProtocolHandler()
+void
+nsHostObjectProtocolHandler::Init(void)
 {
   static bool initialized = false;
 
   if (!initialized) {
     initialized = true;
     RegisterStrongMemoryReporter(new mozilla::HostObjectURLsReporter());
     RegisterStrongMemoryReporter(new mozilla::BlobURLsReporter());
   }
 }
 
+nsHostObjectProtocolHandler::nsHostObjectProtocolHandler()
+{
+  Init();
+}
 
 nsresult
 nsHostObjectProtocolHandler::AddDataEntry(const nsACString& aScheme,
                                           nsISupports* aObject,
                                           nsIPrincipal* aPrincipal,
                                           nsACString& aUri)
 {
+  Init();
+
   nsresult rv = GenerateURIString(aScheme, aUri);
   NS_ENSURE_SUCCESS(rv, rv);
 
   if (!gDataTable) {
     gDataTable = new nsClassHashtable<nsCStringHashKey, DataInfo>;
   }
 
   DataInfo* info = new DataInfo;
--- a/content/html/content/src/HTMLTemplateElement.cpp
+++ b/content/html/content/src/HTMLTemplateElement.cpp
@@ -34,26 +34,18 @@ HTMLTemplateElement::HTMLTemplateElement
   : nsGenericHTMLElement(aNodeInfo)
 {
   SetHasWeirdParserInsertionMode();
 }
 
 nsresult
 HTMLTemplateElement::Init()
 {
-  nsIDocument* doc = OwnerDoc();
-  nsIDocument* contentsOwner = doc;
-
-  // Used to test if the document "has a browsing context".
-  nsCOMPtr<nsISupports> container = doc->GetContainer();
-  if (container) {
-    // GetTemplateContentsOwner lazily creates a document.
-    contentsOwner = doc->GetTemplateContentsOwner();
-    NS_ENSURE_TRUE(contentsOwner, NS_ERROR_UNEXPECTED);
-  }
+  nsIDocument* contentsOwner = OwnerDoc()->GetTemplateContentsOwner();
+  NS_ENSURE_TRUE(contentsOwner, NS_ERROR_UNEXPECTED);
 
   mContent = contentsOwner->CreateDocumentFragment();
   mContent->SetHost(this);
 
   return NS_OK;
 }
 
 HTMLTemplateElement::~HTMLTemplateElement()
--- a/dom/base/URL.cpp
+++ b/dom/base/URL.cpp
@@ -15,17 +15,28 @@
 #include "nsIIOService.h"
 #include "nsEscape.h"
 #include "nsNetCID.h"
 #include "nsIURL.h"
 
 namespace mozilla {
 namespace dom {
 
-NS_IMPL_CYCLE_COLLECTION_1(URL, mSearchParams)
+NS_IMPL_CYCLE_COLLECTION_CLASS(URL)
+
+NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(URL)
+  if (tmp->mSearchParams) {
+    tmp->mSearchParams->RemoveObserver(tmp);
+    NS_IMPL_CYCLE_COLLECTION_UNLINK(mSearchParams)
+  }
+NS_IMPL_CYCLE_COLLECTION_UNLINK_END
+
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(URL)
+  NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSearchParams)
+NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 
 NS_IMPL_CYCLE_COLLECTING_ADDREF(URL)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(URL)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(URL)
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
@@ -216,20 +227,17 @@ URL::SetHref(const nsAString& aHref, Err
   rv = ioService->NewURI(href, nullptr, nullptr, getter_AddRefs(uri));
   if (NS_FAILED(rv)) {
     nsAutoString label(aHref);
     aRv.ThrowTypeError(MSG_INVALID_URL, &label);
     return;
   }
 
   aRv = mURI->SetSpec(href);
-
-  if (mSearchParams) {
-    mSearchParams->Invalidate();
-  }
+  UpdateURLSearchParams();
 }
 
 void
 URL::GetOrigin(nsString& aOrigin) const
 {
   nsContentUtils::GetUTFNonNullOrigin(mURI, aOrigin);
 }
 
@@ -299,38 +307,40 @@ void
 URL::SetHost(const nsAString& aHost)
 {
   mURI->SetHostPort(NS_ConvertUTF16toUTF8(aHost));
 }
 
 void
 URL::URLSearchParamsUpdated()
 {
-  MOZ_ASSERT(mSearchParams && mSearchParams->IsValid());
+  MOZ_ASSERT(mSearchParams);
 
   nsAutoString search;
   mSearchParams->Serialize(search);
   SetSearchInternal(search);
 }
 
 void
-URL::URLSearchParamsNeedsUpdates()
+URL::UpdateURLSearchParams()
 {
-  MOZ_ASSERT(mSearchParams);
+  if (!mSearchParams) {
+    return;
+  }
 
   nsAutoCString search;
   nsCOMPtr<nsIURL> url(do_QueryInterface(mURI));
   if (url) {
     nsresult rv = url->GetQuery(search);
     if (NS_FAILED(rv)) {
       NS_WARNING("Failed to get the query from a nsIURL.");
     }
   }
 
-  mSearchParams->ParseInput(search);
+  mSearchParams->ParseInput(search, this);
 }
 
 void
 URL::GetHostname(nsString& aHostname) const
 {
   URL_GETTER(aHostname, GetHost);
 }
 
@@ -421,20 +431,17 @@ URL::GetSearch(nsString& aSearch) const
     CopyUTF8toUTF16(NS_LITERAL_CSTRING("?") + search, aSearch);
   }
 }
 
 void
 URL::SetSearch(const nsAString& aSearch)
 {
   SetSearchInternal(aSearch);
-
-  if (mSearchParams) {
-    mSearchParams->Invalidate();
-  }
+  UpdateURLSearchParams();
 }
 
 void
 URL::SetSearchInternal(const nsAString& aSearch)
 {
   nsCOMPtr<nsIURL> url(do_QueryInterface(mURI));
   if (!url) {
     // Ignore failures to be compatible with NS4.
@@ -453,25 +460,23 @@ URL::GetSearchParams()
 
 void
 URL::SetSearchParams(URLSearchParams* aSearchParams)
 {
   if (!aSearchParams) {
     return;
   }
 
-  if (!aSearchParams->HasURLAssociated()) {
-    MOZ_ASSERT(aSearchParams->IsValid());
+  if (mSearchParams) {
+    mSearchParams->RemoveObserver(this);
+  }
 
-    mSearchParams = aSearchParams;
-    mSearchParams->SetObserver(this);
-  } else {
-    CreateSearchParamsIfNeeded();
-    mSearchParams->CopyFromURLSearchParams(*aSearchParams);
-  }
+  // the observer will be cleared using the cycle collector.
+  mSearchParams = aSearchParams;
+  mSearchParams->AddObserver(this);
 
   nsAutoString search;
   mSearchParams->Serialize(search);
   SetSearchInternal(search);
 }
 
 void
 URL::GetHash(nsString& aHash) const
@@ -501,15 +506,15 @@ bool IsChromeURI(nsIURI* aURI)
   return false;
 }
 
 void
 URL::CreateSearchParamsIfNeeded()
 {
   if (!mSearchParams) {
     mSearchParams = new URLSearchParams();
-    mSearchParams->SetObserver(this);
-    mSearchParams->Invalidate();
+    mSearchParams->AddObserver(this);
+    UpdateURLSearchParams();
   }
 }
 
 }
 }
--- a/dom/base/URL.h
+++ b/dom/base/URL.h
@@ -120,28 +120,29 @@ public:
 
   void Stringify(nsString& aRetval) const
   {
     GetHref(aRetval);
   }
 
   // URLSearchParamsObserver
   void URLSearchParamsUpdated() MOZ_OVERRIDE;
-  void URLSearchParamsNeedsUpdates() MOZ_OVERRIDE;
 
 private:
   nsIURI* GetURI() const
   {
     return mURI;
   }
 
   void CreateSearchParamsIfNeeded();
 
   void SetSearchInternal(const nsAString& aSearch);
 
+  void UpdateURLSearchParams();
+
   static void CreateObjectURLInternal(const GlobalObject& aGlobal,
                                       nsISupports* aObject,
                                       const nsACString& aScheme,
                                       const objectURLOptions& aOptions,
                                       nsString& aResult,
                                       ErrorResult& aError);
 
   nsCOMPtr<nsIURI> mURI;
--- a/dom/base/URLSearchParams.cpp
+++ b/dom/base/URLSearchParams.cpp
@@ -4,27 +4,26 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "URLSearchParams.h"
 #include "mozilla/dom/URLSearchParamsBinding.h"
 
 namespace mozilla {
 namespace dom {
 
-NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_1(URLSearchParams, mObserver)
+NS_IMPL_CYCLE_COLLECTION_WRAPPERCACHE_1(URLSearchParams, mObservers)
 NS_IMPL_CYCLE_COLLECTING_ADDREF(URLSearchParams)
 NS_IMPL_CYCLE_COLLECTING_RELEASE(URLSearchParams)
 
 NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(URLSearchParams)
   NS_WRAPPERCACHE_INTERFACE_MAP_ENTRY
   NS_INTERFACE_MAP_ENTRY(nsISupports)
 NS_INTERFACE_MAP_END
 
 URLSearchParams::URLSearchParams()
-  : mValid(false)
 {
   SetIsDOMBinding();
 }
 
 URLSearchParams::~URLSearchParams()
 {
   DeleteAll();
 }
@@ -36,33 +35,33 @@ URLSearchParams::WrapObject(JSContext* a
 }
 
 /* static */ already_AddRefed<URLSearchParams>
 URLSearchParams::Constructor(const GlobalObject& aGlobal,
                              const nsAString& aInit,
                              ErrorResult& aRv)
 {
   nsRefPtr<URLSearchParams> sp = new URLSearchParams();
-  sp->ParseInput(NS_ConvertUTF16toUTF8(aInit));
+  sp->ParseInput(NS_ConvertUTF16toUTF8(aInit), nullptr);
   return sp.forget();
 }
 
 /* static */ already_AddRefed<URLSearchParams>
 URLSearchParams::Constructor(const GlobalObject& aGlobal,
                              URLSearchParams& aInit,
                              ErrorResult& aRv)
 {
   nsRefPtr<URLSearchParams> sp = new URLSearchParams();
   aInit.mSearchParams.EnumerateRead(CopyEnumerator, sp);
-  sp->mValid = true;
   return sp.forget();
 }
 
 void
-URLSearchParams::ParseInput(const nsACString& aInput)
+URLSearchParams::ParseInput(const nsACString& aInput,
+                            URLSearchParamsObserver* aObserver)
 {
   // Remove all the existing data before parsing a new input.
   DeleteAll();
 
   nsACString::const_iterator start, end;
   aInput.BeginReading(start);
   aInput.EndReading(end);
   nsACString::const_iterator iter(start);
@@ -104,17 +103,17 @@ URLSearchParams::ParseInput(const nsACSt
 
     nsAutoCString decodedValue;
     DecodeString(value, decodedValue);
 
     AppendInternal(NS_ConvertUTF8toUTF16(decodedName),
                    NS_ConvertUTF8toUTF16(decodedValue));
   }
 
-  mValid = true;
+  NotifyObservers(aObserver);
 }
 
 void
 URLSearchParams::DecodeString(const nsACString& aInput, nsACString& aOutput)
 {
   nsACString::const_iterator start, end;
   aInput.BeginReading(start);
   aInput.EndReading(end);
@@ -160,114 +159,88 @@ URLSearchParams::DecodeString(const nsAC
       }
     }
 
     aOutput.Append(*start);
     ++start;
   }
 }
 
-void
-URLSearchParams::CopyFromURLSearchParams(URLSearchParams& aSearchParams)
-{
-  // The other SearchParams must be valid before copying its data.
-  aSearchParams.Validate();
-
-  // Remove all the existing data before parsing a new input.
-  DeleteAll();
-  aSearchParams.mSearchParams.EnumerateRead(CopyEnumerator, this);
-  mValid = true;
-}
-
 /* static */ PLDHashOperator
 URLSearchParams::CopyEnumerator(const nsAString& aName,
                                 nsTArray<nsString>* aArray,
                                 void *userData)
 {
   URLSearchParams* aSearchParams = static_cast<URLSearchParams*>(userData);
 
   nsTArray<nsString>* newArray = new nsTArray<nsString>();
   newArray->AppendElements(*aArray);
 
   aSearchParams->mSearchParams.Put(aName, newArray);
   return PL_DHASH_NEXT;
 }
 
 void
-URLSearchParams::SetObserver(URLSearchParamsObserver* aObserver)
+URLSearchParams::AddObserver(URLSearchParamsObserver* aObserver)
 {
-  MOZ_ASSERT(!mObserver);
-  mObserver = aObserver;
+  MOZ_ASSERT(aObserver);
+  MOZ_ASSERT(!mObservers.Contains(aObserver));
+  mObservers.AppendElement(aObserver);
 }
 
 void
-URLSearchParams::Validate()
+URLSearchParams::RemoveObserver(URLSearchParamsObserver* aObserver)
 {
-  MOZ_ASSERT(mValid || mObserver);
-  if (!mValid) {
-    mObserver->URLSearchParamsNeedsUpdates();
-    MOZ_ASSERT(mValid);
-  }
+  MOZ_ASSERT(aObserver);
+  mObservers.RemoveElement(aObserver);
 }
 
 void
 URLSearchParams::Get(const nsAString& aName, nsString& aRetval)
 {
-  Validate();
-
   nsTArray<nsString>* array;
   if (!mSearchParams.Get(aName, &array)) {
     aRetval.Truncate();
     return;
   }
 
   aRetval.Assign(array->ElementAt(0));
 }
 
 void
 URLSearchParams::GetAll(const nsAString& aName, nsTArray<nsString>& aRetval)
 {
-  Validate();
-
   nsTArray<nsString>* array;
   if (!mSearchParams.Get(aName, &array)) {
     return;
   }
 
   aRetval.AppendElements(*array);
 }
 
 void
 URLSearchParams::Set(const nsAString& aName, const nsAString& aValue)
 {
-  // Before setting any new value we have to be sure to have all the previous
-  // values in place.
-  Validate();
-
   nsTArray<nsString>* array;
   if (!mSearchParams.Get(aName, &array)) {
     array = new nsTArray<nsString>();
     array->AppendElement(aValue);
     mSearchParams.Put(aName, array);
   } else {
     array->ElementAt(0) = aValue;
   }
 
-  NotifyObserver();
+  NotifyObservers(nullptr);
 }
 
 void
 URLSearchParams::Append(const nsAString& aName, const nsAString& aValue)
 {
-  // Before setting any new value we have to be sure to have all the previous
-  // values in place.
-  Validate();
-
   AppendInternal(aName, aValue);
-  NotifyObserver();
+  NotifyObservers(nullptr);
 }
 
 void
 URLSearchParams::AppendInternal(const nsAString& aName, const nsAString& aValue)
 {
   nsTArray<nsString>* array;
   if (!mSearchParams.Get(aName, &array)) {
     array = new nsTArray<nsString>();
@@ -275,35 +248,30 @@ URLSearchParams::AppendInternal(const ns
   }
 
   array->AppendElement(aValue);
 }
 
 bool
 URLSearchParams::Has(const nsAString& aName)
 {
-  Validate();
   return mSearchParams.Get(aName, nullptr);
 }
 
 void
 URLSearchParams::Delete(const nsAString& aName)
 {
-  // Before deleting any value we have to be sure to have all the previous
-  // values in place.
-  Validate();
-
   nsTArray<nsString>* array;
   if (!mSearchParams.Get(aName, &array)) {
     return;
   }
 
   mSearchParams.Remove(aName);
 
-  NotifyObserver();
+  NotifyObservers(nullptr);
 }
 
 void
 URLSearchParams::DeleteAll()
 {
   mSearchParams.Clear();
 }
 
@@ -338,18 +306,16 @@ public:
       ++p;
     }
   }
 };
 
 void
 URLSearchParams::Serialize(nsAString& aValue) const
 {
-  MOZ_ASSERT(mValid);
-
   SerializeData data;
   mSearchParams.EnumerateRead(SerializeEnumerator, &data);
   aValue.Assign(data.mValue);
 }
 
 /* static */ PLDHashOperator
 URLSearchParams::SerializeEnumerator(const nsAString& aName,
                                      nsTArray<nsString>* aArray,
@@ -368,23 +334,19 @@ URLSearchParams::SerializeEnumerator(con
     data->mValue.Append(NS_LITERAL_STRING("="));
     data->Serialize(NS_ConvertUTF16toUTF8(aArray->ElementAt(i)));
   }
 
   return PL_DHASH_NEXT;
 }
 
 void
-URLSearchParams::NotifyObserver()
+URLSearchParams::NotifyObservers(URLSearchParamsObserver* aExceptObserver)
 {
-  if (mObserver) {
-    mObserver->URLSearchParamsUpdated();
+  for (uint32_t i = 0; i < mObservers.Length(); ++i) {
+    if (mObservers[i] != aExceptObserver) {
+      mObservers[i]->URLSearchParamsUpdated();
+    }
   }
 }
 
-void
-URLSearchParams::Invalidate()
-{
-  mValid = false;
-}
-
 } // namespace dom
 } // namespace mozilla
--- a/dom/base/URLSearchParams.h
+++ b/dom/base/URLSearchParams.h
@@ -18,34 +18,28 @@ namespace mozilla {
 namespace dom {
 
 class URLSearchParamsObserver : public nsISupports
 {
 public:
   virtual ~URLSearchParamsObserver() {}
 
   virtual void URLSearchParamsUpdated() = 0;
-  virtual void URLSearchParamsNeedsUpdates() = 0;
 };
 
 class URLSearchParams MOZ_FINAL : public nsISupports,
                                   public nsWrapperCache
 {
 public:
   NS_DECL_CYCLE_COLLECTING_ISUPPORTS
   NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(URLSearchParams)
 
   URLSearchParams();
   ~URLSearchParams();
 
-  bool HasURLAssociated() const
-  {
-    return !!mObserver;
-  }
-
   // WebIDL methods
   nsISupports* GetParentObject() const
   {
     return nullptr;
   }
 
   virtual JSObject*
   WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope) MOZ_OVERRIDE;
@@ -53,28 +47,21 @@ public:
   static already_AddRefed<URLSearchParams>
   Constructor(const GlobalObject& aGlobal, const nsAString& aInit,
               ErrorResult& aRv);
 
   static already_AddRefed<URLSearchParams>
   Constructor(const GlobalObject& aGlobal, URLSearchParams& aInit,
               ErrorResult& aRv);
 
-  void ParseInput(const nsACString& aInput);
-
-  void CopyFromURLSearchParams(URLSearchParams& aSearchParams);
-
-  void SetObserver(URLSearchParamsObserver* aObserver);
+  void ParseInput(const nsACString& aInput,
+                  URLSearchParamsObserver* aObserver);
 
-  void Invalidate();
-
-  bool IsValid() const
-  {
-    return mValid;
-  }
+  void AddObserver(URLSearchParamsObserver* aObserver);
+  void RemoveObserver(URLSearchParamsObserver* aObserver);
 
   void Serialize(nsAString& aValue) const;
 
   void Get(const nsAString& aName, nsString& aRetval);
 
   void GetAll(const nsAString& aName, nsTArray<nsString >& aRetval);
 
   void Set(const nsAString& aName, const nsAString& aValue);
@@ -82,43 +69,37 @@ public:
   void Append(const nsAString& aName, const nsAString& aValue);
 
   bool Has(const nsAString& aName);
 
   void Delete(const nsAString& aName);
 
   void Stringify(nsString& aRetval)
   {
-    Validate();
     Serialize(aRetval);
   }
 
 private:
   void AppendInternal(const nsAString& aName, const nsAString& aValue);
 
   void DeleteAll();
 
   void DecodeString(const nsACString& aInput, nsACString& aOutput);
 
-  void NotifyObserver();
+  void NotifyObservers(URLSearchParamsObserver* aExceptObserver);
 
   static PLDHashOperator
   CopyEnumerator(const nsAString& aName, nsTArray<nsString>* aArray,
                  void *userData);
 
   static PLDHashOperator
   SerializeEnumerator(const nsAString& aName, nsTArray<nsString>* aArray,
                       void *userData);
 
-  void
-  Validate();
-
   nsClassHashtable<nsStringHashKey, nsTArray<nsString>> mSearchParams;
 
-  nsRefPtr<URLSearchParamsObserver> mObserver;
-
-  bool mValid;
+  nsTArray<nsRefPtr<URLSearchParamsObserver>> mObservers;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #endif /* mozilla_dom_URLSearchParams_h */
--- a/dom/base/test/test_urlSearchParams.html
+++ b/dom/base/test/test_urlSearchParams.html
@@ -132,17 +132,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     is(url.href, 'http://www.example.net/?foo=bar', 'URL right');
 
     url.searchParams = null;
     is(url.searchParams.get('foo'), 'bar', "URL.searchParams.get('foo')");
     is(url.href, 'http://www.example.net/?foo=bar', 'URL right');
 
     var url2 = new URL('http://www.example.net?e=f');
     url.searchParams = url2.searchParams;
-    isnot(url.searchParams, url2.searchParams, "URL.searchParams is not the same object");
+    is(url.searchParams, url2.searchParams, "URL.searchParams is not the same object");
     is(url.searchParams.get('e'), 'f', "URL.searchParams.get('e')");
 
     url.href = "http://www.example.net?bar=foo";
     is(url.searchParams.get('bar'), 'foo', "URL.searchParams.get('bar')");
 
     runTest();
   }
 
@@ -165,17 +165,17 @@ https://bugzilla.mozilla.org/show_bug.cg
     is(e.href, 'http://www.example.net/?foo=bar', 'e is right');
 
     e.searchParams = null;
     is(e.searchParams.get('foo'), 'bar', "e.searchParams.get('foo')");
     is(e.href, 'http://www.example.net/?foo=bar', 'e is right');
 
     var url2 = new URL('http://www.example.net?e=f');
     e.searchParams = url2.searchParams;
-    isnot(e.searchParams, url2.searchParams, "e.searchParams is not the same object");
+    is(e.searchParams, url2.searchParams, "e.searchParams is not the same object");
     is(e.searchParams.get('e'), 'f', "e.searchParams.get('e')");
 
     e.href = "http://www.example.net?bar=foo";
     is(e.searchParams.get('bar'), 'foo', "e.searchParams.get('bar')");
 
     e.setAttribute('href', "http://www.example.net?bar2=foo2");
     is(e.searchParams.get('bar2'), 'foo2', "e.searchParams.get('bar2')");
 
@@ -198,24 +198,64 @@ https://bugzilla.mozilla.org/show_bug.cg
 
       var url2 = new URL(url.href);
       is(url2.searchParams.get('a'), encoding[i][0], 'a is still there');
     }
 
     runTest();
   }
 
+  function testMultiURL() {
+    var a = new URL('http://www.example.net?a=b&c=d');
+    var b = new URL('http://www.example.net?e=f');
+    var c = document.createElement('a');
+    var d = document.createElement('area');
+    ok(a.searchParams.has('a'), "a.searchParams.has('a')");
+    ok(a.searchParams.has('c'), "a.searchParams.has('c')");
+    ok(b.searchParams.has('e'), "b.searchParams.has('e')");
+    ok(c.searchParams, "c.searchParams");
+    ok(d.searchParams, "d.searchParams");
+
+    var u = new URLSearchParams();
+    a.searchParams = b.searchParams = c.searchParams = d.searchParams = u;
+    is(a.searchParams, u, "a.searchParams === u");
+    is(b.searchParams, u, "b.searchParams === u");
+    is(c.searchParams, u, "c.searchParams === u");
+    is(d.searchParams, u, "d.searchParams === u");
+    ok(!a.searchParams.has('a'), "!a.searchParams.has('a')");
+    ok(!a.searchParams.has('c'), "!a.searchParams.has('c')");
+    ok(!b.searchParams.has('e'), "!b.searchParams.has('e')");
+
+    u.append('foo', 'bar');
+    is(a.searchParams.get('foo'), 'bar', "a has foo=bar");
+    is(b.searchParams.get('foo'), 'bar', "b has foo=bar");
+    is(c.searchParams.get('foo'), 'bar', "c has foo=bar");
+    is(d.searchParams.get('foo'), 'bar', "d has foo=bar");
+    is(a + "", b + "", "stringify a == b");
+    is(c.searchParams + "", b.searchParams + "", "stringify c.searchParams == b.searchParams");
+    is(d.searchParams + "", b.searchParams + "", "stringify d.searchParams == b.searchParams");
+
+    a.search = "?bar=foo";
+    is(a.searchParams.get('bar'), 'foo', "a has bar=foo");
+    is(b.searchParams.get('bar'), 'foo', "b has bar=foo");
+    is(c.searchParams.get('bar'), 'foo', "c has bar=foo");
+    is(d.searchParams.get('bar'), 'foo', "d has bar=foo");
+
+    runTest();
+  }
+
   var tests = [
     testSimpleURLSearchParams,
     testCopyURLSearchParams,
     testParserURLSearchParams,
     testURL,
     function() { testElement(document.getElementById('anchor')) },
     function() { testElement(document.getElementById('area')) },
-    testEncoding
+    testEncoding,
+    testMultiURL
   ];
 
   function runTest() {
     if (!tests.length) {
       SimpleTest.finish();
       return;
     }
 
--- a/dom/bindings/BindingUtils.cpp
+++ b/dom/bindings/BindingUtils.cpp
@@ -230,17 +230,17 @@ ErrorResult::ReportJSExceptionFromJSImpl
     NS_RUNTIMEABORT("We stored a non-DOMError exception!");
   }
 
   nsString message;
   domError->GetMessage(message);
 
   JS_ReportError(aCx, "%hs", message.get());
   JS_RemoveValueRoot(aCx, &mJSException);
-  
+
   // We no longer have a useful exception but we do want to signal that an error
   // occured.
   mResult = NS_ERROR_FAILURE;
 }
 
 void
 ErrorResult::StealJSException(JSContext* cx,
                               JS::MutableHandle<JS::Value> value)
@@ -1568,17 +1568,18 @@ NativeToString(JSContext* cx, JS::Handle
     JSAutoCompartment ac(cx, obj);
     if (toStringDesc.object()) {
       JS::Rooted<JS::Value> toString(cx, toStringDesc.value());
       if (!JS_WrapValue(cx, &toString)) {
         return false;
       }
       MOZ_ASSERT(JS_ObjectIsCallable(cx, &toString.toObject()));
       JS::Rooted<JS::Value> toStringResult(cx);
-      if (JS_CallFunctionValue(cx, obj, toString, JS::EmptyValueArray, &toStringResult)) {
+      if (JS_CallFunctionValue(cx, obj, toString, JS::HandleValueArray::empty(),
+                               &toStringResult)) {
         str = toStringResult.toString();
       } else {
         str = nullptr;
       }
     } else {
       const js::Class* clasp = js::GetObjectClass(obj);
       if (IsDOMClass(clasp)) {
         str = JS_NewStringCopyZ(cx, clasp->name);
--- a/dom/bindings/Codegen.py
+++ b/dom/bindings/Codegen.py
@@ -11346,17 +11346,17 @@ class CallbackMethod(CallbackMember):
             "declThis": self.getThisDecl(),
             "thisVal": self.getThisVal(),
             "declCallable": self.getCallableDecl(),
             "callGuard": self.getCallGuard()
             }
         if self.argCount > 0:
             replacements["args"] = "JS::HandleValueArray::subarray(argv, 0, argc)"
         else:
-            replacements["args"] = "JS::EmptyValueArray"
+            replacements["args"] = "JS::HandleValueArray::empty()"
         return string.Template("${declCallable}${declThis}"
                 "if (${callGuard}!JS::Call(cx, ${thisVal}, callable,\n"
                 "              ${args}, &rval)) {\n"
                 "  aRv.Throw(NS_ERROR_UNEXPECTED);\n"
                 "  return${errorReturn};\n"
                 "}\n").substitute(replacements)
 
 class CallCallback(CallbackMethod):
--- a/dom/indexedDB/IndexedDatabaseManager.cpp
+++ b/dom/indexedDB/IndexedDatabaseManager.cpp
@@ -18,16 +18,17 @@
 #include "mozilla/CondVar.h"
 #include "mozilla/ContentEvents.h"
 #include "mozilla/dom/ErrorEventBinding.h"
 #include "mozilla/dom/quota/OriginOrPatternString.h"
 #include "mozilla/dom/quota/QuotaManager.h"
 #include "mozilla/dom/quota/Utilities.h"
 #include "mozilla/dom/TabContext.h"
 #include "mozilla/Services.h"
+#include "mozilla/Preferences.h"
 #include "mozilla/storage.h"
 #include "nsContentUtils.h"
 #include "nsEventDispatcher.h"
 #include "nsThreadUtils.h"
 
 #include "IDBEvents.h"
 #include "IDBFactory.h"
 #include "IDBKeyRange.h"
@@ -203,17 +204,17 @@ IndexedDatabaseManager::GetOrCreate()
   if (IsClosed()) {
     NS_ERROR("Calling GetOrCreate() after shutdown!");
     return nullptr;
   }
 
   if (!gDBManager) {
     sIsMainProcess = XRE_GetProcessType() == GeckoProcessType_Default;
 
-    if (sIsMainProcess) {
+    if (sIsMainProcess && Preferences::GetBool("disk_space_watcher.enabled", false)) {
       // See if we're starting up in low disk space conditions.
       nsCOMPtr<nsIDiskSpaceWatcher> watcher =
         do_GetService(DISKSPACEWATCHER_CONTRACTID);
       if (watcher) {
         bool isDiskFull;
         if (NS_SUCCEEDED(watcher->GetIsDiskFull(&isDiskFull))) {
           sLowDiskSpaceMode = isDiskFull;
         }
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -1185,17 +1185,22 @@ ContentParent::ActorDestroy(ActorDestroy
 
     if (ppm) {
       ppm->Disconnect();
     }
 
     // Tell the memory reporter manager that this ContentParent is going away.
     nsRefPtr<nsMemoryReporterManager> mgr =
         nsMemoryReporterManager::GetOrCreate();
-    if (mgr) {
+#ifdef MOZ_NUWA_PROCESS
+    bool isMemoryChild = !IsNuwaProcess();
+#else
+    bool isMemoryChild = true;
+#endif
+    if (mgr && isMemoryChild) {
         mgr->DecrementNumChildProcesses();
     }
 
     // remove the global remote preferences observers
     Preferences::RemoveObserver(this, "");
 
     RecvRemoveGeolocationListener();
 
@@ -1400,21 +1405,23 @@ ContentParent::ContentParent(mozIApplica
 
     NS_ASSERTION(NS_IsMainThread(), "Wrong thread!");
     mSubprocess = new GeckoChildProcessHost(GeckoProcessType_Content,
                                             aOSPrivileges);
     mSubprocess->SetSandboxEnabled(ShouldSandboxContentProcesses());
 
     IToplevelProtocol::SetTransport(mSubprocess->GetChannel());
 
-    // Tell the memory reporter manager that this ContentParent exists.
-    nsRefPtr<nsMemoryReporterManager> mgr =
-        nsMemoryReporterManager::GetOrCreate();
-    if (mgr) {
-        mgr->IncrementNumChildProcesses();
+    if (!aIsNuwaProcess) {
+        // Tell the memory reporter manager that this ContentParent exists.
+        nsRefPtr<nsMemoryReporterManager> mgr =
+            nsMemoryReporterManager::GetOrCreate();
+        if (mgr) {
+            mgr->IncrementNumChildProcesses();
+        }
     }
 
     std::vector<std::string> extraArgs;
     if (aIsNuwaProcess) {
         extraArgs.push_back("-nuwa");
     }
     mSubprocess->LaunchAndWaitForProcessHandle(extraArgs);
 
@@ -1466,16 +1473,23 @@ ContentParent::ContentParent(ContentPare
     const FileDescriptor* fd = FindFdProtocolFdMapping(aFds, GetProtocolId());
 
     NS_ASSERTION(fd != nullptr, "IPC Channel for PContent is necessary!");
     mSubprocess = new GeckoExistingProcessHost(GeckoProcessType_Content,
                                                aPid,
                                                *fd,
                                                aOSPrivileges);
 
+    // Tell the memory reporter manager that this ContentParent exists.
+    nsRefPtr<nsMemoryReporterManager> mgr =
+        nsMemoryReporterManager::GetOrCreate();
+    if (mgr) {
+        mgr->IncrementNumChildProcesses();
+    }
+
     mSubprocess->LaunchAndWaitForProcessHandle();
 
     // Clone actors routed by aTemplate for this instance.
     IToplevelProtocol::SetTransport(mSubprocess->GetChannel());
     ProtocolCloneContext cloneContext;
     cloneContext.SetContentParent(this);
     CloneManagees(aTemplate, &cloneContext);
     CloneOpenedToplevels(aTemplate, aFds, aPid, &cloneContext);
--- a/dom/plugins/base/nsJSNPRuntime.cpp
+++ b/dom/plugins/base/nsJSNPRuntime.cpp
@@ -1601,17 +1601,17 @@ NPObjWrapper_Convert(JSContext *cx, JS::
   // methods, none of which are nullary, so the JS-reflected method will behave
   // poorly when called with no arguments.  We work around this problem by
   // giving plugins a [[DefaultValue]] which uses only toString and not valueOf.
 
   JS::Rooted<JS::Value> v(cx, JSVAL_VOID);
   if (!JS_GetProperty(cx, obj, "toString", &v))
     return false;
   if (!JSVAL_IS_PRIMITIVE(v) && JS_ObjectIsCallable(cx, JSVAL_TO_OBJECT(v))) {
-    if (!JS_CallFunctionValue(cx, obj, v, JS::EmptyValueArray, vp))
+    if (!JS_CallFunctionValue(cx, obj, v, JS::HandleValueArray::empty(), vp))
       return false;
     if (JSVAL_IS_PRIMITIVE(vp))
       return true;
   }
 
   JS_ReportErrorNumber(cx, js_GetErrorMessage, nullptr, JSMSG_CANT_CONVERT_TO,
                        JS_GetClass(obj)->name,
                        hint == JSTYPE_VOID
--- a/dom/src/json/nsJSON.cpp
+++ b/dom/src/json/nsJSON.cpp
@@ -215,17 +215,17 @@ nsJSON::EncodeInternal(JSContext* cx, co
    * perfectly fine for GetMethod to fail
    */
   JS::Rooted<JS::Value> val(cx, aValue);
   JS::Rooted<JS::Value> toJSON(cx);
   if (JS_GetProperty(cx, obj, "toJSON", &toJSON) &&
       toJSON.isObject() &&
       JS_ObjectIsCallable(cx, &toJSON.toObject())) {
     // If toJSON is implemented, it must not throw
-    if (!JS_CallFunctionValue(cx, obj, toJSON, JS::EmptyValueArray, &val)) {
+    if (!JS_CallFunctionValue(cx, obj, toJSON, JS::HandleValueArray::empty(), &val)) {
       if (JS_IsExceptionPending(cx))
         // passing NS_OK will throw the pending exception
         return NS_OK;
 
       // No exception, but still failed
       return NS_ERROR_FAILURE;
     }
 
@@ -477,17 +477,17 @@ NS_NewJSON(nsISupports* aOuter, REFNSIID
   NS_ADDREF(json);
   *aResult = json;
 
   return NS_OK;
 }
 
 nsJSONListener::nsJSONListener(JSContext *cx, JS::Value *rootVal,
                                bool needsConverter)
-  : mNeedsConverter(needsConverter), 
+  : mNeedsConverter(needsConverter),
     mCx(cx),
     mRootVal(rootVal)
 {
 }
 
 nsJSONListener::~nsJSONListener()
 {
 }
@@ -546,17 +546,17 @@ nsJSONListener::OnDataAvailable(nsIReque
   if (mNeedsConverter && mSniffBuffer.Length() < 4) {
     uint32_t readCount = (aLength < 4) ? aLength : 4;
     rv = NS_ConsumeStream(aStream, readCount, mSniffBuffer);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (mSniffBuffer.Length() < 4)
       return NS_OK;
   }
-  
+
   char buffer[JSON_STREAM_BUFSIZE];
   unsigned long bytesRemaining = aLength - mSniffBuffer.Length();
   while (bytesRemaining) {
     unsigned int bytesRead;
     rv = aStream->Read(buffer,
                        std::min((unsigned long)sizeof(buffer), bytesRemaining),
                        &bytesRead);
     NS_ENSURE_SUCCESS(rv, rv);
--- a/dom/tests/mochitest/webcomponents/test_template.html
+++ b/dom/tests/mochitest/webcomponents/test_template.html
@@ -45,16 +45,24 @@ ok(!document.getElementById("insidetempl
 is(templateEl.childNodes.length, 0, "Template element should have no children.");
 is(templateEl.content.childNodes.length, 1, "Template content should have 1 child <div>.");
 
 // Make sure that template is owned by different document.
 ok(templateEl.content.ownerDocument != templateEl.ownerDocument, "Template should be in a different document because the current document has a browsing context.");
 var otherTemplateEl = document.getElementById("first");
 is(templateEl.content.ownerDocument, otherTemplateEl.content.ownerDocument, "Template contents within the same document should be owned by the same template contents owner.");
 
+var htmlDoc = document.implementation.createHTMLDocument();
+var otherDocTemplateEl = htmlDoc.createElement("template");
+isnot(otherDocTemplateEl.content.ownerDocument, htmlDoc, "Template content owner should be a new document.");
+
+var templateOwnerDoc = otherDocTemplateEl.content.ownerDocument;
+var docCreatedTemplateEl = templateOwnerDoc.createElement("template");
+is(docCreatedTemplateEl.content.ownerDocument, templateOwnerDoc, "Template content owner of template elements created by a template document should be the template document.");
+
 // Tests for XMLSerializer
 templateEl = document.getElementById("justtemplate");
 var serializer = new XMLSerializer();
 is(serializer.serializeToString(templateEl), '<template xmlns="http://www.w3.org/1999/xhtml" id="justtemplate"></template>', "XMLSerializer should serialize template element.");
 
 templateEl = document.getElementById("first");
 is(serializer.serializeToString(templateEl), '<template xmlns="http://www.w3.org/1999/xhtml" id="first">Hi<template>Bye</template></template>', "XMLSerializer should serialize template content.");
 
--- a/dom/wappush/src/gonk/CpPduHelper.jsm
+++ b/dom/wappush/src/gonk/CpPduHelper.jsm
@@ -182,17 +182,16 @@ this.Authenticator = {
 
     let authInfo = {
       pass: false,
       checked: false,
       sec: AUTH_SEC_TYPE[sec],
       mac: mac.toUpperCase(),
       data: wbxml
     };
-    authInfo.data.length = wbxml.length;
 
     switch (authInfo.sec) {
       case "NETWPIN":
         let key = getNetworkPin();
         authInfo.pass = this.isValid(wbxml, key, authInfo.mac);
         authInfo.checked = true;
         return authInfo;
 
--- a/dom/workers/URL.cpp
+++ b/dom/workers/URL.cpp
@@ -610,19 +610,17 @@ URL::SetHref(const nsAString& aHref, Err
   nsRefPtr<SetterRunnable> runnable =
     new SetterRunnable(mWorkerPrivate, SetterRunnable::SetterHref, aHref,
                        mURLProxy, aRv);
 
   if (!runnable->Dispatch(mWorkerPrivate->GetJSContext())) {
     JS_ReportPendingException(mWorkerPrivate->GetJSContext());
   }
 
-  if (mSearchParams) {
-    mSearchParams->Invalidate();
-  }
+  UpdateURLSearchParams();
 }
 
 void
 URL::GetOrigin(nsString& aOrigin) const
 {
   nsRefPtr<GetterRunnable> runnable =
     new GetterRunnable(mWorkerPrivate, GetterRunnable::GetterOrigin, aOrigin,
                        mURLProxy);
@@ -818,20 +816,17 @@ URL::GetSearch(nsString& aSearch) const
     JS_ReportPendingException(mWorkerPrivate->GetJSContext());
   }
 }
 
 void
 URL::SetSearch(const nsAString& aSearch)
 {
   SetSearchInternal(aSearch);
-
-  if (mSearchParams) {
-    mSearchParams->Invalidate();
-  }
+  UpdateURLSearchParams();
 }
 
 void
 URL::SetSearchInternal(const nsAString& aSearch)
 {
   ErrorResult rv;
   nsRefPtr<SetterRunnable> runnable =
     new SetterRunnable(mWorkerPrivate, SetterRunnable::SetterSearch,
@@ -851,26 +846,22 @@ URL::GetSearchParams()
 
 void
 URL::SetSearchParams(URLSearchParams* aSearchParams)
 {
   if (!aSearchParams) {
     return;
   }
 
-  if (!aSearchParams->HasURLAssociated()) {
-    MOZ_ASSERT(aSearchParams->IsValid());
-
-    mSearchParams = aSearchParams;
-    mSearchParams->SetObserver(this);
-  } else {
-    CreateSearchParamsIfNeeded();
-    mSearchParams->CopyFromURLSearchParams(*aSearchParams);
+  if (mSearchParams) {
+    mSearchParams->RemoveObserver(this);
   }
 
+  mSearchParams = aSearchParams;
+  mSearchParams->AddObserver(this);
 
   nsString search;
   mSearchParams->Serialize(search);
   SetSearchInternal(search);
 }
 
 void
 URL::GetHash(nsString& aHash) const
@@ -946,36 +937,36 @@ URL::RevokeObjectURL(const GlobalObject&
   if (!runnable->Dispatch(cx)) {
     JS_ReportPendingException(cx);
   }
 }
 
 void
 URL::URLSearchParamsUpdated()
 {
-  MOZ_ASSERT(mSearchParams && mSearchParams->IsValid());
+  MOZ_ASSERT(mSearchParams);
 
   nsString search;
   mSearchParams->Serialize(search);
   SetSearchInternal(search);
 }
 
 void
-URL::URLSearchParamsNeedsUpdates()
+URL::UpdateURLSearchParams()
 {
-  MOZ_ASSERT(mSearchParams);
-
-  nsString search;
-  GetSearch(search);
-  mSearchParams->ParseInput(NS_ConvertUTF16toUTF8(Substring(search, 1)));
+  if (mSearchParams) {
+    nsString search;
+    GetSearch(search);
+    mSearchParams->ParseInput(NS_ConvertUTF16toUTF8(Substring(search, 1)), this);
+  }
 }
 
 void
 URL::CreateSearchParamsIfNeeded()
 {
   if (!mSearchParams) {
     mSearchParams = new URLSearchParams();
-    mSearchParams->SetObserver(this);
-    mSearchParams->Invalidate();
+    mSearchParams->AddObserver(this);
+    UpdateURLSearchParams();
   }
 }
 
 END_WORKERS_NAMESPACE
--- a/dom/workers/URL.h
+++ b/dom/workers/URL.h
@@ -114,28 +114,29 @@ public:
 
   void Stringify(nsString& aRetval) const
   {
     GetHref(aRetval);
   }
 
   // IURLSearchParamsObserver
   void URLSearchParamsUpdated() MOZ_OVERRIDE;
-  void URLSearchParamsNeedsUpdates() MOZ_OVERRIDE;
 
 private:
   URLProxy* GetURLProxy() const
   {
     return mURLProxy;
   }
 
   void CreateSearchParamsIfNeeded();
 
   void SetSearchInternal(const nsAString& aSearch);
 
+  void UpdateURLSearchParams();
+
   WorkerPrivate* mWorkerPrivate;
   nsRefPtr<URLProxy> mURLProxy;
   nsRefPtr<URLSearchParams> mSearchParams;
 };
 
 END_WORKERS_NAMESPACE
 
 #endif /* mozilla_dom_workers_url_h__ */
--- a/dom/workers/test/urlSearchParams_worker.js
+++ b/dom/workers/test/urlSearchParams_worker.js
@@ -3,21 +3,16 @@ function ok(a, msg) {
   postMessage({type: 'status', status: !!a, msg: a + ": " + msg });
 }
 
 function is(a, b, msg) {
   dump("IS: " + (a===b) + "  =>  " + a + " | " + b + " " + msg + "\n");
   postMessage({type: 'status', status: a === b, msg: a + " === " + b + ": " + msg });
 }
 
-function isnot(a, b, msg) {
-  dump("ISNOT: " + (a!==b) + "  =>  " + a + " | " + b + " " + msg + "\n");
-  postMessage({type: 'status', status: a !== b, msg: a + " !== " + b + ": " + msg });
-}
-
 onmessage = function() {
   status = false;
   try {
     if ((URLSearchParams instanceof Object)) {
       status = true;
     }
   } catch(e) {
   }
@@ -129,17 +124,17 @@ onmessage = function() {
     is(url.href, 'http://www.example.net/?foo=bar', 'URL right');
 
     url.searchParams = null;
     is(url.searchParams.get('foo'), 'bar', "URL.searchParams.get('foo')");
     is(url.href, 'http://www.example.net/?foo=bar', 'URL right');
 
     var url2 = new URL('http://www.example.net?e=f');
     url.searchParams = url2.searchParams;
-    isnot(url.searchParams, url2.searchParams, "URL.searchParams is not the same object");
+    is(url.searchParams, url2.searchParams, "URL.searchParams is not the same object");
     is(url.searchParams.get('e'), 'f', "URL.searchParams.get('e')");
 
     url.href = "http://www.example.net?bar=foo";
     is(url.searchParams.get('bar'), 'foo', "URL.searchParams.get('bar')");
 
     runTest();
   }
 
@@ -159,22 +154,49 @@ onmessage = function() {
 
       var url2 = new URL(url.href);
       is(url2.searchParams.get('a'), encoding[i][0], 'a is still there');
     }
 
     runTest();
   }
 
+  function testMultiURL() {
+    var a = new URL('http://www.example.net?a=b&c=d');
+    var b = new URL('http://www.example.net?e=f');
+    ok(a.searchParams.has('a'), "a.searchParams.has('a')");
+    ok(a.searchParams.has('c'), "a.searchParams.has('c')");
+    ok(b.searchParams.has('e'), "b.searchParams.has('e')");
+
+    var u = new URLSearchParams();
+    a.searchParams = b.searchParams = u;
+    is(a.searchParams, u, "a.searchParams === u");
+    is(b.searchParams, u, "b.searchParams === u");
+    ok(!a.searchParams.has('a'), "!a.searchParams.has('a')");
+    ok(!a.searchParams.has('c'), "!a.searchParams.has('c')");
+    ok(!b.searchParams.has('e'), "!b.searchParams.has('e')");
+
+    u.append('foo', 'bar');
+    is(a.searchParams.get('foo'), 'bar', "a has foo=bar");
+    is(b.searchParams.get('foo'), 'bar', "b has foo=bar");
+    is(a + "", b + "", "stringify a == b");
+
+    a.search = "?bar=foo";
+    is(a.searchParams.get('bar'), 'foo', "a has bar=foo");
+    is(b.searchParams.get('bar'), 'foo', "b has bar=foo");
+
+    runTest();
+  }
   var tests = [
     testSimpleURLSearchParams,
     testCopyURLSearchParams,
     testParserURLSearchParams,
     testURL,
-    testEncoding
+    testEncoding,
+    testMultiURL
   ];
 
   function runTest() {
     if (!tests.length) {
       postMessage({type: 'finish' });
       return;
     }
 
--- a/dom/xbl/nsXBLProtoImplMethod.cpp
+++ b/dom/xbl/nsXBLProtoImplMethod.cpp
@@ -34,34 +34,34 @@ nsXBLProtoImplMethod::~nsXBLProtoImplMet
 {
   MOZ_COUNT_DTOR(nsXBLProtoImplMethod);
 
   if (!IsCompiled()) {
     delete GetUncompiledMethod();
   }
 }
 
-void 
+void
 nsXBLProtoImplMethod::AppendBodyText(const nsAString& aText)
 {
   NS_PRECONDITION(!IsCompiled(),
                   "Must not be compiled when accessing uncompiled method");
 
   nsXBLUncompiledMethod* uncompiledMethod = GetUncompiledMethod();
   if (!uncompiledMethod) {
     uncompiledMethod = new nsXBLUncompiledMethod();
     if (!uncompiledMethod)
       return;
     SetUncompiledMethod(uncompiledMethod);
   }
 
   uncompiledMethod->AppendBodyText(aText);
 }
 
-void 
+void
 nsXBLProtoImplMethod::AddParameter(const nsAString& aText)
 {
   NS_PRECONDITION(!IsCompiled(),
                   "Must not be compiled when accessing uncompiled method");
 
   if (aText.IsEmpty()) {
     NS_WARNING("Empty name attribute in xbl:parameter!");
     return;
@@ -120,17 +120,17 @@ nsXBLProtoImplMethod::InstallMember(JSCo
                                name.Length(), value,
                                nullptr, nullptr, JSPROP_ENUMERATE)) {
       return NS_ERROR_OUT_OF_MEMORY;
     }
   }
   return NS_OK;
 }
 
-nsresult 
+nsresult
 nsXBLProtoImplMethod::CompileMember(const nsCString& aClassStr,
                                     JS::Handle<JSObject*> aClassObject)
 {
   AssertInCompilationScope();
   NS_PRECONDITION(!IsCompiled(),
                   "Trying to compile an already-compiled method");
   NS_PRECONDITION(aClassObject,
                   "Must have class object to compile");
@@ -160,19 +160,19 @@ nsXBLProtoImplMethod::CompileMember(cons
   int32_t paramCount = uncompiledMethod->GetParameterCount();
   char** args = nullptr;
   if (paramCount > 0) {
     args = new char*[paramCount];
     if (!args)
       return NS_ERROR_OUT_OF_MEMORY;
 
     // Add our parameters to our args array.
-    int32_t argPos = 0; 
-    for (nsXBLParameter* curr = uncompiledMethod->mParameters; 
-         curr; 
+    int32_t argPos = 0;
+    for (nsXBLParameter* curr = uncompiledMethod->mParameters;
+         curr;
          curr = curr->mNext) {
       args[argPos] = curr->mName;
       argPos++;
     }
   }
 
   // Get the body
   nsDependentString body;
@@ -330,17 +330,17 @@ nsXBLProtoImplAnonymousMethod::Execute(n
   // Check whether script is enabled.
   bool scriptAllowed = nsContentUtils::GetSecurityManager()->
                          ScriptAllowed(js::GetGlobalForObjectCrossCompartment(method));
 
   bool ok = true;
   if (scriptAllowed) {
     JS::Rooted<JS::Value> retval(cx);
     JS::Rooted<JS::Value> methodVal(cx, JS::ObjectValue(*method));
-    ok = ::JS::Call(cx, thisObject, methodVal, JS::EmptyValueArray, &retval);
+    ok = ::JS::Call(cx, thisObject, methodVal, JS::HandleValueArray::empty(), &retval);
   }
 
   if (!ok) {
     // If a constructor or destructor threw an exception, it doesn't stop
     // anything else.  We just report it.  Note that we need to set aside the
     // frame chain here, since the constructor invocation is not related to
     // whatever is on the stack right now, really.
     nsJSUtils::ReportPendingException(cx);
--- a/gfx/2d/Types.h
+++ b/gfx/2d/Types.h
@@ -241,17 +241,17 @@ struct GradientStop
 
   Float offset;
   Color color;
 };
 
 }
 }
 
-#if defined(XP_WIN) && defined(GKMEDIAS_SHARED_LIBRARY)
+#if defined(XP_WIN) && defined(MOZ_GFX)
 #ifdef GFX2D_INTERNAL
 #define GFX2D_API __declspec(dllexport)
 #else
 #define GFX2D_API __declspec(dllimport)
 #endif
 #else
 #define GFX2D_API
 #endif
--- a/gfx/2d/moz.build
+++ b/gfx/2d/moz.build
@@ -123,17 +123,17 @@ if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'coco
 FAIL_ON_WARNINGS = True
 
 MSVC_ENABLE_PGO = True
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
 FINAL_LIBRARY = 'xul'
 
-for var in ('MOZ_GFX', 'USE_CAIRO', 'GFX2D_INTERNAL', 'MOZ2D_HAS_MOZ_CAIRO'):
+for var in ('USE_CAIRO', 'MOZ2D_HAS_MOZ_CAIRO'):
     DEFINES[var] = True
 
 if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gtk2', 'gtk3', 'gonk', 'qt'):
     DEFINES['MOZ_ENABLE_FREETYPE'] = True
 
 DEFINES['SK_A32_SHIFT'] = 24
 DEFINES['SK_R32_SHIFT'] = 16
 DEFINES['SK_G32_SHIFT'] = 8
--- a/gfx/gl/SharedSurfaceGralloc.cpp
+++ b/gfx/gl/SharedSurfaceGralloc.cpp
@@ -15,33 +15,31 @@
 #include "mozilla/layers/ShadowLayers.h"
 
 #include "ui/GraphicBuffer.h"
 #include "../layers/ipc/ShadowLayers.h"
 #include "ScopedGLHelpers.h"
 
 #include "gfxPlatform.h"
 #include "gfx2DGlue.h"
+#include "gfxPrefs.h"
 
 #define DEBUG_GRALLOC
 #ifdef DEBUG_GRALLOC
 #define DEBUG_PRINT(...) do { printf_stderr(__VA_ARGS__); } while (0)
 #else
 #define DEBUG_PRINT(...) do { } while (0)
 #endif
 
 using namespace mozilla;
 using namespace mozilla::gfx;
 using namespace gl;
 using namespace layers;
 using namespace android;
 
-static bool sForceReadPixelsToFence = false;
-
-
 SurfaceFactory_Gralloc::SurfaceFactory_Gralloc(GLContext* prodGL,
                                                const SurfaceCaps& caps,
                                                layers::ISurfaceAllocator* allocator)
     : SurfaceFactory_GL(prodGL, SharedSurfaceType::Gralloc, caps)
 {
     if (caps.surfaceAllocator) {
         allocator = caps.surfaceAllocator;
     }
@@ -53,24 +51,16 @@ SurfaceFactory_Gralloc::SurfaceFactory_G
 
 SharedSurface_Gralloc*
 SharedSurface_Gralloc::Create(GLContext* prodGL,
                               const GLFormats& formats,
                               const gfx::IntSize& size,
                               bool hasAlpha,
                               ISurfaceAllocator* allocator)
 {
-    static bool runOnce = true;
-    if (runOnce) {
-        sForceReadPixelsToFence = false;
-        mozilla::Preferences::AddBoolVarCache(&sForceReadPixelsToFence,
-                                              "gfx.gralloc.fence-with-readpixels");
-        runOnce = false;
-    }
-
     GLLibraryEGL* egl = &sEGLLibrary;
     MOZ_ASSERT(egl);
 
     DEBUG_PRINT("SharedSurface_Gralloc::Create -------\n");
 
     if (!HasExtensions(egl, prodGL))
         return nullptr;
 
@@ -144,17 +134,17 @@ SharedSurface_Gralloc::~SharedSurface_Gr
 }
 
 void
 SharedSurface_Gralloc::Fence()
 {
     // We should be able to rely on genlock write locks/read locks.
     // But they're broken on some configs, and even a glFinish doesn't
     // work.  glReadPixels seems to, though.
-    if (sForceReadPixelsToFence) {
+    if (gfxPrefs::GrallocFenceWithReadPixels()) {
         mGL->MakeCurrent();
         // read a 1x1 pixel
         unsigned char pixels[4];
         mGL->fReadPixels(0, 0, 1, 1, LOCAL_GL_RGBA, LOCAL_GL_UNSIGNED_BYTE, &pixels[0]);
     }
 }
 
 bool
--- a/gfx/skia/generate_mozbuild.py
+++ b/gfx/skia/generate_mozbuild.py
@@ -61,19 +61,16 @@ if CONFIG['INTEL_ARCHITECTURE'] and CONF
     DEFINES['SK_BUILD_SSSE3'] = 1
 
 if (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android') or \
    (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa') or \
    (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk') or \
    CONFIG['MOZ_WIDGET_QT'] or \
    CONFIG['MOZ_WIDGET_GTK']:
     DEFINES['SK_FONTHOST_DOES_NOT_USE_FONTMGR'] = 1
-
-DEFINES['SKIA_IMPLEMENTATION'] = 1
-DEFINES['GR_IMPLEMENTATION'] = 1
 """
 
 import json
 
 platforms = ['linux', 'mac', 'android', 'win']
 
 custom_includes = {
   'trunk/src/ports/SkAtomics_android.h': True,
--- a/gfx/skia/moz.build
+++ b/gfx/skia/moz.build
@@ -844,11 +844,8 @@ DEFINES['SK_B32_SHIFT'] = 0
 if CONFIG['MOZ_WIDGET_TOOLKIT'] in ('android', 'gtk2', 'gtk3', 'qt', 'gonk', 'cocoa'):
     DEFINES['SK_USE_POSIX_THREADS'] = 1
 
 if CONFIG['INTEL_ARCHITECTURE'] and CONFIG['HAVE_TOOLCHAIN_SUPPORT_MSSSE3']:
     DEFINES['SK_BUILD_SSSE3'] = 1
 
 if (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android') or (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'gonk') or    (CONFIG['MOZ_WIDGET_TOOLKIT'] == 'cocoa') or    CONFIG['MOZ_WIDGET_GTK'] or    CONFIG['MOZ_WIDGET_QT']:
     DEFINES['SK_FONTHOST_DOES_NOT_USE_FONTMGR'] = 1
-
-DEFINES['SKIA_IMPLEMENTATION'] = 1
-DEFINES['GR_IMPLEMENTATION'] = 1
--- a/gfx/thebes/gfxAndroidPlatform.cpp
+++ b/gfx/thebes/gfxAndroidPlatform.cpp
@@ -14,17 +14,17 @@
 #include "gfxFT2FontList.h"
 #include "gfxImageSurface.h"
 #include "mozilla/dom/ContentChild.h"
 #include "nsXULAppAPI.h"
 #include "nsIScreen.h"
 #include "nsIScreenManager.h"
 #include "nsILocaleService.h"
 #include "nsServiceManagerUtils.h"
-
+#include "gfxPrefs.h"
 #include "cairo.h"
 
 #include "ft2build.h"
 #include FT_FREETYPE_H
 #include FT_MODULE_H
 
 using namespace mozilla;
 using namespace mozilla::dom;
@@ -116,17 +116,17 @@ gfxAndroidPlatform::gfxAndroidPlatform()
     screenMgr->GetPrimaryScreen(getter_AddRefs(screen));
     mScreenDepth = 24;
     screen->GetColorDepth(&mScreenDepth);
 
     mOffscreenFormat = mScreenDepth == 16
                        ? gfxImageFormat::RGB16_565
                        : gfxImageFormat::RGB24;
 
-    if (Preferences::GetBool("gfx.android.rgb16.force", false)) {
+    if (gfxPrefs::AndroidRGB16Force()) {
         mOffscreenFormat = gfxImageFormat::RGB16_565;
     }
 
 }
 
 gfxAndroidPlatform::~gfxAndroidPlatform()
 {
     cairo_debug_reset_static_data();
--- a/gfx/thebes/gfxPrefs.h
+++ b/gfx/thebes/gfxPrefs.h
@@ -104,26 +104,28 @@ private:
   // a method accessing a pref already exists. Just add yours in the list.
 
   DECL_GFX_PREF(Once, "apz.fling_friction",                    APZFlingFriction, float, 0.002f);
   DECL_GFX_PREF(Once, "apz.fling_stopped_threshold",           APZFlingStoppedThreshold, float, 0.01f);
   DECL_GFX_PREF(Once, "apz.max_event_acceleration",            APZMaxEventAcceleration, float, 999.0f);
   DECL_GFX_PREF(Once, "apz.max_velocity_pixels_per_ms",        APZMaxVelocity, float, -1.0f);
   DECL_GFX_PREF(Once, "apz.max_velocity_queue_size",           APZMaxVelocityQueueSize, uint32_t, 5);
 
+  DECL_GFX_PREF(Once, "gfx.android.rgb16.force",               AndroidRGB16Force, bool, false);
 #if defined(ANDROID)
   DECL_GFX_PREF(Once, "gfx.apitrace.enabled",                  UseApitrace, bool, false);
 #endif
   DECL_GFX_PREF(Live, "gfx.canvas.azure.accelerated",          CanvasAzureAccelerated, bool, false);
   DECL_GFX_PREF(Once, "gfx.canvas.skiagl.dynamic-cache",       CanvasSkiaGLDynamicCache, bool, false);
   DECL_GFX_PREF(Once, "gfx.canvas.skiagl.cache-size",          CanvasSkiaGLCacheSize, int32_t, 96);
   DECL_GFX_PREF(Once, "gfx.canvas.skiagl.cache-items",         CanvasSkiaGLCacheItems, int32_t, 256);
 
   DECL_GFX_PREF(Once, "gfx.direct2d.disabled",                 Direct2DDisabled, bool, false);
   DECL_GFX_PREF(Once, "gfx.direct2d.force-enabled",            Direct2DForceEnabled, bool, false);
+  DECL_GFX_PREF(Live, "gfx.gralloc.fence-with-readpixels",     GrallocFenceWithReadPixels, bool, false);
   DECL_GFX_PREF(Live, "gfx.layerscope.enabled",                LayerScopeEnabled, bool, false);
   DECL_GFX_PREF(Live, "gfx.layerscope.port",                   LayerScopePort, int32_t, 23456);
   DECL_GFX_PREF(Once, "gfx.work-around-driver-bugs",           WorkAroundDriverBugs, bool, true);
 
   DECL_GFX_PREF(Live, "gl.msaa-level",                         MSAALevel, uint32_t, 2);
 
   DECL_GFX_PREF(Once, "layers.acceleration.disabled",          LayersAccelerationDisabled, bool, false);
   DECL_GFX_PREF(Live, "layers.acceleration.draw-fps",          LayersDrawFPS, bool, true);
--- a/js/public/ProfilingStack.h
+++ b/js/public/ProfilingStack.h
@@ -86,14 +86,17 @@ class ProfileEntry
 
 JS_FRIEND_API(void)
 SetRuntimeProfilingStack(JSRuntime *rt, ProfileEntry *stack, uint32_t *size,
                          uint32_t max);
 
 JS_FRIEND_API(void)
 EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled);
 
+JS_FRIEND_API(void)
+RegisterRuntimeProfilingEventMarker(JSRuntime *rt, void (*fn)(const char *));
+
 JS_FRIEND_API(jsbytecode*)
 ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip);
 
 } // namespace js
 
 #endif  /* js_ProfilingStack_h */
--- a/js/src/jit/BaselineBailouts.cpp
+++ b/js/src/jit/BaselineBailouts.cpp
@@ -1,14 +1,15 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sts=4 et sw=4 tw=99:
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "jsprf.h"
 #include "jit/arm/Simulator-arm.h"
 #include "jit/BaselineIC.h"
 #include "jit/BaselineJIT.h"
 #include "jit/CompileInfo.h"
 #include "jit/IonSpewer.h"
 #include "vm/ArgumentsObject.h"
 
 #include "jsscriptinlines.h"
@@ -970,24 +971,44 @@ InitFromBailout(JSContext *cx, HandleScr
                 }
             } else {
                 opReturnAddr = nativeCodeForPC;
             }
             builder.setResumeAddr(opReturnAddr);
             IonSpew(IonSpew_BaselineBailouts, "      Set resumeAddr=%p", opReturnAddr);
         }
 
-        if (cx->runtime()->spsProfiler.enabled() && blFrame->hasPushedSPSFrame()) {
-            // Set PC index to 0 for the innermost frame to match what the
-            // interpreter and Baseline do: they update the SPS pc for
-            // JSOP_CALL ops but set it to 0 when running other ops. Ion code
-            // can set the pc to NullPCIndex and this will confuse SPS when
-            // Baseline calls into the VM at non-CALL ops and re-enters JS.
-            IonSpew(IonSpew_BaselineBailouts, "      Setting PCidx for last frame to 0");
-            cx->runtime()->spsProfiler.updatePC(script, script->code());
+        if (cx->runtime()->spsProfiler.enabled()) {
+            if (blFrame->hasPushedSPSFrame()) {
+                // Set PC index to 0 for the innermost frame to match what the
+                // interpreter and Baseline do: they update the SPS pc for
+                // JSOP_CALL ops but set it to 0 when running other ops. Ion code
+                // can set the pc to NullPCIndex and this will confuse SPS when
+                // Baseline calls into the VM at non-CALL ops and re-enters JS.
+                IonSpew(IonSpew_BaselineBailouts, "      Setting PCidx for last frame to 0");
+                cx->runtime()->spsProfiler.updatePC(script, script->code());
+            }
+
+            // Register bailout with profiler.
+            const char *filename = script->filename();
+            if (filename == nullptr)
+                filename = "<unknown>";
+            unsigned len = strlen(filename) + 200;
+            char *buf = js_pod_malloc<char>(len);
+            if (buf == nullptr)
+                return false;
+            JS_snprintf(buf, len, "%s %s %s on line %d of %s:%d",
+                                  BailoutKindString(bailoutKind),
+                                  resumeAfter ? "after" : "at",
+                                  js_CodeName[op],
+                                  int(PCToLineNumber(script, pc)),
+                                  filename,
+                                  int(script->lineno()));
+            cx->runtime()->spsProfiler.markEvent(buf);
+            js_free(buf);
         }
 
         return true;
     }
 
     *callPC = pc;
 
     // Write out descriptor of BaselineJS frame.
--- a/js/src/jit/CodeGenerator.cpp
+++ b/js/src/jit/CodeGenerator.cpp
@@ -8,16 +8,17 @@
 
 #include "mozilla/Assertions.h"
 #include "mozilla/Attributes.h"
 #include "mozilla/DebugOnly.h"
 
 #include "jslibmath.h"
 #include "jsmath.h"
 #include "jsnum.h"
+#include "jsprf.h"
 
 #include "builtin/Eval.h"
 #include "builtin/TypedObject.h"
 #ifdef JSGC_GENERATIONAL
 # include "gc/Nursery.h"
 #endif
 #include "jit/ExecutionModeInlines.h"
 #include "jit/IonCaches.h"
@@ -6221,16 +6222,29 @@ CodeGenerator::link(JSContext *cx, types
     ionScript->setSkipArgCheckEntryOffset(getSkipArgCheckEntryOffset());
 
     // If SPS is enabled, mark IonScript as having been instrumented with SPS
     if (sps_.enabled())
         ionScript->setHasSPSInstrumentation();
 
     SetIonScript(script, executionMode, ionScript);
 
+    if (cx->runtime()->spsProfiler.enabled()) {
+        const char *filename = script->filename();
+        if (filename == nullptr)
+            filename = "<unknown>";
+        unsigned len = strlen(filename) + 50;
+        char *buf = js_pod_malloc<char>(len);
+        if (!buf)
+            return false;
+        JS_snprintf(buf, len, "Ion compiled %s:%d", filename, (int) script->lineno());
+        cx->runtime()->spsProfiler.markEvent(buf);
+        js_free(buf);
+    }
+
     // In parallel execution mode, when we first compile a script, we
     // don't know that its potential callees are compiled, so set a
     // flag warning that the callees may not be fully compiled.
     if (!callTargets.empty())
         ionScript->setHasUncompiledCallTarget();
 
     invalidateEpilogueData_.fixup(&masm);
     Assembler::patchDataWithValueCheck(CodeLocationLabel(code, invalidateEpilogueData_),
--- a/js/src/jit/Ion.cpp
+++ b/js/src/jit/Ion.cpp
@@ -10,16 +10,17 @@
 #include "mozilla/ThreadLocal.h"
 
 #include "jscompartment.h"
 #include "jsworkers.h"
 #if JS_TRACE_LOGGING
 #include "TraceLogging.h"
 #endif
 
+#include "jsprf.h"
 #include "gc/Marking.h"
 #include "jit/AliasAnalysis.h"
 #include "jit/AsmJSModule.h"
 #include "jit/BacktrackingAllocator.h"
 #include "jit/BaselineFrame.h"
 #include "jit/BaselineInspector.h"
 #include "jit/BaselineJIT.h"
 #include "jit/CodeGenerator.h"
@@ -2616,16 +2617,37 @@ jit::Invalidate(JSContext *cx, const Vec
 }
 
 bool
 jit::Invalidate(JSContext *cx, JSScript *script, ExecutionMode mode, bool resetUses,
                 bool cancelOffThread)
 {
     JS_ASSERT(script->hasIonScript());
 
+    if (cx->runtime()->spsProfiler.enabled()) {
+        // Register invalidation with profiler.
+        // Format of event payload string:
+        //      "<filename>:<lineno>"
+
+        // Get the script filename, if any, and its length.
+        const char *filename = script->filename();
+        if (filename == nullptr)
+            filename = "<unknown>";
+
+        size_t len = strlen(filename) + 20;
+        char *buf = js_pod_malloc<char>(len);
+        if (!buf)
+            return false;
+
+        // Construct the descriptive string.
+        JS_snprintf(buf, len, "Invalidate %s:%llu", filename, script->lineno());
+        cx->runtime()->spsProfiler.markEvent(buf);
+        js_free(buf);
+    }
+
     Vector<types::RecompileInfo> scripts(cx);
 
     switch (mode) {
       case SequentialExecution:
         JS_ASSERT(script->hasIonScript());
         if (!scripts.append(script->ionScript()->recompileInfo()))
             return false;
         break;
--- a/js/src/jit/IonTypes.h
+++ b/js/src/jit/IonTypes.h
@@ -47,17 +47,16 @@ enum BailoutKind
 
     // A bailout caused by invalid assumptions based on Baseline code.
     Bailout_BaselineInfo
 };
 
 static const uint32_t BAILOUT_KIND_BITS = 3;
 static const uint32_t BAILOUT_RESUME_BITS = 1;
 
-#ifdef DEBUG
 inline const char *
 BailoutKindString(BailoutKind kind)
 {
     switch (kind) {
       case Bailout_Normal:
         return "Bailout_Normal";
       case Bailout_ArgumentCheck:
         return "Bailout_ArgumentCheck";
@@ -66,17 +65,16 @@ BailoutKindString(BailoutKind kind)
       case Bailout_ShapeGuard:
         return "Bailout_ShapeGuard";
       case Bailout_BaselineInfo:
         return "Bailout_BaselineInfo";
       default:
         MOZ_ASSUME_UNREACHABLE("Invalid BailoutKind");
     }
 }
-#endif
 
 static const uint32_t ELEMENT_TYPE_BITS = 4;
 static const uint32_t ELEMENT_TYPE_SHIFT = 0;
 static const uint32_t ELEMENT_TYPE_MASK = (1 << ELEMENT_TYPE_BITS) - 1;
 static const uint32_t VECTOR_SCALE_BITS = 2;
 static const uint32_t VECTOR_SCALE_SHIFT = ELEMENT_TYPE_BITS + ELEMENT_TYPE_SHIFT;
 static const uint32_t VECTOR_SCALE_MASK = (1 << VECTOR_SCALE_BITS) - 1;
 
--- a/js/src/jit/MCallOptimize.cpp
+++ b/js/src/jit/MCallOptimize.cpp
@@ -280,31 +280,35 @@ IonBuilder::inlineArray(CallInfo &callIn
 
     if (callInfo.argc() >= 2) {
         // Get the elements vector.
         MElements *elements = MElements::New(alloc(), ins);
         current->add(elements);
 
         // Store all values, no need to initialize the length after each as
         // jsop_initelem_array is doing because we do not expect to bailout
-        // because the memory is supposed to be allocated by now. There is no
-        // need for a post barrier on these writes, as as the MNewAray will use
-        // the nursery if possible, triggering a minor collection if it can't.
+        // because the memory is supposed to be allocated by now.
         MConstant *id = nullptr;
         for (uint32_t i = 0; i < initLength; i++) {
             id = MConstant::New(alloc(), Int32Value(i));
             current->add(id);
 
             MDefinition *value = callInfo.getArg(i);
             if (conversion == types::TemporaryTypeSet::AlwaysConvertToDoubles) {
                 MInstruction *valueDouble = MToDouble::New(alloc(), value);
                 current->add(valueDouble);
                 value = valueDouble;
             }
 
+            // There is normally no need for a post barrier on these writes
+            // because the new array will be in the nursery. However, this
+            // assumption is volated if we specifically requested pre-tenuring.
+            if (ins->initialHeap() == gc::TenuredHeap)
+                current->add(MPostWriteBarrier::New(alloc(), ins, value));
+
             MStoreElement *store = MStoreElement::New(alloc(), elements, id, value,
                                                       /* needsHoleCheck = */ false);
             current->add(store);
         }
 
         // Update the length.
         MSetInitializedLength *length = MSetInitializedLength::New(alloc(), elements, id);
         current->add(length);
--- a/js/src/jsapi-tests/moz.build
+++ b/js/src/jsapi-tests/moz.build
@@ -63,16 +63,17 @@ UNIFIED_SOURCES += [
     'testScriptObject.cpp',
     'testSetProperty.cpp',
     'testSourcePolicy.cpp',
     'testStringBuffer.cpp',
     'testStructuredClone.cpp',
     'testToIntWidth.cpp',
     'testTrap.cpp',
     'testTypedArrays.cpp',
+    'testUncaughtError.cpp',
     'testUTF8.cpp',
     'testXDR.cpp',
 ]
 
 if CONFIG['ENABLE_ION']:
     UNIFIED_SOURCES += [
         'testJitRValueAlloc.cpp',
     ]
--- a/js/src/jsapi-tests/testBindCallable.cpp
+++ b/js/src/jsapi-tests/testBindCallable.cpp
@@ -16,17 +16,17 @@ BEGIN_TEST(test_BindCallable)
 
   JS::RootedObject funcObj(cx, JSVAL_TO_OBJECT(func));
   JS::RootedObject vObj(cx, JSVAL_TO_OBJECT(v));
   JSObject* newCallable = JS_BindCallable(cx, funcObj, vObj);
   CHECK(newCallable);
 
   JS::RootedValue retval(cx);
   JS::RootedValue fun(cx, JS::ObjectValue(*newCallable));
-  bool called = JS_CallFunctionValue(cx, JS::NullPtr(), fun, JS::EmptyValueArray, &retval);
+  bool called = JS_CallFunctionValue(cx, JS::NullPtr(), fun, JS::HandleValueArray::empty(), &retval);
   CHECK(called);
 
   CHECK(JSVAL_IS_INT(retval));
 
   CHECK(JSVAL_TO_INT(retval) == 1717);
   return true;
 }
 END_TEST(test_BindCallable)
--- a/js/src/jsapi-tests/testCallNonGenericMethodOnProxy.cpp
+++ b/js/src/jsapi-tests/testCallNonGenericMethodOnProxy.cpp
@@ -51,17 +51,18 @@ BEGIN_TEST(test_CallNonGenericMethodOnPr
   CHECK(customA);
   JS_SetReservedSlot(customA, CUSTOM_SLOT, Int32Value(17));
 
   JS::RootedFunction customMethodA(cx, JS_NewFunction(cx, CustomMethod, 0, 0,
                                                       customA, "customMethodA"));
   CHECK(customMethodA);
 
   JS::RootedValue rval(cx);
-  CHECK(JS_CallFunction(cx, customA, customMethodA, JS::EmptyValueArray, &rval));
+  CHECK(JS_CallFunction(cx, customA, customMethodA, JS::HandleValueArray::empty(),
+                        &rval));
   CHECK_SAME(rval, Int32Value(17));
 
   // Now create the second global object and compartment...
   {
     JS::RootedObject globalB(cx, JS_NewGlobalObject(cx, getGlobalClass(), nullptr, JS::FireOnNewGlobalHook));
     CHECK(globalB);
 
     // ...and enter it.
@@ -69,22 +70,24 @@ BEGIN_TEST(test_CallNonGenericMethodOnPr
     JS::RootedObject customB(cx, JS_NewObject(cx, &CustomClass, JS::NullPtr(), JS::NullPtr()));
     CHECK(customB);
     JS_SetReservedSlot(customB, CUSTOM_SLOT, Int32Value(42));
 
     JS::RootedFunction customMethodB(cx, JS_NewFunction(cx, CustomMethod, 0, 0, customB, "customMethodB"));
     CHECK(customMethodB);
 
     JS::RootedValue rval(cx);
-    CHECK(JS_CallFunction(cx, customB, customMethodB, JS::EmptyValueArray, &rval));
+    CHECK(JS_CallFunction(cx, customB, customMethodB, JS::HandleValueArray::empty(),
+                          &rval));
     CHECK_SAME(rval, Int32Value(42));
 
     JS::RootedObject wrappedCustomA(cx, customA);
     CHECK(JS_WrapObject(cx, &wrappedCustomA));
 
     JS::RootedValue rval2(cx);
-    CHECK(JS_CallFunction(cx, wrappedCustomA, customMethodB, JS::EmptyValueArray, &rval2));
+    CHECK(JS_CallFunction(cx, wrappedCustomA, customMethodB, JS::HandleValueArray::empty(),
+                          &rval2));
     CHECK_SAME(rval, Int32Value(42));
   }
 
   return true;
 }
 END_TEST(test_CallNonGenericMethodOnProxy)
--- a/js/src/jsapi-tests/testChromeBuffer.cpp
+++ b/js/src/jsapi-tests/testChromeBuffer.cpp
@@ -30,17 +30,17 @@ CallTrusted(JSContext *cx, unsigned argc
 
     if (!JS_SaveFrameChain(cx))
         return false;
 
     bool ok = false;
     {
         JSAutoCompartment ac(cx, trusted_glob);
         JS::RootedValue funVal(cx, JS::ObjectValue(*trusted_fun));
-        ok = JS_CallFunctionValue(cx, JS::NullPtr(), funVal, JS::EmptyValueArray, args.rval());
+        ok = JS_CallFunctionValue(cx, JS::NullPtr(), funVal, JS::HandleValueArray::empty(), args.rval());
     }
     JS_RestoreFrameChain(cx);
     return ok;
 }
 
 BEGIN_TEST(testChromeBuffer)
 {
     JS_SetTrustedPrincipals(rt, &system_principals);
--- a/js/src/jsapi-tests/testClassGetter.cpp
+++ b/js/src/jsapi-tests/testClassGetter.cpp
@@ -58,15 +58,16 @@ BEGIN_TEST(testClassGetter_isCalled)
 {
     CHECK(JS_InitClass(cx, global, js::NullPtr(), &ptestClass, PTest, 0,
                        nullptr, ptestFunctions, nullptr, nullptr));
 
     EXEC("function check() { var o = new PTest(); o.test_fn(); o.test_value1; o.test_value2; o.test_value1; }");
 
     for (int i = 1; i < 9; i++) {
         JS::RootedValue rval(cx);
-        CHECK(JS_CallFunctionName(cx, global, "check", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "check", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK_SAME(INT_TO_JSVAL(called_test_fn), INT_TO_JSVAL(i));
         CHECK_SAME(INT_TO_JSVAL(called_test_prop_get), INT_TO_JSVAL(4 * i));
     }
     return true;
 }
 END_TEST(testClassGetter_isCalled)
--- a/js/src/jsapi-tests/testErrorCopying.cpp
+++ b/js/src/jsapi-tests/testErrorCopying.cpp
@@ -15,17 +15,18 @@ static uint32_t column = 0;
 BEGIN_TEST(testErrorCopying_columnCopied)
 {
         //0         1         2
         //0123456789012345678901234567
     EXEC("function check() { Object; foo; }");
 
     JS::RootedValue rval(cx);
     JS_SetErrorReporter(cx, my_ErrorReporter);
-    CHECK(!JS_CallFunctionName(cx, global, "check", JS::EmptyValueArray, &rval));
+    CHECK(!JS_CallFunctionName(cx, global, "check", JS::HandleValueArray::empty(),
+                               &rval));
     CHECK(column == 27);
     return true;
 }
 
 static void
 my_ErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
 {
     column = report->column;
--- a/js/src/jsapi-tests/testException.cpp
+++ b/js/src/jsapi-tests/testException.cpp
@@ -10,17 +10,17 @@
 BEGIN_TEST(testException_bug860435)
 {
     JS::RootedValue fun(cx);
 
     EVAL("ReferenceError", fun.address());
     CHECK(fun.isObject());
 
     JS::RootedValue v(cx);
-    JS_CallFunctionValue(cx, global, fun, JS::EmptyValueArray, &v);
+    JS_CallFunctionValue(cx, global, fun, JS::HandleValueArray::empty(), &v);
     CHECK(v.isObject());
     JS::RootedObject obj(cx, &v.toObject());
 
     JS_GetProperty(cx, obj, "stack", &v);
     CHECK(v.isString());
     return true;
 }
 END_TEST(testException_bug860435)
--- a/js/src/jsapi-tests/testOps.cpp
+++ b/js/src/jsapi-tests/testOps.cpp
@@ -50,15 +50,16 @@ static const JSFunctionSpec s_functions[
 BEGIN_TEST(testOps_bug559006)
 {
     CHECK(JS_DefineFunctions(cx, global, s_functions));
 
     EXEC("function main() { while(1) return 0 + createMyObject(); }");
 
     for (int i = 0; i < 9; i++) {
         JS::RootedValue rval(cx);
-        CHECK(JS_CallFunctionName(cx, global, "main", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "main", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK_SAME(rval, INT_TO_JSVAL(123));
     }
     return true;
 }
 END_TEST(testOps_bug559006)
 
--- a/js/src/jsapi-tests/testProfileStrings.cpp
+++ b/js/src/jsapi-tests/testProfileStrings.cpp
@@ -37,17 +37,17 @@ test_fn(JSContext *cx, unsigned argc, js
     return true;
 }
 
 static bool
 test_fn2(JSContext *cx, unsigned argc, jsval *vp)
 {
     JS::RootedValue r(cx);
     JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx));
-    return JS_CallFunctionName(cx, global, "d", JS::EmptyValueArray, &r);
+    return JS_CallFunctionName(cx, global, "d", JS::HandleValueArray::empty(), &r);
 }
 
 static bool
 enable(JSContext *cx, unsigned argc, jsval *vp)
 {
     js::EnableRuntimeProfilingStack(cx->runtime(), true);
     return true;
 }
@@ -99,42 +99,46 @@ BEGIN_TEST(testProfileStrings_isCalledWi
     EXEC("function a() { b(); }");
     EXEC("function check() { var p = new Prof(); p.test_fn(); a(); }");
     EXEC("function check2() { var p = new Prof(); p.test_fn2(); }");
 
     reset(cx);
     {
         JS::RootedValue rval(cx);
         /* Make sure the stack resets and we have an entry for each stack */
-        CHECK(JS_CallFunctionName(cx, global, "check", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "check", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK(psize == 0);
         CHECK(max_stack >= 8);
         CHECK(cx->runtime()->spsProfiler.stringsCount() == 8);
         /* Make sure the stack resets and we added no new entries */
         max_stack = 0;
-        CHECK(JS_CallFunctionName(cx, global, "check", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "check", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK(psize == 0);
         CHECK(max_stack >= 8);
         CHECK(cx->runtime()->spsProfiler.stringsCount() == 8);
     }
     reset(cx);
     {
         JS::RootedValue rval(cx);
-        CHECK(JS_CallFunctionName(cx, global, "check2", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "check2", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK(cx->runtime()->spsProfiler.stringsCount() == 5);
         CHECK(max_stack >= 6);
         CHECK(psize == 0);
     }
     js::EnableRuntimeProfilingStack(cx->runtime(), false);
     js::SetRuntimeProfilingStack(cx->runtime(), pstack, &psize, 3);
     reset(cx);
     {
         JS::RootedValue rval(cx);
         pstack[3].setLabel((char*) 1234);
-        CHECK(JS_CallFunctionName(cx, global, "check", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "check", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK((size_t) pstack[3].label() == 1234);
         CHECK(max_stack >= 8);
         CHECK(psize == 0);
     }
     return true;
 }
 END_TEST(testProfileStrings_isCalledWithInterpreter)
 
@@ -153,37 +157,40 @@ BEGIN_TEST(testProfileStrings_isCalledWi
     EXEC("function a() { b(); }");
     EXEC("function check() { var p = new Prof(); p.test_fn(); a(); }");
     EXEC("function check2() { var p = new Prof(); p.test_fn2(); }");
 
     reset(cx);
     {
         JS::RootedValue rval(cx);
         /* Make sure the stack resets and we have an entry for each stack */
-        CHECK(JS_CallFunctionName(cx, global, "check", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "check", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK(psize == 0);
         CHECK(max_stack >= 8);
 
         /* Make sure the stack resets and we added no new entries */
         uint32_t cnt = cx->runtime()->spsProfiler.stringsCount();
         max_stack = 0;
-        CHECK(JS_CallFunctionName(cx, global, "check", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "check", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK(psize == 0);
         CHECK(cx->runtime()->spsProfiler.stringsCount() == cnt);
         CHECK(max_stack >= 8);
     }
 
     js::EnableRuntimeProfilingStack(cx->runtime(), false);
     js::SetRuntimeProfilingStack(cx->runtime(), pstack, &psize, 3);
     reset(cx);
     {
         /* Limit the size of the stack and make sure we don't overflow */
         JS::RootedValue rval(cx);
         pstack[3].setLabel((char*) 1234);
-        CHECK(JS_CallFunctionName(cx, global, "check", JS::EmptyValueArray, &rval));
+        CHECK(JS_CallFunctionName(cx, global, "check", JS::HandleValueArray::empty(),
+                                  &rval));
         CHECK(psize == 0);
         CHECK(max_stack >= 8);
         CHECK((size_t) pstack[3].label() == 1234);
     }
     return true;
 }
 END_TEST(testProfileStrings_isCalledWithJIT)
 
@@ -195,17 +202,18 @@ BEGIN_TEST(testProfileStrings_isCalledWh
 
     EXEC("function check2() { throw 'a'; }");
 
     reset(cx);
     JS::ContextOptionsRef(cx).setDontReportUncaught(true);
     {
         JS::RootedValue rval(cx);
         /* Make sure the stack resets and we have an entry for each stack */
-        bool ok = JS_CallFunctionName(cx, global, "check2", JS::EmptyValueArray, &rval);
+        bool ok = JS_CallFunctionName(cx, global, "check2", JS::HandleValueArray::empty(),
+                                      &rval);
         CHECK(!ok);
         CHECK(psize == 0);
         CHECK(cx->runtime()->spsProfiler.stringsCount() == 1);
 
         JS_ClearPendingException(cx);
     }
     return true;
 }
@@ -219,49 +227,49 @@ BEGIN_TEST(testProfileStrings_worksWhenE
 
     EXEC("function b(p) { p.test_fn(); }");
     EXEC("function a() { var p = new Prof(); p.enable(); b(p); }");
     reset(cx);
     js::EnableRuntimeProfilingStack(cx->runtime(), false);
     {
         /* enable it in the middle of JS and make sure things check out */
         JS::RootedValue rval(cx);
-        JS_CallFunctionName(cx, global, "a", JS::EmptyValueArray, &rval);
+        JS_CallFunctionName(cx, global, "a", JS::HandleValueArray::empty(), &rval);
         CHECK(psize == 0);
         CHECK(max_stack >= 1);
         CHECK(cx->runtime()->spsProfiler.stringsCount() == 1);
     }
 
     EXEC("function d(p) { p.disable(); }");
     EXEC("function c() { var p = new Prof(); d(p); }");
     reset(cx);
     {
         /* now disable in the middle of js */
         JS::RootedValue rval(cx);
-        JS_CallFunctionName(cx, global, "c", JS::EmptyValueArray, &rval);
+        JS_CallFunctionName(cx, global, "c", JS::HandleValueArray::empty(), &rval);
         CHECK(psize == 0);
     }
 
     EXEC("function e() { var p = new Prof(); d(p); p.enable(); b(p); }");
     reset(cx);
     {
         /* now disable in the middle of js, but re-enable before final exit */
         JS::RootedValue rval(cx);
-        JS_CallFunctionName(cx, global, "e", JS::EmptyValueArray, &rval);
+        JS_CallFunctionName(cx, global, "e", JS::HandleValueArray::empty(), &rval);
         CHECK(psize == 0);
         CHECK(max_stack >= 3);
     }
 
     EXEC("function h() { }");
     EXEC("function g(p) { p.disable(); for (var i = 0; i < 100; i++) i++; }");
     EXEC("function f() { g(new Prof()); }");
     reset(cx);
     cx->runtime()->spsProfiler.enableSlowAssertions(false);
     {
         JS::RootedValue rval(cx);
         /* disable, and make sure that if we try to re-enter the JIT the pop
          * will still happen */
-        JS_CallFunctionName(cx, global, "f", JS::EmptyValueArray, &rval);
+        JS_CallFunctionName(cx, global, "f", JS::HandleValueArray::empty(), &rval);
         CHECK(psize == 0);
     }
     return true;
 }
 END_TEST(testProfileStrings_worksWhenEnabledOnTheFly)
new file mode 100644
--- /dev/null
+++ b/js/src/jsapi-tests/testUncaughtError.cpp
@@ -0,0 +1,56 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "jsapi-tests/tests.h"
+
+using JS::CreateTypeError;
+using JS::Rooted;
+using JS::ObjectValue;
+using JS::Value;
+
+static size_t uncaughtCount = 0;
+
+BEGIN_TEST(testUncaughtError)
+{
+    JSErrorReporter old = JS_SetErrorReporter(cx, UncaughtErrorReporter);
+
+    CHECK(uncaughtCount == 0);
+
+    Rooted<JSString*> empty(cx, JS_GetEmptyString(JS_GetRuntime(cx)));
+    if (!empty)
+        return false;
+
+    Rooted<Value> err(cx);
+    if (!CreateTypeError(cx, empty, empty, 0, 0, nullptr, empty, &err))
+        return false;
+
+    Rooted<JSObject*> errObj(cx, &err.toObject());
+    if (!JS_SetProperty(cx, errObj, "fileName", err))
+        return false;
+    if (!JS_SetProperty(cx, errObj, "lineNumber", err))
+        return false;
+    if (!JS_SetProperty(cx, errObj, "columnNumber", err))
+        return false;
+    if (!JS_SetProperty(cx, errObj, "stack", err))
+        return false;
+    if (!JS_SetProperty(cx, errObj, "message", err))
+        return false;
+
+    JS_SetPendingException(cx, err);
+    JS_ReportPendingException(cx);
+
+    CHECK(uncaughtCount == 1);
+
+    JS_SetErrorReporter(cx, old);
+
+    return true;
+}
+
+static void
+UncaughtErrorReporter(JSContext *cx, const char *message, JSErrorReport *report)
+{
+    uncaughtCount++;
+}
+
+END_TEST(testUncaughtError)
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -111,18 +111,16 @@ using js::frontend::Parser;
 #else
 #define JS_ADDRESSOF_VA_LIST(ap) (&(ap))
 #endif
 
 /* Make sure that jschar is two bytes unsigned integer */
 JS_STATIC_ASSERT((jschar)-1 > 0);
 JS_STATIC_ASSERT(sizeof(jschar) == 2);
 
-const JS::HandleValueArray JS::EmptyValueArray;
-
 JS_PUBLIC_API(int64_t)
 JS_Now()
 {
     return PRMJ_Now();
 }
 
 JS_PUBLIC_API(jsval)
 JS_GetNaNValue(JSContext *cx)
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -599,22 +599,21 @@ class JS_PUBLIC_API(CustomAutoRooter) : 
   private:
     MOZ_DECL_USE_GUARD_OBJECT_NOTIFIER
 };
 
 /* A handle to an array of rooted values. */
 class HandleValueArray
 {
     const size_t length_;
-    const Value *elements_;
+    const Value * const elements_;
 
     HandleValueArray(size_t len, const Value *elements) : length_(len), elements_(elements) {}
 
   public:
-    HandleValueArray() : length_(0), elements_(nullptr) {}
     HandleValueArray(const RootedValue& value) : length_(1), elements_(value.address()) {}
 
     HandleValueArray(const AutoValueVector& values)
       : length_(values.length()), elements_(values.begin()) {}
 
     template <size_t N>
     HandleValueArray(const AutoValueArray<N>& values) : length_(N), elements_(values.begin()) {}
 
@@ -626,27 +625,29 @@ class HandleValueArray
         return HandleValueArray(len, elements);
     }
 
     static HandleValueArray subarray(const HandleValueArray& values, size_t startIndex, size_t len) {
         JS_ASSERT(startIndex + len <= values.length());
         return HandleValueArray(len, values.begin() + startIndex);
     }
 
+    static HandleValueArray empty() {
+        return HandleValueArray(0, nullptr);
+    }
+
     size_t length() const { return length_; }
     const Value *begin() const { return elements_; }
 
     HandleValue operator[](size_t i) const {
         JS_ASSERT(i < length_);
         return HandleValue::fromMarkedLocation(&elements_[i]);
     }
 };
 
-extern JS_PUBLIC_DATA(const HandleValueArray) EmptyValueArray;
-
 }  /* namespace JS */
 
 /************************************************************************/
 
 struct JSFreeOp {
   private:
     JSRuntime   *runtime_;
 
--- a/js/src/jsexn.cpp
+++ b/js/src/jsexn.cpp
@@ -27,16 +27,18 @@
 
 #include "gc/Marking.h"
 #include "vm/ErrorObject.h"
 #include "vm/GlobalObject.h"
 #include "vm/StringBuffer.h"
 
 #include "jsobjinlines.h"
 
+#include "vm/ErrorObject-inl.h"
+
 using namespace js;
 using namespace js::gc;
 using namespace js::types;
 
 using mozilla::ArrayLength;
 using mozilla::PodArrayZero;
 using mozilla::PodZero;
 
@@ -890,20 +892,20 @@ js_CopyErrorObject(JSContext *cx, Handle
         copyReport = CopyErrorReport(cx, errorReport);
         if (!copyReport)
             return nullptr;
     }
 
     RootedString message(cx, err->getMessage());
     if (message && !cx->compartment()->wrap(cx, message.address()))
         return nullptr;
-    RootedString fileName(cx, err->fileName());
+    RootedString fileName(cx, err->fileName(cx));
     if (!cx->compartment()->wrap(cx, fileName.address()))
         return nullptr;
-    RootedString stack(cx, err->stack());
+    RootedString stack(cx, err->stack(cx));
     if (!cx->compartment()->wrap(cx, stack.address()))
         return nullptr;
     uint32_t lineNumber = err->lineNumber();
     uint32_t columnNumber = err->columnNumber();
     JSExnType errorType = err->type();
 
     // Create the Error object.
     return ErrorObject::create(cx, errorType, stack, fileName,
--- a/js/src/jsobj.h
+++ b/js/src/jsobj.h
@@ -422,17 +422,22 @@ class JSObject : public js::ObjectImpl
     inline void nativeSetSlotWithType(js::ExclusiveContext *cx, js::Shape *shape,
                                       const js::Value &value);
 
     inline const js::Value &getReservedSlot(uint32_t index) const {
         JS_ASSERT(index < JSSLOT_FREE(getClass()));
         return getSlot(index);
     }
 
-    inline js::HeapSlot &getReservedSlotRef(uint32_t index) {
+    const js::HeapSlot &getReservedSlotRef(uint32_t index) const {
+        JS_ASSERT(index < JSSLOT_FREE(getClass()));
+        return getSlotRef(index);
+    }
+
+    js::HeapSlot &getReservedSlotRef(uint32_t index) {
         JS_ASSERT(index < JSSLOT_FREE(getClass()));
         return getSlotRef(index);
     }
 
     void initReservedSlot(uint32_t index, const js::Value &v) {
         JS_ASSERT(index < JSSLOT_FREE(getClass()));
         initSlot(index, v);
     }
--- a/js/src/shell/js.cpp
+++ b/js/src/shell/js.cpp
@@ -321,18 +321,21 @@ ShellOperationCallback(JSContext *cx)
         return true;
 
     bool result;
     if (!gTimeoutFunc.isNull()) {
         JS::AutoSaveExceptionState savedExc(cx);
         JSAutoCompartment ac(cx, &gTimeoutFunc.toObject());
         RootedValue rval(cx);
         HandleValue timeoutFunc = HandleValue::fromMarkedLocation(&gTimeoutFunc);
-        if (!JS_CallFunctionValue(cx, JS::NullPtr(), timeoutFunc, JS::EmptyValueArray, &rval))
+        if (!JS_CallFunctionValue(cx, JS::NullPtr(), timeoutFunc,
+                                  JS::HandleValueArray::empty(), &rval))
+        {
             return false;
+        }
         if (rval.isBoolean())
             result = rval.toBoolean();
         else
             result = false;
     } else {
         result = false;
     }
 
@@ -4251,17 +4254,17 @@ WithSourceHook(JSContext *cx, unsigned a
 
     ShellSourceHook *hook = new ShellSourceHook(cx, args[0].toObject().as<JSFunction>());
     if (!hook)
         return false;
 
     SourceHook *savedHook = js::ForgetSourceHook(cx->runtime());
     js::SetSourceHook(cx->runtime(), hook);
     RootedObject fun(cx, &args[1].toObject());
-    bool result = Call(cx, UndefinedHandleValue, fun, JS::EmptyValueArray, args.rval());
+    bool result = Call(cx, UndefinedHandleValue, fun, JS::HandleValueArray::empty(), args.rval());
     js::SetSourceHook(cx->runtime(), savedHook);
     return result;
 }
 
 static bool
 IsCachingEnabled(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
@@ -4273,16 +4276,32 @@ static bool
 SetCachingEnabled(JSContext *cx, unsigned argc, Value *vp)
 {
     CallArgs args = CallArgsFromVp(argc, vp);
     jsCachingEnabled = ToBoolean(args.get(0));
     args.rval().setUndefined();
     return true;
 }
 
+static void
+PrintProfilerEvents_Callback(const char *msg)
+{
+    fprintf(stderr, "PROFILER EVENT: %s\n", msg);
+}
+
+static bool
+PrintProfilerEvents(JSContext *cx, unsigned argc, Value *vp)
+{
+    CallArgs args = CallArgsFromVp(argc, vp);
+    if (cx->runtime()->spsProfiler.enabled())
+        js::RegisterRuntimeProfilingEventMarker(cx->runtime(), &PrintProfilerEvents_Callback);
+    args.rval().setUndefined();
+    return true;
+}
+
 static const JSFunctionSpecWithHelp shell_functions[] = {
     JS_FN_HELP("version", Version, 0, 0,
 "version([number])",
 "  Get or force a script compilation version number."),
 
     JS_FN_HELP("options", Options, 0, 0,
 "options([option ...])",
 "  Get or toggle JavaScript options."),
@@ -4613,16 +4632,21 @@ static const JSFunctionSpecWithHelp shel
 
     JS_FN_HELP("cacheEntry", CacheEntry, 1, 0,
 "cacheEntry(code)",
 "  Return a new opaque object which emulates a cache entry of a script.  This\n"
 "  object encapsulates the code and its cached content. The cache entry is filled\n"
 "  and read by the \"evaluate\" function by using it in place of the source, and\n"
 "  by setting \"saveBytecode\" and \"loadBytecode\" options."),
 
+    JS_FN_HELP("printProfilerEvents", PrintProfilerEvents, 0, 0,
+"printProfilerEvents()",
+"  Register a callback with the profiler that prints javascript profiler events\n"
+"  to stderr.  Callback is only registered if profiling is enabled."),
+
     JS_FS_HELP_END
 };
 
 static const JSFunctionSpecWithHelp fuzzing_unsafe_functions[] = {
     JS_FN_HELP("clone", Clone, 1, 0,
 "clone(fun[, scope])",
 "  Clone function object."),
 
new file mode 100644
--- /dev/null
+++ b/js/src/vm/ErrorObject-inl.h
@@ -0,0 +1,44 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: set ts=8 sts=4 et sw=4 tw=99:
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef vm_ErrorObject_inl_h
+#define vm_ErrorObject_inl_h
+
+#include "vm/ErrorObject.h"
+
+#include "jscntxt.h"
+
+inline JSString *
+js::ErrorObject::fileName(JSContext *cx) const
+{
+    const HeapSlot &slot = getReservedSlotRef(FILENAME_SLOT);
+    return slot.isString() ? slot.toString() : cx->names().empty;
+}
+
+inline uint32_t
+js::ErrorObject::lineNumber() const
+{
+    const HeapSlot &slot = getReservedSlotRef(LINENUMBER_SLOT);
+    return slot.isInt32() ? slot.toInt32() : 0;
+}
+
+inline uint32_t
+js::ErrorObject::columnNumber() const
+{
+    const HeapSlot &slot = getReservedSlotRef(COLUMNNUMBER_SLOT);
+    return slot.isInt32() ? slot.toInt32() : 0;
+}
+
+inline JSString *
+js::ErrorObject::stack(JSContext *cx) const
+{
+    const HeapSlot &slot = getReservedSlotRef(STACK_SLOT);
+    if (slot.isString())
+        return slot.toString();
+    return cx->names().empty;
+}
+
+#endif /* vm_ErrorObject_inl_h */
--- a/js/src/vm/ErrorObject.cpp
+++ b/js/src/vm/ErrorObject.cpp
@@ -1,16 +1,16 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  * vim: set ts=8 sw=4 et tw=78:
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#include "vm/ErrorObject.h"
+#include "vm/ErrorObject-inl.h"
 
 #include "jsexn.h"
 
 #include "vm/GlobalObject.h"
 
 #include "jsobjinlines.h"
 
 #include "vm/Shape-inl.h"
@@ -120,17 +120,17 @@ js::ErrorObject::getOrCreateErrorReport(
     PodZero(&report);
 
     // Type.
     JSExnType type_ = type();
     report.exnType = type_;
 
     // Filename.
     JSAutoByteString filenameStr;
-    if (!filenameStr.encodeLatin1(cx, fileName()))
+    if (!filenameStr.encodeLatin1(cx, fileName(cx)))
         return nullptr;
     report.filename = filenameStr.ptr();
 
     // Coordinates.
     report.lineno = lineNumber();
     report.column = columnNumber();
 
     // Message. Note that |new Error()| will result in an undefined |message|
--- a/js/src/vm/ErrorObject.h
+++ b/js/src/vm/ErrorObject.h
@@ -80,33 +80,22 @@ class ErrorObject : public JSObject
         const Value &slot = getReservedSlot(ERROR_REPORT_SLOT);
         if (slot.isUndefined())
             return nullptr;
         return static_cast<JSErrorReport*>(slot.toPrivate());
     }
 
     JSErrorReport * getOrCreateErrorReport(JSContext *cx);
 
-    JSString * fileName() const {
-        return getReservedSlot(FILENAME_SLOT).toString();
-    }
-
-    uint32_t lineNumber() const {
-        return getReservedSlot(LINENUMBER_SLOT).toInt32();
-    }
-
-    uint32_t columnNumber() const {
-        return getReservedSlot(COLUMNNUMBER_SLOT).toInt32();
-    }
-
-    JSString * stack() const {
-        return getReservedSlot(STACK_SLOT).toString();
-    }
+    inline JSString * fileName(JSContext *cx) const;
+    inline uint32_t lineNumber() const;
+    inline uint32_t columnNumber() const;
+    inline JSString * stack(JSContext *cx) const;
 
     JSString * getMessage() const {
-        HeapSlot &slot = const_cast<ErrorObject*>(this)->getReservedSlotRef(MESSAGE_SLOT);
+        const HeapSlot &slot = getReservedSlotRef(MESSAGE_SLOT);
         return slot.isString() ? slot.toString() : nullptr;
     }
 };
 
 } // namespace js
 
 #endif // vm_ErrorObject_h_
--- a/js/src/vm/ObjectImpl.h
+++ b/js/src/vm/ObjectImpl.h
@@ -1320,38 +1320,58 @@ class ObjectImpl : public gc::BarrieredC
     const Value &getSlot(uint32_t slot) const {
         MOZ_ASSERT(slotInRange(slot));
         uint32_t fixed = numFixedSlots();
         if (slot < fixed)
             return fixedSlots()[slot];
         return slots[slot - fixed];
     }
 
-    HeapSlot *getSlotAddressUnchecked(uint32_t slot) {
+    const HeapSlot *getSlotAddressUnchecked(uint32_t slot) const {
         uint32_t fixed = numFixedSlots();
         if (slot < fixed)
             return fixedSlots() + slot;
         return slots + (slot - fixed);
     }
 
+    HeapSlot *getSlotAddressUnchecked(uint32_t slot) {
+        const ObjectImpl *obj = static_cast<const ObjectImpl*>(this);
+        return const_cast<HeapSlot*>(obj->getSlotAddressUnchecked(slot));
+    }
+
     HeapSlot *getSlotAddress(uint32_t slot) {
         /*
          * This can be used to get the address of the end of the slots for the
          * object, which may be necessary when fetching zero-length arrays of
          * slots (e.g. for callObjVarArray).
          */
         MOZ_ASSERT(slotInRange(slot, SENTINEL_ALLOWED));
         return getSlotAddressUnchecked(slot);
     }
 
+    const HeapSlot *getSlotAddress(uint32_t slot) const {
+        /*
+         * This can be used to get the address of the end of the slots for the
+         * object, which may be necessary when fetching zero-length arrays of
+         * slots (e.g. for callObjVarArray).
+         */
+        MOZ_ASSERT(slotInRange(slot, SENTINEL_ALLOWED));
+        return getSlotAddressUnchecked(slot);
+    }
+
     HeapSlot &getSlotRef(uint32_t slot) {
         MOZ_ASSERT(slotInRange(slot));
         return *getSlotAddress(slot);
     }
 
+    const HeapSlot &getSlotRef(uint32_t slot) const {
+        MOZ_ASSERT(slotInRange(slot));
+        return *getSlotAddress(slot);
+    }
+
     HeapSlot &nativeGetSlotRef(uint32_t slot) {
         JS_ASSERT(isNative() && slot < slotSpan());
         return getSlotRef(slot);
     }
     const Value &nativeGetSlot(uint32_t slot) const {
         JS_ASSERT(isNative() && slot < slotSpan());
         return getSlot(slot);
     }
--- a/js/src/vm/SPSProfiler.cpp
+++ b/js/src/vm/SPSProfiler.cpp
@@ -21,17 +21,18 @@ using mozilla::DebugOnly;
 
 SPSProfiler::SPSProfiler(JSRuntime *rt)
   : rt(rt),
     stack_(nullptr),
     size_(nullptr),
     max_(0),
     slowAssertions(false),
     enabled_(false),
-    lock_(nullptr)
+    lock_(nullptr),
+    eventMarker_(nullptr)
 {
     JS_ASSERT(rt != nullptr);
 }
 
 bool
 SPSProfiler::init()
 {
 #ifdef JS_THREADSAFE
@@ -62,16 +63,22 @@ SPSProfiler::setProfilingStack(ProfileEn
     if (!strings.initialized())
         strings.init();
     stack_ = stack;
     size_  = size;
     max_   = max;
 }
 
 void
+SPSProfiler::setEventMarker(void (*fn)(const char *))
+{
+    eventMarker_ = fn;
+}
+
+void
 SPSProfiler::enable(bool enabled)
 {
     JS_ASSERT(installed());
 
     if (enabled_ == enabled)
         return;
 
     /*
@@ -126,16 +133,26 @@ SPSProfiler::onScriptFinalized(JSScript 
         return;
     if (ProfileStringMap::Ptr entry = strings.lookup(script)) {
         const char *tofree = entry->value();
         strings.remove(entry);
         js_free(const_cast<char *>(tofree));
     }
 }
 
+void
+SPSProfiler::markEvent(const char *event)
+{
+    JS_ASSERT(enabled());
+    if (eventMarker_) {
+        JS::AutoAssertNoGC nogc;
+        eventMarker_(event);
+    }
+}
+
 bool
 SPSProfiler::enter(JSScript *script, JSFunction *maybeFun)
 {
     const char *str = profileString(script, maybeFun);
     if (str == nullptr)
         return false;
 
 #ifdef DEBUG
@@ -326,13 +343,20 @@ js::SetRuntimeProfilingStack(JSRuntime *
 }
 
 JS_FRIEND_API(void)
 js::EnableRuntimeProfilingStack(JSRuntime *rt, bool enabled)
 {
     rt->spsProfiler.enable(enabled);
 }
 
+JS_FRIEND_API(void)
+js::RegisterRuntimeProfilingEventMarker(JSRuntime *rt, void (*fn)(const char *))
+{
+    JS_ASSERT(rt->spsProfiler.enabled());
+    rt->spsProfiler.setEventMarker(fn);
+}
+
 JS_FRIEND_API(jsbytecode*)
 js::ProfilingGetPC(JSRuntime *rt, JSScript *script, void *ip)
 {
     return rt->spsProfiler.ipToPC(script, size_t(ip));
 }
--- a/js/src/vm/SPSProfiler.h
+++ b/js/src/vm/SPSProfiler.h
@@ -120,16 +120,17 @@ class SPSProfiler
     JSRuntime            *rt;
     ProfileStringMap     strings;
     ProfileEntry         *stack_;
     uint32_t             *size_;
     uint32_t             max_;
     bool                 slowAssertions;
     uint32_t             enabled_;
     PRLock               *lock_;
+    void                (*eventMarker_)(const char *);
 
     const char *allocProfileString(JSScript *script, JSFunction *function);
     void push(const char *string, void *sp, JSScript *script, jsbytecode *pc);
     void pushNoCopy(const char *string, void *sp,
                     JSScript *script, jsbytecode *pc) {
         push(string, reinterpret_cast<void*>(
             reinterpret_cast<uintptr_t>(sp) | ProfileEntry::NoCopyBit),
             script, pc);
@@ -186,19 +187,22 @@ class SPSProfiler
 
     /* Enter a C++ function. */
     void enterNative(const char *string, void *sp);
     void exitNative() { pop(); }
 
     jsbytecode *ipToPC(JSScript *script, size_t ip) { return nullptr; }
 
     void setProfilingStack(ProfileEntry *stack, uint32_t *size, uint32_t max);
+    void setEventMarker(void (*fn)(const char *));
     const char *profileString(JSScript *script, JSFunction *maybeFun);
     void onScriptFinalized(JSScript *script);
 
+    void markEvent(const char *event);
+
     /* meant to be used for testing, not recommended to call in normal code */
     size_t stringsCount();
     void stringsReset();
 
     uint32_t *addressOfEnabled() {
         return &enabled_;
     }
 };
--- a/js/xpconnect/loader/mozJSComponentLoader.cpp
+++ b/js/xpconnect/loader/mozJSComponentLoader.cpp
@@ -865,17 +865,17 @@ mozJSComponentLoader::ObjectForLocation(
                                                buf, fileSize32);
             }
 
             PR_MemUnmap(buf, fileSize32);
 
 #else  /* HAVE_PR_MEMMAP */
 
             /**
-             * No memmap implementation, so fall back to 
+             * No memmap implementation, so fall back to
              * reading in the file
              */
 
             FILE *fileHandle;
             rv = aComponentFile->OpenANSIFileDesc("r", &fileHandle);
             if (NS_FAILED(rv)) {
                 return NS_ERROR_FILE_NOT_FOUND;
             }
@@ -1008,17 +1008,17 @@ mozJSComponentLoader::ObjectForLocation(
     {
         AutoSaveContextOptions asco(cx);
         if (aPropagateExceptions)
             ContextOptionsRef(cx).setDontReportUncaught(true);
         if (script) {
             ok = JS_ExecuteScriptVersion(cx, obj, script, nullptr, JSVERSION_LATEST);
         } else {
             RootedValue rval(cx);
-            ok = JS_CallFunction(cx, obj, function, JS::EmptyValueArray, &rval);
+            ok = JS_CallFunction(cx, obj, function, JS::HandleValueArray::empty(), &rval);
         }
      }
 
     if (!ok) {
         if (aPropagateExceptions) {
             JS_GetPendingException(cx, aException);
             JS_ClearPendingException(cx);
         }
--- a/js/xpconnect/loader/mozJSSubScriptLoader.cpp
+++ b/js/xpconnect/loader/mozJSSubScriptLoader.cpp
@@ -343,17 +343,18 @@ mozJSSubScriptLoader::DoLoadSubScriptWit
         script = JS_GetFunctionScript(cx, function);
     }
 
     loader->NoteSubScript(script, targetObj);
 
 
     bool ok = false;
     if (function) {
-        ok = JS_CallFunction(cx, targetObj, function, JS::EmptyValueArray, retval);
+        ok = JS_CallFunction(cx, targetObj, function, JS::HandleValueArray::empty(),
+                             retval);
     } else {
         ok = JS_ExecuteScriptVersion(cx, targetObj, script, retval.address(), version);
     }
 
     if (ok) {
         JSAutoCompartment rac(cx, result_obj);
         if (!JS_WrapValue(cx, retval))
             return NS_ERROR_UNEXPECTED;
--- a/js/xpconnect/src/XPCShellImpl.cpp
+++ b/js/xpconnect/src/XPCShellImpl.cpp
@@ -657,17 +657,17 @@ XPCShellOperationCallback(JSContext *cx)
 {
     // If no operation callback was set by script, no-op.
     if (sScriptedOperationCallback.isUndefined())
         return true;
 
     JSAutoCompartment ac(cx, &sScriptedOperationCallback.toObject());
     RootedValue rv(cx);
     RootedValue callback(cx, sScriptedOperationCallback);
-    if (!JS_CallFunctionValue(cx, JS::NullPtr(), callback, JS::EmptyValueArray, &rv) ||
+    if (!JS_CallFunctionValue(cx, JS::NullPtr(), callback, JS::HandleValueArray::empty(), &rv) ||
         !rv.isBoolean())
     {
         NS_WARNING("Scripted operation callback failed! Terminating script.");
         JS_ClearPendingException(cx);
         return false;
     }
 
     return rv.toBoolean();
new file mode 100644
--- /dev/null
+++ b/media/libpng/crashtests/974825-1.html
@@ -0,0 +1,7 @@
+<html><head><title>crash test for bug #974825</title></head>
+<body>
+<img alt="Crash Test bug#974825" title="Crash Test bug#974825"
+src="data:image/png;base64,
+iVBORw0KGgoAAAANSUhEUgAAAEAAAAAgCAYAAACinX6EAAAAAElEQVRKVU5LdGhlIGp1TmtKVU5LCg==">
+</body>
+</html>
--- a/media/libpng/crashtests/crashtests.list
+++ b/media/libpng/crashtests/crashtests.list
@@ -1,2 +1,3 @@
 load 374810-1.html
 load 945912-1.html
+load 974825-1.html
--- a/media/libpng/pngpread.c
+++ b/media/libpng/pngpread.c
@@ -230,16 +230,17 @@ png_push_read_chunk(png_structrp png_ptr
          if (png_ptr->push_length + 4 > png_ptr->buffer_size)
          {
             png_push_save_buffer(png_ptr);
             return;
          }
 
          png_push_crc_skip(png_ptr, png_ptr->push_length);
          png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
+         png_ptr->process_mode = PNG_READ_IDAT_MODE;
          return;
       }
       else if (chunk_name == png_fdAT)
       {
          if (png_ptr->buffer_size < 4)
          {
             png_push_save_buffer(png_ptr);
             return;
@@ -332,16 +333,17 @@ png_push_read_chunk(png_structrp png_ptr
       if (!(png_ptr->mode & PNG_HAVE_IHDR))
          png_error(png_ptr, "Missing IHDR before IDAT");
 
       else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
           !(png_ptr->mode & PNG_HAVE_PLTE))
          png_error(png_ptr, "Missing PLTE before IDAT");
 
       png_ptr->mode |= PNG_HAVE_IDAT;
+      png_ptr->process_mode = PNG_READ_IDAT_MODE;
 
       if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
          if (png_ptr->push_length == 0)
             return;
 
       if (png_ptr->mode & PNG_AFTER_IDAT)
          png_benign_error(png_ptr, "Too many IDATs found");
    }
--- a/media/libsoundtouch/moz-libsoundtouch.patch
+++ b/media/libsoundtouch/moz-libsoundtouch.patch
@@ -69,17 +69,17 @@ diff -u /src/cpu_detect_x86.cpp /src/cpu
 +#else
 +    // Compatible with GCC but no cpuid.h.
 +    return 0;
  #endif
  
      return res & ~_dwDisabledISA;
 --- /src/STTypes.h	2012-08-02 10:04:06.301691592 -0700
 +++ /src/STTypes.h
-@@ -42,21 +42,13 @@
+@@ -42,21 +42,17 @@
  typedef unsigned int    uint;
  typedef unsigned long   ulong;
  
 -#ifdef __GNUC__
 -    // In GCC, include soundtouch_config.h made by config scritps
 -    #include "soundtouch_config.h"
 -#endif
 -
@@ -90,33 +90,37 @@ diff -u /src/cpu_detect_x86.cpp /src/cpu
 -
 -    #define FALSE   0
 -    #define TRUE    1
 -
 -#endif  // _WINDEF_
 +#include "soundtouch_config.h"
  
 +#ifdef WIN32
++#ifdef BUILDING_SOUNDTOUCH
 +#define EXPORT __declspec(dllexport)
 +#else
++#define EXPORT __declspec(dllimport)
++#endif
++#else
 +#define EXPORT
 +#endif
  
  namespace soundtouch
  {
-@@ -82,7 +74,7 @@
+@@ -82,7 +78,7 @@
          ///   also in GNU environment, then please #undef the INTEGER_SAMPLE
          ///   and FLOAT_SAMPLE defines first as in comments above.
          //#define SOUNDTOUCH_INTEGER_SAMPLES     1    //< 16bit integer samples
 -        #define SOUNDTOUCH_FLOAT_SAMPLES       1    //< 32bit float samples
 +        #define SOUNDTOUCH_FLOAT_SAMPLES       1    //< 32bit float samples 
       
      #endif
  
-@@ -144,10 +136,10 @@
+@@ -144,10 +140,10 @@
  
      #endif  // SOUNDTOUCH_INTEGER_SAMPLES
  
 -};
 +}
  
  // define ST_NO_EXCEPTION_HANDLING switch to disable throwing std exceptions:
 -// #define ST_NO_EXCEPTION_HANDLING    1
--- a/media/libsoundtouch/src/STTypes.h
+++ b/media/libsoundtouch/src/STTypes.h
@@ -52,18 +52,22 @@ typedef unsigned long   ulong;
 
 // Helper macro for aligning pointer up to next 16-byte boundary
 #define SOUNDTOUCH_ALIGN_POINTER_16(x)      ( ( (ulongptr)(x) + 15 ) & ~(ulongptr)15 )
 
 
 #include "soundtouch_config.h"
 
 #ifdef WIN32
+#ifdef BUILDING_SOUNDTOUCH
 #define EXPORT __declspec(dllexport)
 #else
+#define EXPORT __declspec(dllimport)
+#endif
+#else
 #define EXPORT
 #endif
 
 namespace soundtouch
 {
     /// Activate these undef's to overrule the possible sampletype 
     /// setting inherited from some other header file:
     //#undef SOUNDTOUCH_INTEGER_SAMPLES
--- a/media/libsoundtouch/src/moz.build
+++ b/media/libsoundtouch/src/moz.build
@@ -34,8 +34,10 @@ if CONFIG['INTEL_ARCHITECTURE']:
 MSVC_ENABLE_PGO = True
 if CONFIG['GKMEDIAS_SHARED_LIBRARY']:
     NO_VISIBILITY_FLAGS = True
 
 FINAL_LIBRARY = 'gkmedias'
 
 # Use abort() instead of exception in SoundTouch.
 DEFINES['ST_NO_EXCEPTION_HANDLING'] = 1
+
+DEFINES['BUILDING_SOUNDTOUCH'] = True
old mode 100644
new mode 100755
--- a/mobile/android/base/tests/robocop.ini
+++ b/mobile/android/base/tests/robocop.ini
@@ -94,12 +94,12 @@ skip-if = processor == "x86"
 
 # Used for Talos, please don't use in mochitest
 #[testPan]
 #[testCheck]
 #[testCheck2]
 #[testBrowserProviderPerf]
 
 # Using UITest
-[testAboutHomePageNavigation]
+#[testAboutHomePageNavigation] # see bug 947550 and bug 977952
 [testAboutHomeVisibility]
 [testInputConnection]
 [testSessionHistory]
--- a/security/apps/AppTrustDomain.cpp
+++ b/security/apps/AppTrustDomain.cpp
@@ -93,25 +93,16 @@ AppTrustDomain::FindPotentialIssuers(con
   MOZ_ASSERT(mTrustedRoot);
   if (!mTrustedRoot) {
     PR_SetError(PR_INVALID_STATE_ERROR, 0);
     return SECFailure;
   }
 
   results = CERT_CreateSubjectCertList(nullptr, CERT_GetDefaultCertDB(),
                                        encodedIssuerName, time, true);
-  if (!results) {
-    // NSS sometimes returns this unhelpful error code upon failing to find any
-    // candidate certificates.
-    if (PR_GetError() == SEC_ERROR_BAD_DATABASE) {
-      PR_SetError(SEC_ERROR_UNKNOWN_ISSUER, 0);
-    }
-    return SECFailure;
-  }
-
   return SECSuccess;
 }
 
 SECStatus
 AppTrustDomain::GetCertTrust(EndEntityOrCA endEntityOrCA,
                              SECOidTag policy,
                              const CERTCertificate* candidateCert,
                      /*out*/ TrustLevel* trustLevel)
--- a/security/certverifier/NSSCertDBTrustDomain.cpp
+++ b/security/certverifier/NSSCertDBTrustDomain.cpp
@@ -52,25 +52,16 @@ NSSCertDBTrustDomain::FindPotentialIssue
   const SECItem* encodedIssuerName, PRTime time,
   /*out*/ insanity::pkix::ScopedCERTCertList& results)
 {
   // TODO: normalize encodedIssuerName
   // TODO: NSS seems to be ambiguous between "no potential issuers found" and
   // "there was an error trying to retrieve the potential issuers."
   results = CERT_CreateSubjectCertList(nullptr, CERT_GetDefaultCertDB(),
                                        encodedIssuerName, time, true);
-  if (!results) {
-    // NSS sometimes returns this unhelpful error code upon failing to find any
-    // candidate certificates.
-    if (PR_GetError() == SEC_ERROR_BAD_DATABASE) {
-      PR_SetError(SEC_ERROR_UNKNOWN_ISSUER, 0);
-    }
-    return SECFailure;
-  }
-
   return SECSuccess;
 }
 
 SECStatus
 NSSCertDBTrustDomain::GetCertTrust(EndEntityOrCA endEntityOrCA,
                                    SECOidTag policy,
                                    const CERTCertificate* candidateCert,
                                    /*out*/ TrustLevel* trustLevel)
--- a/security/insanity/include/insanity/pkixtypes.h
+++ b/security/insanity/include/insanity/pkixtypes.h
@@ -68,18 +68,21 @@ public:
   virtual SECStatus GetCertTrust(EndEntityOrCA endEntityOrCA,
                                  SECOidTag policy,
                                  const CERTCertificate* candidateCert,
                          /*out*/ TrustLevel* trustLevel) = 0;
 
   // Find all certificates (intermediate and/or root) in the certificate
   // database that have a subject name matching |encodedIssuerName| at
   // the given time. Certificates where the given time is not within the
-  // certificate's validity period may be excluded. The results should be
-  // added to the |results| certificate list.
+  // certificate's validity period may be excluded. On input, |results|
+  // will be null on input. If no potential issuers are found, then this
+  // function should return SECSuccess with results being either null or
+  // an empty list. Otherwise, this function should construct a
+  // CERTCertList and return it in |results|, transfering ownership.
   virtual SECStatus FindPotentialIssuers(const SECItem* encodedIssuerName,
                                          PRTime time,
                                  /*out*/ ScopedCERTCertList& results) = 0;
 
   // Verify the given signature using the public key of the given certificate.
   // The implementation should be careful to ensure that the given certificate
   // has all the public key information needed--i.e. it should ensure that the
   // certificate is not trying to use EC(DSA) parameter inheritance.
--- a/security/insanity/lib/pkixbuild.cpp
+++ b/security/insanity/lib/pkixbuild.cpp
@@ -227,17 +227,16 @@ BuildForward(TrustDomain& trustDomain,
 
   // Find a trusted issuer.
   // TODO(bug 965136): Add SKI/AKI matching optimizations
   ScopedCERTCertList candidates;
   if (trustDomain.FindPotentialIssuers(&subject.GetNSSCert()->derIssuer, time,
                                        candidates) != SECSuccess) {
     return MapSECStatus(SECFailure);
   }
-  PORT_Assert(candidates.get());
   if (!candidates) {
     return Fail(RecoverableError, SEC_ERROR_UNKNOWN_ISSUER);
   }
 
   PRErrorCode errorToReturn = 0;
 
   for (CERTCertListNode* n = CERT_LIST_HEAD(candidates);
        !CERT_LIST_END(n, candidates); n = CERT_LIST_NEXT(n)) {
--- a/security/manager/ssl/src/moz.build
+++ b/security/manager/ssl/src/moz.build
@@ -93,12 +93,14 @@ FAIL_ON_WARNINGS = True
 
 FINAL_LIBRARY = 'xul'
 
 LOCAL_INCLUDES += [
     '../../../certverifier',
     '../../../insanity/include',
 ]
 
+if CONFIG['NSS_DISABLE_DBM']:
+    DEFINES['NSS_DISABLE_DBM'] = '1'
 
 DEFINES['NSS_ENABLE_ECC'] = 'True'
 for var in ('DLL_PREFIX', 'DLL_SUFFIX'):
     DEFINES[var] = '"%s"' % CONFIG[var]
--- a/security/manager/ssl/src/nsNSSCertificateDB.cpp
+++ b/security/manager/ssl/src/nsNSSCertificateDB.cpp
@@ -53,16 +53,41 @@
 using namespace mozilla;
 using namespace mozilla::psm;
 using mozilla::psm::SharedSSLState;
 
 #ifdef PR_LOGGING
 extern PRLogModuleInfo* gPIPNSSLog;
 #endif
 
+static nsresult
+attemptToLogInWithDefaultPassword()
+{
+#ifdef NSS_DISABLE_DBM
+  // The SQL NSS DB requires the user to be authenticated to set certificate
+  // trust settings, even if the user's password is empty. To maintain
+  // compatibility with the DBM-based database, try to log in with the
+  // default empty password. This will allow, at least, tests that need to
+  // change certificate trust to pass on all platforms. TODO(bug 978120): Do
+  // proper testing and/or implement a better solution so that we are confident
+  // that this does the correct thing outside of xpcshell tests too.
+  ScopedPK11SlotInfo slot(PK11_GetInternalKeySlot());
+  if (!slot) {
+    return MapSECStatus(SECFailure);
+  }
+  if (PK11_NeedUserInit(slot)) {
+    // Ignore the return value. Presumably PK11_InitPin will fail if the user
+    // has a non-default password.
+    (void) PK11_InitPin(slot, nullptr, nullptr);
+  }
+#endif
+
+  return NS_OK;
+}
+
 NS_IMPL_ISUPPORTS2(nsNSSCertificateDB, nsIX509CertDB, nsIX509CertDB2)
 
 nsNSSCertificateDB::nsNSSCertificateDB()
 : mBadCertsLock("nsNSSCertificateDB::mBadCertsLock")
 {
   SharedSSLState::NoteCertDBServiceInstantiated();
 }
 
@@ -973,16 +998,21 @@ nsNSSCertificateDB::SetCertTrust(nsIX509
   nsNSSCertTrust trust;
   nsresult rv;
   nsCOMPtr<nsIX509Cert2> pipCert = do_QueryInterface(cert, &rv);
   if (!pipCert) {
     return rv;
   }
   insanity::pkix::ScopedCERTCertificate nsscert(pipCert->GetCert());
 
+  rv = attemptToLogInWithDefaultPassword();
+  if (NS_WARN_IF(rv != NS_OK)) {
+    return rv;
+  }
+
   SECStatus srv;
   if (type == nsIX509Cert::CA_CERT) {
     // always start with untrusted and move up
     trust.SetValidCA();
     trust.AddCATrust(!!(trusted & nsIX509CertDB::TRUSTED_SSL),
                      !!(trusted & nsIX509CertDB::TRUSTED_EMAIL),
                      !!(trusted & nsIX509CertDB::TRUSTED_OBJSIGN));
     srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), 
@@ -1609,16 +1639,21 @@ NS_IMETHODIMP nsNSSCertificateDB::AddCer
     return NS_OK;
   }
 
   nsXPIDLCString nickname;
   nickname.Adopt(CERT_MakeCANickname(tmpCert.get()));
 
   PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Created nick \"%s\"\n", nickname.get()));
 
+  rv = attemptToLogInWithDefaultPassword();
+  if (NS_WARN_IF(rv != NS_OK)) {
+    return rv;
+  }
+
   SECStatus srv = __CERT_AddTempCertToPerm(tmpCert.get(),
                                            const_cast<char*>(nickname.get()),
                                            trust.GetTrust());
   return MapSECStatus(srv);
 }
 
 NS_IMETHODIMP
 nsNSSCertificateDB::AddCert(const nsACString & aCertDER, const char *aTrust,
@@ -1638,16 +1673,22 @@ nsNSSCertificateDB::SetCertTrustFromStri
 
   // need to calculate the trust bits from the aTrust string.
   SECStatus srv = CERT_DecodeTrustString(&trust,
                                          const_cast<char *>(trustString));
   if (srv != SECSuccess) {
     return MapSECStatus(SECFailure);
   }
   insanity::pkix::ScopedCERTCertificate nssCert(cert->GetCert());
+
+  nsresult rv = attemptToLogInWithDefaultPassword();
+  if (NS_WARN_IF(rv != NS_OK)) {
+    return rv;
+  }
+
   srv = CERT_ChangeCertTrust(CERT_GetDefaultCertDB(), nssCert.get(), &trust);
   return MapSECStatus(srv);
 }
 
 NS_IMETHODIMP 
 nsNSSCertificateDB::GetCerts(nsIX509CertList **_retval)
 {
   nsNSSShutDownPreventionLock locker;
--- a/security/manager/ssl/tests/unit/xpcshell.ini
+++ b/security/manager/ssl/tests/unit/xpcshell.ini
@@ -6,38 +6,29 @@ support-files =
   test_signed_apps/**
   tlsserver/**
   test_cert_signatures/**
   test_ev_certs/**
   test_getchain/**
   test_intermediate_basic_usage_constraints/**
   test_name_constraints/**
 
-[test_signed_apps.js]
-# Bug 978117: test fails consistently on Android and B2G
-fail-if = os == "android" || buildapp == "b2g"
-[test_signed_apps-marketplace.js]
-# Bug 978117: test fails consistently on Android and B2G
-fail-if = os == "android" || buildapp == "b2g"
-
 [test_datasignatureverifier.js]
 [test_hash_algorithms.js]
 [test_hmac.js]
 
 [test_sts_preloadlist_perwindowpb.js]
 # Bug 978426: Test fails consistently only on B2G ARM
 skip-if = buildapp == "b2g" && processor = "arm"
 
 [test_sts_preloadlist_selfdestruct.js]
 [test_sts_holepunch.js]
 [test_sts_ipv4_ipv6.js]
 
 [test_certificate_usages.js]
-# Bug 676972: test fails consistently on Android and B2G
-fail-if = os == "android" || buildapp == "b2g"
 [test_ocsp_stapling.js]
 run-sequentially = hardcoded ports
 # Bug 676972: test fails consistently on Android and B2G
 fail-if = os == "android" || buildapp == "b2g"
 [test_ocsp_stapling_expired.js]
 run-sequentially = hardcoded ports
 # Bug 676972: test fails consistently on Android and B2G
 fail-if = os == "android" || buildapp == "b2g"
@@ -49,26 +40,21 @@ fail-if = os == "android" || buildapp ==
 run-sequentially = hardcoded ports
 # Bug 676972: test fails consistently on Android and B2G
 fail-if = os == "android" || buildapp == "b2g"
 [test_ocsp_required.js]
 run-sequentially = hardcoded ports
 # Bug 676972: test fails consistently on Android and B2G
 fail-if = os == "android" || buildapp == "b2g"
 [test_cert_signatures.js]
-# Bug 676972: test fails consistently on Android and B2G
-fail-if = os == "android" || buildapp == "b2g"
 [test_ev_certs.js]
 # Bug 676972: test fails consistently on Android and B2G
 fail-if = os == "android" || buildapp == "b2g"
 [test_getchain.js]
-# Bug 676972: test fails consistently on Android and B2G
-fail-if = os == "android" || buildapp == "b2g"
 [test_cert_overrides.js]
 run-sequentially = hardcoded ports
 # Bug 676972: test fails consistently on Android and B2G
 fail-if = os == "android" || buildapp == "b2g"
 [test_intermediate_basic_usage_constraints.js]
-# Bug 676972: test fails consistently on Android and B2G
-fail-if = os == "android" || buildapp == "b2g"
 [test_name_constraints.js]
-# Bug 676972: test fails consistently on Android and B2G
-fail-if = os == "android" || buildapp == "b2g"
+
+[test_signed_apps.js]
+[test_signed_apps-marketplace.js]
--- a/security/nss/TAG-INFO
+++ b/security/nss/TAG-INFO
@@ -1,1 +1,1 @@
-NSS_3_16_BETA3
+NSS_3_16_BETA4
--- a/security/nss/automation/buildbot-slave/bbenv-example.sh
+++ b/security/nss/automation/buildbot-slave/bbenv-example.sh
@@ -14,18 +14,16 @@ export HOST
 #HOST=localhost
 #DOMSUF=localdomain
 #export DOMSUF
 
 ARCH=$(uname -s)
 
 ulimit -c unlimited 2> /dev/null
 
-export NSS_ENABLE_ECC=1
-export NSS_ECC_MORE_THAN_SUITE_B=1
 export NSPR_LOG_MODULES="pkix:1"
 
 #export JAVA_HOME_32=
 #export JAVA_HOME_64=
 
 #enable if you have PKITS data
 #export PKITS_DATA=$HOME/pkits/data/
 
--- a/security/nss/automation/buildbot-slave/build.sh
+++ b/security/nss/automation/buildbot-slave/build.sh
@@ -283,17 +283,17 @@ prepare()
 {
     rm -rf ${OUTPUTDIR}.oldest >/dev/null 2>&1
     mv ${OUTPUTDIR}.older ${OUTPUTDIR}.oldest >/dev/null 2>&1
     mv ${OUTPUTDIR}.old ${OUTPUTDIR}.older >/dev/null 2>&1
     mv ${OUTPUTDIR}.last ${OUTPUTDIR}.old >/dev/null 2>&1
     mv ${OUTPUTDIR} ${OUTPUTDIR}.last >/dev/null 2>&1
     mkdir -p ${OUTPUTDIR}
 
-    if [ -n "${NSS_ENABLE_ECC}" -a -n "${NSS_ECC_MORE_THAN_SUITE_B}" ]; then
+    if [ -z "${NSS_DISABLE_ECC}" -a -n "${NSS_ECC_MORE_THAN_SUITE_B}" ]; then
         cd ${HGDIR}/nss
         ECF="lib/freebl/ecl/ecl-curve.h"
 	print_log "hg revert -r NSS_3_11_1_RTM ${ECF}"
         hg revert -r NSS_3_11_1_RTM security/nss/${ECF}
         cp -f security/nss/${ECF} ${ECF}
     fi
 
     return 0
--- a/security/nss/cmd/bltest/blapitest.c
+++ b/security/nss/cmd/bltest/blapitest.c
@@ -16,17 +16,17 @@
 #include "basicutil.h"
 #include "plgetopt.h"
 #include "softoken.h"
 #include "nspr.h"
 #include "secport.h"
 #include "secoid.h"
 #include "nssutil.h"
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #include "ecl-curve.h"
 SECStatus EC_DecodeParams(const SECItem *encodedParams, 
 	ECParams **ecparams);
 SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams,
 	      const ECParams *srcParams);
 #endif
 
 char *progName;
@@ -128,25 +128,25 @@ static void Usage()
     PRINTUSAGE("",	"-b", "size of input buffer");
     PRINTUSAGE("",	"-p", "do performance test");
     PRINTUSAGE("",	"-4", "run test in multithread mode. th_num number of parallel threads");
     PRINTUSAGE("",	"-5", "run test for specified time interval(in seconds)");
     fprintf(stderr, "\n");
     PRINTUSAGE(progName, "-S -m mode", "Sign a buffer");
     PRINTUSAGE("",	"", "[-i plaintext] [-o signature] [-k key]");
     PRINTUSAGE("",	"", "[-b bufsize]");
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     PRINTUSAGE("",	"", "[-n curvename]");
 #endif
     PRINTUSAGE("",	"", "[-p repetitions | -5 time_interval] [-4 th_num]");
     PRINTUSAGE("",	"-m", "cipher mode to use");
     PRINTUSAGE("",	"-i", "file which contains input buffer");
     PRINTUSAGE("",	"-o", "file for signature");
     PRINTUSAGE("",	"-k", "file which contains key");
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     PRINTUSAGE("",	"-n", "name of curve for EC key generation; one of:");
     PRINTUSAGE("",  "",   "  sect163k1, nistk163, sect163r1, sect163r2,");
     PRINTUSAGE("",  "",   "  nistb163, sect193r1, sect193r2, sect233k1, nistk233,");
     PRINTUSAGE("",  "",   "  sect233r1, nistb233, sect239k1, sect283k1, nistk283,");
     PRINTUSAGE("",  "",   "  sect283r1, nistb283, sect409k1, nistk409, sect409r1,");
     PRINTUSAGE("",  "",   "  nistb409, sect571k1, nistk571, sect571r1, nistb571,");
     PRINTUSAGE("",  "",   "  secp160k1, secp160r1, secp160r2, secp192k1, secp192r1,");
     PRINTUSAGE("",  "",   "  nistp192, secp224k1, secp224r1, nistp224, secp256k1,");
@@ -385,17 +385,17 @@ dsakey_from_filedata(SECItem *filedata)
     PLArenaPool *arena;
     arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
     key = (DSAPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(DSAPrivateKey));
     key->params.arena = arena;
     key_from_filedata(arena, &key->params.prime, 0, 5, filedata);
     return key;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 static ECPrivateKey *
 eckey_from_filedata(SECItem *filedata)
 {
     ECPrivateKey *key;
     PLArenaPool *arena;
     SECStatus rv;
     ECParams *tmpECParams = NULL;
     arena = PORT_NewArena(BLTEST_DEFAULT_CHUNKSIZE);
@@ -539,17 +539,17 @@ getECParams(const char *curve)
      * oidData->oid.data so we simply prepend 0x06 and OID length
      */
     ecparams->data[0] = SEC_ASN1_OBJECT_ID;
     ecparams->data[1] = oidData->oid.len;
     memcpy(ecparams->data + 2, oidData->oid.data, oidData->oid.len);
 
     return ecparams;
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 static void
 dump_pqg(PQGParams *pqg)
 {
     SECU_PrintInteger(stdout, &pqg->prime, "PRIME:", 0);
     SECU_PrintInteger(stdout, &pqg->subPrime, "SUBPRIME:", 0);
     SECU_PrintInteger(stdout, &pqg->base, "BASE:", 0);
 }
@@ -557,17 +557,17 @@ dump_pqg(PQGParams *pqg)
 static void
 dump_dsakey(DSAPrivateKey *key)
 {
     dump_pqg(&key->params);
     SECU_PrintInteger(stdout, &key->publicValue, "PUBLIC VALUE:", 0);
     SECU_PrintInteger(stdout, &key->privateValue, "PRIVATE VALUE:", 0);
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 static void
 dump_ecp(ECParams *ecp)
 {
     /* TODO other fields */
     SECU_PrintInteger(stdout, &ecp->base, "BASE POINT:", 0);
 }
 
 static void
@@ -646,17 +646,17 @@ typedef enum {
     bltestAES_GCM,        /* .                     */
     bltestCAMELLIA_ECB,   /* .                     */
     bltestCAMELLIA_CBC,   /* .                     */
     bltestSEED_ECB,       /* SEED algorithm	   */
     bltestSEED_CBC,       /* SEED algorithm	   */
     bltestRSA,            /* Public Key Ciphers    */
     bltestRSA_OAEP,       /* . (Public Key Enc.)   */
     bltestRSA_PSS,        /* . (Public Key Sig.)   */
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     bltestECDSA,          /* . (Public Key Sig.)   */
 #endif
     bltestDSA,            /* . (Public Key Sig.)   */
     bltestMD2,		  /* Hash algorithms	   */
     bltestMD5,		  /* .			   */
     bltestSHA1,           /* .			   */
     bltestSHA224,         /* .			   */
     bltestSHA256,         /* .			   */
@@ -685,17 +685,17 @@ static char *mode_strings[] =
     "aes_gcm",
     "camellia_ecb",
     "camellia_cbc",
     "seed_ecb",
     "seed_cbc",
     "rsa",
     "rsa_oaep",
     "rsa_pss",
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     "ecdsa",
 #endif
     /*"pqg",*/
     "dsa",
     "md2",
     "md5",
     "sha1",
     "sha224",
@@ -739,17 +739,17 @@ typedef struct
 {
     bltestIO   pqgdata;
     unsigned int keysize;
     bltestIO   keyseed;
     bltestIO   sigseed;
     PQGParams *pqg;
 } bltestDSAParams;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 typedef struct
 {
     char      *curveName;
     bltestIO   sigseed;
 } bltestECDSAParams;
 #endif
 
 typedef struct
@@ -758,17 +758,17 @@ typedef struct
     void *   privKey;
     void *   pubKey;
     bltestIO sig; /* if doing verify, the signature (which may come
                    * from sigfile. */
 
     union {
         bltestRSAParams rsa;
         bltestDSAParams dsa;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
         bltestECDSAParams ecdsa;
 #endif
     } cipherParams;
 } bltestAsymKeyParams;
 
 typedef struct
 {
     bltestIO   key; /* unused */
@@ -1261,17 +1261,17 @@ dsa_signDigest(void *cx, SECItem *output
 
 SECStatus
 dsa_verifyDigest(void *cx, SECItem *output, const SECItem *input)
 {
     bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx;
     return DSA_VerifyDigest((DSAPublicKey *)params->pubKey, output, input);
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 SECStatus
 ecdsa_signDigest(void *cx, SECItem *output, const SECItem *input)
 {
     bltestAsymKeyParams *params = (bltestAsymKeyParams *)cx;
     if (params->cipherParams.ecdsa.sigseed.buf.len > 0) {
         return ECDSA_SignDigestWithSeed(
                         (ECPrivateKey *)params->privKey,
                         output, input,
@@ -1715,17 +1715,17 @@ bltest_dsa_init(bltestCipherInfo *cipher
 	pubkey->publicValue.len = key->publicValue.len;
 	pubkey->publicValue.data = key->publicValue.data;
 	asymk->pubKey = pubkey;
 	cipherInfo->cipher.pubkeyCipher = dsa_verifyDigest;
     }
     return SECSuccess;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 SECStatus
 bltest_ecdsa_init(bltestCipherInfo *cipherInfo, PRBool encrypt)
 {
     int i;
     ECPrivateKey **dummyKey;
     PRIntervalTime time1, time2;
     bltestAsymKeyParams *asymk = &cipherInfo->params.asymk;
     cipherInfo->cx = asymk;
@@ -2072,30 +2072,30 @@ SHA512_restart(unsigned char *dest, cons
     SHA512_End(cx, dest, &len, MD5_LENGTH);
 finish:
     SHA512_DestroyContext(cx, PR_TRUE);
     return rv;
 }
 
 SECStatus
 pubkeyInitKey(bltestCipherInfo *cipherInfo, PRFileDesc *file,
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	      int keysize, int exponent, char *curveName)
 #else
 	      int keysize, int exponent)
 #endif
 {
     int i;
     SECStatus rv = SECSuccess;
     bltestAsymKeyParams *asymk = &cipherInfo->params.asymk;
     bltestRSAParams *rsap;
     RSAPrivateKey **rsaKey = NULL;
     bltestDSAParams *dsap;
     DSAPrivateKey **dsaKey = NULL;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     SECItem *tmpECParamsDER;
     ECParams *tmpECParams = NULL;
     SECItem ecSerialize[3];
     ECPrivateKey **ecKey = NULL;
 #endif
     switch (cipherInfo->mode) {
     case bltestRSA:
     case bltestRSA_PSS:
@@ -2127,17 +2127,17 @@ pubkeyInitKey(bltestCipherInfo *cipherIn
 	    CHECKERROR(rv, __LINE__);
 	    serialize_key(&(*dsaKey)->params.prime, 5, file);
 	} else {
 	    setupIO(cipherInfo->arena, &asymk->key, file, NULL, 0);
 	    *dsaKey = dsakey_from_filedata(&asymk->key.buf);
 	    dsap->keysize = (*dsaKey)->params.prime.len*8;
 	}
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case bltestECDSA:
 	ecKey = (ECPrivateKey **)&asymk->privKey;
 	if (curveName != NULL) {
 	    tmpECParamsDER = getECParams(curveName);
 	    rv = SECOID_Init();
 	    CHECKERROR(rv, __LINE__);
 	    rv = EC_DecodeParams(tmpECParamsDER, &tmpECParams) == SECFailure;
 	    CHECKERROR(rv, __LINE__);
@@ -2239,17 +2239,17 @@ cipherInit(bltestCipherInfo *cipherInfo,
 	break;
     case bltestDSA:
 	if (encrypt) {
 		SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
 		                  DSA_MAX_SIGNATURE_LEN);
 	}
 	return bltest_dsa_init(cipherInfo, encrypt);
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case bltestECDSA:
 	if (encrypt) {
 		SECITEM_AllocItem(cipherInfo->arena, &cipherInfo->output.buf,
 		                  2 * MAX_ECKEY_LEN);
 	}
 	return bltest_ecdsa_init(cipherInfo, encrypt);
 	break;
 #endif
@@ -2489,17 +2489,17 @@ cipherFinish(bltestCipherInfo *cipherInf
     case bltestRC5_CBC:
 	RC5_DestroyContext((RC5Context *)cipherInfo->cx, PR_TRUE);
 	break;
 #endif
     case bltestRSA:      /* keys are alloc'ed within cipherInfo's arena, */
     case bltestRSA_PSS:  /* will be freed with it. */
     case bltestRSA_OAEP:
     case bltestDSA:
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case bltestECDSA:
 #endif
     case bltestMD2: /* hash contexts are ephemeral */
     case bltestMD5:
     case bltestSHA1:
     case bltestSHA224:
     case bltestSHA256:
     case bltestSHA384:
@@ -2669,17 +2669,17 @@ print_td:
           break;
       case bltestDSA:
           if (td) {
               fprintf(stdout, "%8s", "pqg_mod");
           } else {
               fprintf(stdout, "%8d", info->params.asymk.cipherParams.dsa.keysize);
           }
           break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
       case bltestECDSA:
           if (td) {
               fprintf(stdout, "%12s", "ec_curve");
           } else {
               ECPrivateKey *key = (ECPrivateKey*)info->params.asymk.privKey;
               ECCurveName curveName = key->ecParams.name;
               fprintf(stdout, "%12s",
                       ecCurve_map[curveName]? ecCurve_map[curveName]->text:
@@ -2901,17 +2901,17 @@ get_params(PLArenaPool *arena, bltestPar
 	load_file_data(arena, &params->asymk.cipherParams.dsa.keyseed, filename,
 	               bltestBase64Encoded);
 	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j);
 	load_file_data(arena, &params->asymk.cipherParams.dsa.sigseed, filename,
 	               bltestBase64Encoded);
 	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "ciphertext",j);
 	load_file_data(arena, &params->asymk.sig, filename, bltestBase64Encoded);
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case bltestECDSA:
 	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "key", j);
 	load_file_data(arena, &params->asymk.key, filename, bltestBase64Encoded);
 	params->asymk.privKey =
 	      (void *)eckey_from_filedata(&params->asymk.key.buf);
 	sprintf(filename, "%s/tests/%s/%s%d", testdir, modestr, "sigseed", j);
 	load_file_data(arena, &params->asymk.cipherParams.ecdsa.sigseed,
 	               filename, bltestBase64Encoded);
@@ -3123,17 +3123,17 @@ dump_file(bltestCipherMode mode, char *f
 	get_file_data(filename, &item, PR_TRUE);
 	pqg = pqg_from_filedata(&item);
 	dump_pqg(pqg);
 #endif
 	DSAPrivateKey *key;
 	load_file_data(arena, &keydata, filename, bltestBase64Encoded);
 	key = dsakey_from_filedata(&keydata.buf);
 	dump_dsakey(key);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     } else if (mode == bltestECDSA) {
 	ECPrivateKey *key;
 	load_file_data(arena, &keydata, filename, bltestBase64Encoded);
 	key = eckey_from_filedata(&keydata.buf);
 	dump_eckey(key);
 #endif
     }
     PORT_FreeArena(arena, PR_FALSE);
@@ -3368,17 +3368,17 @@ enum {
     opt_SigFile,
     opt_KeySize,
     opt_Hex,
     opt_Input,
     opt_PQGFile,
     opt_Key,
     opt_HexWSpc,
     opt_Mode,
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     opt_CurveName,
 #endif
     opt_Output,
     opt_Repetitions,
     opt_ZeroBuf,
     opt_Rounds,
     opt_Seed,
     opt_SigSeedFile,
@@ -3421,17 +3421,17 @@ static secuCommandFlag bltest_options[] 
     { /* opt_SigFile      */ 'f', PR_TRUE,  0, PR_FALSE },
     { /* opt_KeySize	  */ 'g', PR_TRUE,  0, PR_FALSE },
     { /* opt_Hex	  */ 'h', PR_FALSE, 0, PR_FALSE },
     { /* opt_Input	  */ 'i', PR_TRUE,  0, PR_FALSE },
     { /* opt_PQGFile	  */ 'j', PR_TRUE,  0, PR_FALSE },
     { /* opt_Key	  */ 'k', PR_TRUE,  0, PR_FALSE },
     { /* opt_HexWSpc	  */ 'l', PR_FALSE, 0, PR_FALSE },
     { /* opt_Mode	  */ 'm', PR_TRUE,  0, PR_FALSE },
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     { /* opt_CurveName	  */ 'n', PR_TRUE,  0, PR_FALSE },
 #endif
     { /* opt_Output	  */ 'o', PR_TRUE,  0, PR_FALSE },
     { /* opt_Repetitions  */ 'p', PR_TRUE,  0, PR_FALSE },
     { /* opt_ZeroBuf	  */ 'q', PR_FALSE, 0, PR_FALSE },
     { /* opt_Rounds	  */ 'r', PR_TRUE,  0, PR_FALSE },
     { /* opt_Seed	  */ 's', PR_TRUE,  0, PR_FALSE },
     { /* opt_SigSeedFile  */ 't', PR_TRUE,  0, PR_FALSE },
@@ -3456,17 +3456,17 @@ int main(int argc, char **argv)
     SECStatus rv = SECFailure;
 
     double              totalTime;
     PRIntervalTime      time1, time2;
     PRFileDesc          *outfile = NULL;
     bltestCipherInfo    *cipherInfoListHead, *cipherInfo;
     bltestIOMode        ioMode;
     int                 bufsize, exponent, curThrdNum;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     char		*curveName = NULL;
 #endif
     int			 i, commandsEntered;
     int			 inoff, outoff;
     int                  threads = 1;
 
     secuCommand bltest;
     bltest.numCommands = sizeof(bltest_commands) / sizeof(secuCommandFlag);
@@ -3690,17 +3690,17 @@ int main(int argc, char **argv)
 	     (bltest.options[opt_HexWSpc].activated) ? bltestHexSpaceDelim :
 						       bltestBinary;
 
     if (bltest.options[opt_Exponent].activated)
 	exponent = PORT_Atoi(bltest.options[opt_Exponent].arg);
     else
 	exponent = 65537;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     if (bltest.options[opt_CurveName].activated)
 	curveName = PORT_Strdup(bltest.options[opt_CurveName].arg);
     else
 	curveName = NULL;
 #endif
 
     if (bltest.commands[cmd_Verify].activated &&
         !bltest.options[opt_SigFile].activated) {
@@ -3778,17 +3778,17 @@ int main(int argc, char **argv)
             } else {
                 if (bltest.options[opt_KeySize].activated)
                     keysize = PORT_Atoi(bltest.options[opt_KeySize].arg);
                 else
                     keysize = 64; /* use 512-bit default */
                 file = PR_Open("tmp.key", PR_WRONLY|PR_CREATE_FILE, 00660);
             }
             params->key.mode = bltestBase64Encoded;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
             pubkeyInitKey(cipherInfo, file, keysize, exponent, curveName);
 #else
             pubkeyInitKey(cipherInfo, file, keysize, exponent);
 #endif
             PR_Close(file);
         }
 
         /* set up an initialization vector. */
--- a/security/nss/cmd/certutil/certutil.c
+++ b/security/nss/cmd/certutil/certutil.c
@@ -963,25 +963,25 @@ PrintSyntax(char *progName)
     FPS "\t%s -E -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n", 
 	progName);
     FPS "\t%s -F -n nickname [-d certdir] [-P dbprefix]\n", 
 	progName);
     FPS "\t%s -G -n key-name [-h token-name] [-k rsa] [-g key-size] [-y exp]\n" 
 	"\t\t [-f pwfile] [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
     FPS "\t%s -G [-h token-name] -k dsa [-q pqgfile -g key-size] [-f pwfile]\n"
 	"\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     FPS "\t%s -G [-h token-name] -k ec -q curve [-f pwfile]\n"
 	"\t\t [-z noisefile] [-d certdir] [-P dbprefix]\n", progName);
     FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|ec|rsa|all]\n", 
 	progName);
 #else
     FPS "\t%s -K [-n key-name] [-h token-name] [-k dsa|rsa|all]\n", 
 	progName);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     FPS "\t\t [-f pwfile] [-X] [-d certdir] [-P dbprefix]\n");
     FPS "\t%s --upgrade-merge --source-dir upgradeDir --upgrade-id uniqueID\n",
 	progName);
     FPS "\t\t [--upgrade-token-name tokenName] [-d targetDBDir]\n");
     FPS "\t\t [-P targetDBPrefix] [--source-prefix upgradeDBPrefix]\n");
     FPS "\t\t [-f targetPWfile] [-@ upgradePWFile]\n");
     FPS "\t%s --merge --source-dir sourceDBDir [-d targetDBdir]\n",
 	progName);
@@ -1150,36 +1150,36 @@ static void luG(enum usage_level ul, con
     int is_my_command = (command && 0 == strcmp(command, "G"));
     if (ul == usage_all || !command || is_my_command)
     FPS "%-15s Generate a new key pair\n",
         "-G");
     if (ul == usage_selected && !is_my_command)
         return;
     FPS "%-20s Name of token in which to generate key (default is internal)\n",
         "   -h token-name");
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n",
         "   -k key-type");
     FPS "%-20s Key size in bits, (min %d, max %d, default %d) (not for ec)\n",
         "   -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS);
 #else
     FPS "%-20s Type of key pair to generate (\"dsa\", \"rsa\" (default))\n",
         "   -k key-type");
     FPS "%-20s Key size in bits, (min %d, max %d, default %d)\n",
         "   -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     FPS "%-20s Set the public exponent value (3, 17, 65537) (rsa only)\n",
         "   -y exp");
     FPS "%-20s Specify the password file\n",
         "   -f password-file");
     FPS "%-20s Specify the noise file to be used\n",
         "   -z noisefile");
     FPS "%-20s read PQG value from pqgfile (dsa only)\n",
         "   -q pqgfile");
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     FPS "%-20s Elliptic curve name (ec only)\n",
         "   -q curve-name");
     FPS "%-20s One of nistp256, nistp384, nistp521\n", "");
 #ifdef NSS_ECC_MORE_THAN_SUITE_B
     FPS "%-20s sect163k1, nistk163, sect163r1, sect163r2,\n", "");
     FPS "%-20s nistb163, sect193r1, sect193r2, sect233k1, nistk233,\n", "");
     FPS "%-20s sect233r1, nistb233, sect239k1, sect283k1, nistk283,\n", "");
     FPS "%-20s sect283r1, nistb283, sect409k1, nistk409, sect409r1,\n", "");
@@ -1281,17 +1281,17 @@ static void luK(enum usage_level ul, con
     FPS "%-15s List all private keys\n",
         "-K");
     if (ul == usage_selected && !is_my_command)
         return;
     FPS "%-20s Name of token to search (\"all\" for all tokens)\n",
         "   -h token-name ");
 
     FPS "%-20s Key type (\"all\" (default), \"dsa\","
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
                                                     " \"ec\","
 #endif
                                                     " \"rsa\")\n",
         "   -k key-type");
     FPS "%-20s The nickname of the key or associated certificate\n",
         "   -n name");
     FPS "%-20s Specify the password file\n",
         "   -f password-file");
@@ -1413,36 +1413,36 @@ static void luR(enum usage_level ul, con
     FPS "%-15s Generate a certificate request (stdout)\n",
         "-R");
     if (ul == usage_selected && !is_my_command)
         return;
     FPS "%-20s Specify the subject name (using RFC1485)\n",
         "   -s subject");
     FPS "%-20s Output the cert request to this file\n",
         "   -o output-req");
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n",
 #else
     FPS "%-20s Type of key pair to generate (\"dsa\", \"rsa\" (default))\n",
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
         "   -k key-type-or-id");
     FPS "%-20s or nickname of the cert key to use \n",
         "");
     FPS "%-20s Name of token in which to generate key (default is internal)\n",
         "   -h token-name");
     FPS "%-20s Key size in bits, RSA keys only (min %d, max %d, default %d)\n",
         "   -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS);
     FPS "%-20s Name of file containing PQG parameters (dsa only)\n",
         "   -q pqgfile");
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     FPS "%-20s Elliptic curve name (ec only)\n",
         "   -q curve-name");
     FPS "%-20s See the \"-G\" option for a full list of supported names.\n",
         "");
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     FPS "%-20s Specify the password file\n",
         "   -f pwfile");
     FPS "%-20s Key database directory (default is ~/.netscape)\n",
         "   -d keydir");
     FPS "%-20s Cert & Key database prefix\n",
         "   -P dbprefix");
     FPS "%-20s Specify the contact phone number (\"123-456-7890\")\n",
         "   -p phone");
@@ -1565,34 +1565,34 @@ static void luS(enum usage_level ul, con
     FPS "%-20s Specify the nickname of the cert\n",
         "   -n key-name");
     FPS "%-20s Specify the subject name (using RFC1485)\n",
         "   -s subject");
     FPS "%-20s The nickname of the issuer cert\n",
         "   -c issuer-name");
     FPS "%-20s Set the certificate trust attributes (see -A above)\n",
         "   -t trustargs");
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     FPS "%-20s Type of key pair to generate (\"dsa\", \"ec\", \"rsa\" (default))\n",
 #else
     FPS "%-20s Type of key pair to generate (\"dsa\", \"rsa\" (default))\n",
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
         "   -k key-type-or-id");
     FPS "%-20s Name of token in which to generate key (default is internal)\n",
         "   -h token-name");
     FPS "%-20s Key size in bits, RSA keys only (min %d, max %d, default %d)\n",
         "   -g key-size", MIN_KEY_BITS, MAX_KEY_BITS, DEFAULT_KEY_BITS);
     FPS "%-20s Name of file containing PQG parameters (dsa only)\n",
         "   -q pqgfile");
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     FPS "%-20s Elliptic curve name (ec only)\n",
         "   -q curve-name");
     FPS "%-20s See the \"-G\" option for a full list of supported names.\n",
         "");
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     FPS "%-20s Self sign\n",
         "   -x");
     FPS "%-20s Cert serial number\n",
         "   -m serial-number");
     FPS "%-20s Time Warp\n",
         "   -w warp-months");
     FPS "%-20s Months valid (default is 3)\n",
         "   -v months-valid");
@@ -2443,22 +2443,22 @@ certutil_main(int argc, char **argv, PRB
     if (certutil.options[opt_KeySize].activated) {
 	keysize = PORT_Atoi(certutil.options[opt_KeySize].arg);
 	if ((keysize < MIN_KEY_BITS) || (keysize > MAX_KEY_BITS)) {
 	    PR_fprintf(PR_STDERR, 
                        "%s -g:  Keysize must be between %d and %d.\n",
 		       progName, MIN_KEY_BITS, MAX_KEY_BITS);
 	    return 255;
 	}
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	if (keytype == ecKey) {
 	    PR_fprintf(PR_STDERR, "%s -g:  Not for ec keys.\n", progName);
 	    return 255;
 	}
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     }
 
     /*  -h specify token name  */
     if (certutil.options[opt_TokenName].activated) {
 	if (PL_strcmp(certutil.options[opt_TokenName].arg, "all") == 0)
 	    slotname = NULL;
 	else
@@ -2478,20 +2478,20 @@ certutil_main(int argc, char **argv, PRB
 
     /*  -k key type  */
     if (certutil.options[opt_KeyType].activated) {
 	char * arg = certutil.options[opt_KeyType].arg;
 	if (PL_strcmp(arg, "rsa") == 0) {
 	    keytype = rsaKey;
 	} else if (PL_strcmp(arg, "dsa") == 0) {
 	    keytype = dsaKey;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	} else if (PL_strcmp(arg, "ec") == 0) {
 	    keytype = ecKey;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	} else if (PL_strcmp(arg, "all") == 0) {
 	    keytype = nullKey;
 	} else {
 	    /* use an existing private/public key pair */
 	    keysource = arg;
 	}
     } else if (certutil.commands[cmd_ListKeys].activated) {
 	keytype = nullKey;
@@ -2534,26 +2534,26 @@ certutil_main(int argc, char **argv, PRB
             srcCertPrefix = strdup(certutil.options[opt_SourcePrefix].arg);
         } else {
             Usage(progName);
         }
     }
 
     /*  -q PQG file or curve name */
     if (certutil.options[opt_PQGFile].activated) {
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	if ((keytype != dsaKey) && (keytype != ecKey)) {
 	    PR_fprintf(PR_STDERR, "%s -q: specifies a PQG file for DSA keys" \
 		       " (-k dsa) or a named curve for EC keys (-k ec)\n)",
 	               progName);
 #else   /* } */
 	if (keytype != dsaKey) {
 	    PR_fprintf(PR_STDERR, "%s -q: PQG file is for DSA key (-k dsa).\n)",
 	               progName);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	    return 255;
 	}
     }
 
     /*  -s subject name  */
     if (certutil.options[opt_Subject].activated) {
 	subject = CERT_AsciiToName(certutil.options[opt_Subject].arg);
 	if (!subject) {
--- a/security/nss/cmd/certutil/keystuff.c
+++ b/security/nss/cmd/certutil/keystuff.c
@@ -351,17 +351,17 @@ CERTUTIL_FileForRNG(const char *noise)
 	    PK11_RandomUpdate(buf,count);
 	}
     } while (count > 0);
 
     PR_Close(fd);
     return SECSuccess;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 typedef struct curveNameTagPairStr {
     char *curveName;
     SECOidTag curveOidTag;
 } CurveNameTagPair;
 
 #define DEFAULT_CURVE_OID_TAG  SEC_OID_SECG_EC_SECP192R1
 /* #define DEFAULT_CURVE_OID_TAG  SEC_OID_SECG_EC_SECP160R1 */
 
@@ -479,17 +479,17 @@ getECParams(const char *curve)
      * oidData->oid.data so we simply prepend 0x06 and OID length
      */
     ecparams->data[0] = SEC_ASN1_OBJECT_ID;
     ecparams->data[1] = oidData->oid.len;
     memcpy(ecparams->data + 2, oidData->oid.data, oidData->oid.len);
 
     return ecparams;
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 SECKEYPrivateKey *
 CERTUTIL_GeneratePrivateKey(KeyType keytype, PK11SlotInfo *slot, int size,
 			    int publicExponent, const char *noise, 
 			    SECKEYPublicKey **pubkeyp, const char *pqgFile,
 			    PK11AttrFlags attrFlags, CK_FLAGS opFlagsOn,
 			    CK_FLAGS opFlagsOff, secuPWData *pwdata)
 {
@@ -540,37 +540,37 @@ CERTUTIL_GeneratePrivateKey(KeyType keyt
 	    if (dsaparams == NULL)
 	    	return NULL;
 	    params = dsaparams;
 	} else {
 	    /* cast away const, and don't set dsaparams */
 	    params = (void *)&default_pqg_params;
 	}
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case ecKey:
 	mechanism = CKM_EC_KEY_PAIR_GEN;
 	/* For EC keys, PQGFile determines EC parameters */
 	if ((params = (void *) getECParams(pqgFile)) == NULL)
 	    return NULL;
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     default:
 	return NULL;
     }
 
     fprintf(stderr, "\n\n");
     fprintf(stderr, "Generating key.  This may take a few moments...\n\n");
 
     privKey = PK11_GenerateKeyPairWithOpFlags(slot, mechanism, params, pubkeyp,
 				attrFlags, opFlagsOn, opFlagsOn|opFlagsOff,
 				pwdata /*wincx*/);
     /* free up the params */
     switch (keytype) {
     case dsaKey: if (dsaparams) CERTUTIL_DestroyParamsPQG(dsaparams); 
 	                                                      break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case ecKey: SECITEM_FreeItem((SECItem *)params, PR_TRUE); break;
 #endif
     default: /* nothing to free */                            break;
     }
     return privKey;
 }
--- a/security/nss/cmd/fipstest/fipstest.c
+++ b/security/nss/cmd/fipstest/fipstest.c
@@ -17,17 +17,17 @@
 #include "hasht.h"
 #include "lowkeyi.h"
 #include "softoken.h"
 
 #if 0
 #include "../../lib/freebl/mpi/mpi.h"
 #endif
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 extern SECStatus
 EC_DecodeParams(const SECItem *encodedParams, ECParams **ecparams);
 extern SECStatus
 EC_CopyParams(PLArenaPool *arena, ECParams *dstParams,
               const ECParams *srcParams);
 #endif
 
 #define ENCRYPT 1
@@ -1844,17 +1844,17 @@ int get_next_line(FILE *req, char *key, 
 	} else {
 	    writeto[w++] = c;
 	}
     }
     writeto[w] = '\0';
     return (c == EOF) ? -1 : ignore;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 typedef struct curveNameTagPairStr {
     char *curveName;
     SECOidTag curveOidTag;
 } CurveNameTagPair;
 
 #define DEFAULT_CURVE_OID_TAG  SEC_OID_SECG_EC_SECP192R1
 /* #define DEFAULT_CURVE_OID_TAG  SEC_OID_SECG_EC_SECP160R1 */
 
@@ -2525,17 +2525,17 @@ ecdsa_sigver_test(char *reqfn)
 	}
     }
 loser:
     if (ecpub.ecParams.arena != NULL) {
 	PORT_FreeArena(ecpub.ecParams.arena, PR_FALSE);
     }
     fclose(ecdsareq);
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 
 /*
  * Read a value from the test and allocate the result.
  */
 static unsigned char *
 alloc_value(char *buf, int *len)
 {
@@ -5322,17 +5322,17 @@ int main(int argc, char **argv)
             dsa_pqgver_test(argv[3]);
         } else if (strcmp(argv[2], "siggen") == 0) {
             /* Signature Generation Test */
             dsa_siggen_test(argv[3]);
         } else if (strcmp(argv[2], "sigver") == 0) {
             /* Signature Verification Test */
             dsa_sigver_test(argv[3]);
         }
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     /*************/
     /*   ECDSA   */
     /*************/
     } else if (strcmp(argv[1], "ecdsa") == 0) {
 	/* argv[2]=keypair|pkv|siggen|sigver argv[3]=<test name>.req */
 	if (       strcmp(argv[2], "keypair") == 0) {
 	    /* Key Pair Generation Test */
 	    ecdsa_keypair_test(argv[3]);
@@ -5341,17 +5341,17 @@ int main(int argc, char **argv)
 	    ecdsa_pkv_test(argv[3]);
 	} else if (strcmp(argv[2], "siggen") == 0) {
 	    /* Signature Generation Test */
 	    ecdsa_siggen_test(argv[3]);
 	} else if (strcmp(argv[2], "sigver") == 0) {
 	    /* Signature Verification Test */
 	    ecdsa_sigver_test(argv[3]);
 	}
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     /*************/
     /*   RNG     */
     /*************/
     } else if (strcmp(argv[1], "rng") == 0) {
 	/* argv[2]=vst|mct argv[3]=<test name>.req */
 	if (       strcmp(argv[2], "vst") == 0) {
 	    /* Variable Seed Test */
 	    rng_vst(argv[3]);
--- a/security/nss/cmd/lib/secutil.c
+++ b/security/nss/cmd/lib/secutil.c
@@ -1359,17 +1359,17 @@ secu_PrintAttribute(FILE *out, SEC_PKCS7
 		    SECU_PrintTimeChoice(out, value, om, level+1);
 		    break;
 		}
 	    }
 	}
     }
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 static void
 secu_PrintECPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level)
 {
     SECItem curveOID = { siBuffer, NULL, 0};
 
     SECU_Indent(out, level); fprintf(out, "%s:\n", m);
     SECU_PrintInteger(out, &pk->u.ec.publicValue, "PublicValue", level+1);
     /* For named curves, the DEREncodedParams field contains an
@@ -1377,17 +1377,17 @@ secu_PrintECPublicKey(FILE *out, SECKEYP
      */
     if ((pk->u.ec.DEREncodedParams.len > 2) &&
 	(pk->u.ec.DEREncodedParams.data[0] == 0x06)) {
         curveOID.len = pk->u.ec.DEREncodedParams.data[1];
 	curveOID.data = pk->u.ec.DEREncodedParams.data + 2;
 	SECU_PrintObjectID(out, &curveOID, "Curve", level +1);
     }
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 void
 SECU_PrintRSAPublicKey(FILE *out, SECKEYPublicKey *pk, char *m, int level)
 {
     SECU_Indent(out, level); fprintf(out, "%s:\n", m);
     SECU_PrintInteger(out, &pk->u.rsa.modulus, "Modulus", level+1);
     SECU_PrintInteger(out, &pk->u.rsa.publicExponent, "Exponent", level+1);
     if (pk->u.rsa.publicExponent.len == 1 &&
@@ -1421,17 +1421,17 @@ secu_PrintSubjectPublicKeyInfo(FILE *out
 	case rsaKey:
 	    SECU_PrintRSAPublicKey(out, pk, "RSA Public Key", level +1);
 	    break;
 
 	case dsaKey:
 	    SECU_PrintDSAPublicKey(out, pk, "DSA Public Key", level +1);
 	    break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	case ecKey:
 	    secu_PrintECPublicKey(out, pk, "EC Public Key", level +1);
 	    break;
 #endif
 
 	case dhKey:
 	case fortezzaKey:
 	case keaKey:
--- a/security/nss/cmd/selfserv/selfserv.c
+++ b/security/nss/cmd/selfserv/selfserv.c
@@ -155,21 +155,21 @@ static void
 PrintUsageHeader(const char *progName)
 {
     fprintf(stderr, 
 "Usage: %s -n rsa_nickname -p port [-BDENRbjlmrsuvx] [-w password]\n"
 "         [-t threads] [-i pid_file] [-c ciphers] [-Y] [-d dbdir] [-g numblocks]\n"
 "         [-f password_file] [-L [seconds]] [-M maxProcs] [-P dbprefix]\n"
 "         [-V [min-version]:[max-version]] [-a sni_name]\n"
 "         [ T <good|revoked|unknown|badsig|corrupted|none|ocsp>] [-A ca]\n"
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 "         [-C SSLCacheEntries] [-e ec_nickname]\n"
 #else
 "         [-C SSLCacheEntries]\n"
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
         ,progName);
 }
 
 static void
 PrintParameterUsage()
 {
     fputs(
 "-V [min]:[max] restricts the set of enabled SSL/TLS protocol versions.\n"
@@ -2128,17 +2128,17 @@ SECStatus enableOCSPStapling(const char*
     return SECFailure;
 }
 
 int
 main(int argc, char **argv)
 {
     char *               progName    = NULL;
     char *               nickName    = NULL;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     char *               ecNickName   = NULL;
 #endif
     const char *         fileName    = NULL;
     char *               cipherString= NULL;
     const char *         dir         = ".";
     char *               passwd      = NULL;
     char *               pwfile      = NULL;
     const char *         pidFile     = NULL;
@@ -2241,19 +2241,19 @@ main(int argc, char **argv)
                       PORT_Strdup(optstate->value); break;
 
 	case 'b': bindOnly = PR_TRUE; break;
 
 	case 'c': cipherString = PORT_Strdup(optstate->value); break;
 
 	case 'd': dir = optstate->value; break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	case 'e': ecNickName = PORT_Strdup(optstate->value); break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 	case 'f':
             pwdata.source = PW_FROMFILE;
             pwdata.data = pwfile = PORT_Strdup(optstate->value);
             break;
 
         case 'g': 
             testBulk = PR_TRUE;
@@ -2357,17 +2357,17 @@ main(int argc, char **argv)
 	}
         if (listen_sock) {
             PR_Close(listen_sock);
         }
 	exit(0);
     }
 
     if ((nickName == NULL)
- #ifdef NSS_ENABLE_ECC
+ #ifndef NSS_DISABLE_ECC
 						&& (ecNickName == NULL)
  #endif
     ) {
 
 	fprintf(stderr, "Required arg '-n' (rsa nickname) not supplied.\n");
 	fprintf(stderr, "Run '%s -h' for usage information.\n", progName);
         exit(6);
     }
@@ -2588,17 +2588,17 @@ main(int argc, char **argv)
 		exit(14);
 	    }
 	    fprintf(stderr, "selfserv: %s can%s bypass\n", nickName,
 		    bypassOK ? "" : "not");
 	}
 	setupCertStatus(certStatusArena, ocspStaplingMode, cert[kt_rsa], kt_rsa,
 			&pwdata);
     }
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     if (ecNickName) {
 	cert[kt_ecdh] = PK11_FindCertFromNickname(ecNickName, &pwdata);
 	if (cert[kt_ecdh] == NULL) {
 	    fprintf(stderr, "selfserv: Can't find certificate %s\n",
 		    ecNickName);
 	    exit(13);
 	}
 	privKey[kt_ecdh] = PK11_FindKeyByAnyCert(cert[kt_ecdh], &pwdata);
@@ -2615,17 +2615,17 @@ main(int argc, char **argv)
 		exit(15);
 	    }
 	    fprintf(stderr, "selfserv: %s can%s bypass\n", ecNickName,
 		    bypassOK ? "" : "not");
 	}
 	setupCertStatus(certStatusArena, ocspStaplingMode, cert[kt_ecdh], kt_ecdh,
 			&pwdata);
     }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     if (testbypass)
 	goto cleanup;
 
 /* allocate the array of thread slots, and launch the worker threads. */
     rv = launch_threads(&jobLoop, 0, 0, requestCert, useLocalThreads);
 
     if (rv == SECSuccess && logStats) {
@@ -2686,17 +2686,17 @@ cleanup:
         PORT_Free(passwd);
     }
     if (pwfile) {
         PORT_Free(pwfile);
     }
     if (certPrefix && certPrefix != emptyString) {                            
         PORT_Free(certPrefix);
     }
- #ifdef NSS_ENABLE_ECC
+ #ifndef NSS_DISABLE_ECC
     if (ecNickName) {
         PORT_Free(ecNickName);
     }
  #endif
 
     if (hasSidCache) {
 	SSL_ShutdownServerSessionIDCache();
     }
--- a/security/nss/coreconf/config.mk
+++ b/security/nss/coreconf/config.mk
@@ -141,20 +141,20 @@ endif
 #######################################################################
 
 -include $(MKDEPENDENCIES)
 
 #######################################################################
 # [16.0] Global environ ment defines
 #######################################################################
 
-ifdef NSS_ENABLE_ECC
-DEFINES += -DNSS_ENABLE_ECC
+ifdef NSS_DISABLE_ECC
+DEFINES += -DNSS_DISABLE_ECC
 endif
-
+ 
 ifdef NSS_ECC_MORE_THAN_SUITE_B
 DEFINES += -DNSS_ECC_MORE_THAN_SUITE_B
 endif
 
 ifdef NSS_ALLOW_UNSUPPORTED_CRITICAL
 DEFINES += -DNSS_ALLOW_UNSUPPORTED_CRITICAL
 endif
 
--- a/security/nss/coreconf/coreconf.dep
+++ b/security/nss/coreconf/coreconf.dep
@@ -5,9 +5,8 @@
 
 /*
  * A dummy header file that is a dependency for all the object files.
  * Used to force a full recompilation of NSS in Mozilla's Tinderbox
  * depend builds.  See comments in rules.mk.
  */
 
 #error "Do not include this header file."
-
--- a/security/nss/coverage/cov.sh
+++ b/security/nss/coverage/cov.sh
@@ -27,17 +27,16 @@ DATE_DIR="${BRANCH_DIR}/${DATE}-${ARCH}"
 CVS_DIR="${DATE_DIR}/cvs_mozilla"
 TCOV_DIR="${DATE_DIR}/tcov_mozilla"
 
 CVS_CHECKOUT_BRANCH="cvs_checkout_${BRANCH}"
 
 export HOST=`hostname`
 export DOMSUF=red.iplanet.com
 
-export NSS_ENABLE_ECC=1
 export NSS_ECC_MORE_THAN_SUITE_B=1
 export IOPR_HOSTADDR_LIST="dochinups.red.iplanet.com"
 export NSS_AIA_PATH="/share/builds/mccrel3/security/aia_certs"
 export NSS_AIA_HTTP="http://cindercone.red.iplanet.com/share/builds/mccrel3/security/aia_certs"
 
 export USE_TCOV=1
 export SUN_PROFDATA_DIR="${DATE_DIR}"
 export SUN_PROFDATA="tcov_data"
--- a/security/nss/lib/freebl/Makefile
+++ b/security/nss/lib/freebl/Makefile
@@ -444,24 +444,24 @@ else
  	ifndef NS_USE_GCC
  	   MPCPU_SRCS =
  	   ASFILES += mpcpucache_x86.s
  	endif
     endif
 endif # Solaris for non-sparc family CPUs
 endif # target == SunOS
 
-ifdef NSS_ENABLE_ECC
+ifndef NSS_DISABLE_ECC
     ifdef ECL_USE_FP
 	#enable floating point ECC code	
 	DEFINES  += -DECL_USE_FP
 	ECL_SRCS += ecp_fp160.c ecp_fp192.c ecp_fp224.c ecp_fp.c
 	ECL_HDRS += ecp_fp.h
     endif
-endif # NSS_ENABLE_ECC
+endif
 
 #######################################################################
 # (5) Execute "global" rules. (OPTIONAL)                              #
 #######################################################################
 
 include $(CORE_DEPTH)/coreconf/rules.mk
 
 #######################################################################
--- a/security/nss/lib/freebl/ec.c
+++ b/security/nss/lib/freebl/ec.c
@@ -11,17 +11,17 @@
 #include "prerr.h"
 #include "secerr.h"
 #include "secmpi.h"
 #include "secitem.h"
 #include "mplogic.h"
 #include "ec.h"
 #include "ecl.h"
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 
 /* 
  * Returns true if pointP is the point at infinity, false otherwise
  */
 PRBool
 ec_point_at_infinity(SECItem *pointP)
 {
     unsigned int i;
@@ -187,28 +187,28 @@ cleanup:
     mp_clear(&b);
     if (err) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
 
     return rv;
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 /* Generates a new EC key pair. The private key is a supplied
  * value and the public key is the result of performing a scalar 
  * point multiplication of that value with the curve's base point.
  */
 SECStatus 
 ec_NewKey(ECParams *ecParams, ECPrivateKey **privKey, 
     const unsigned char *privKeyBytes, int privKeyLen)
 {
     SECStatus rv = SECFailure;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     PLArenaPool *arena;
     ECPrivateKey *key;
     mp_int k;
     mp_err err = MP_OKAY;
     int len;
 
 #if EC_DEBUG
     printf("ec_NewKey called\n");
@@ -296,41 +296,41 @@ cleanup:
 	PORT_FreeArena(arena, PR_TRUE);
 
 #if EC_DEBUG
     printf("ec_NewKey returning %s\n", 
 	(rv == SECSuccess) ? "success" : "failure");
 #endif
 #else
     PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     return rv;
 
 }
 
 /* Generates a new EC key pair. The private key is a supplied
  * random value (in seed) and the public key is the result of 
  * performing a scalar point multiplication of that value with 
  * the curve's base point.
  */
 SECStatus 
 EC_NewKeyFromSeed(ECParams *ecParams, ECPrivateKey **privKey, 
     const unsigned char *seed, int seedlen)
 {
     SECStatus rv = SECFailure;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     rv = ec_NewKey(ecParams, privKey, seed, seedlen);
 #else
     PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     return rv;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 /* Generate a random private key using the algorithm A.4.1 of ANSI X9.62,
  * modified a la FIPS 186-2 Change Notice 1 to eliminate the bias in the
  * random number generator.
  *
  * Parameters
  * - order: a buffer that holds the curve's group order
  * - len: the length in octets of the order buffer
  *
@@ -376,27 +376,27 @@ cleanup:
 	rv = SECFailure;
     }
     if (rv != SECSuccess && privKeyBytes) {
 	PORT_Free(privKeyBytes);
 	privKeyBytes = NULL;
     }
     return privKeyBytes;
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 /* Generates a new EC key pair. The private key is a random value and
  * the public key is the result of performing a scalar point multiplication
  * of that value with the curve's base point.
  */
 SECStatus 
 EC_NewKey(ECParams *ecParams, ECPrivateKey **privKey)
 {
     SECStatus rv = SECFailure;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     int len;
     unsigned char *privKeyBytes = NULL;
 
     if (!ecParams) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
 
@@ -411,31 +411,31 @@ cleanup:
 	PORT_ZFree(privKeyBytes, len);
     }
 #if EC_DEBUG
     printf("EC_NewKey returning %s\n", 
 	(rv == SECSuccess) ? "success" : "failure");
 #endif
 #else
     PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     
     return rv;
 }
 
 /* Validates an EC public key as described in Section 5.2.2 of
  * X9.62. The ECDH primitive when used without the cofactor does
  * not address small subgroup attacks, which may occur when the
  * public key is not valid. These attacks can be prevented by 
  * validating the public key before using ECDH.
  */
 SECStatus 
 EC_ValidatePublicKey(ECParams *ecParams, SECItem *publicValue)
 {
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     mp_int Px, Py;
     ECGroup *group = NULL;
     SECStatus rv = SECFailure;
     mp_err err = MP_OKAY;
     int len;
 
     if (!ecParams || !publicValue) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
@@ -501,17 +501,17 @@ cleanup:
     if (err) {
 	MP_TO_SEC_ERROR(err);
 	rv = SECFailure;
     }
     return rv;
 #else
     PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
     return SECFailure;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 }
 
 /* 
 ** Performs an ECDH key derivation by computing the scalar point
 ** multiplication of privateValue and publicValue (with or without the
 ** cofactor) and returns the x-coordinate of the resulting elliptic
 ** curve point in derived secret.  If successful, derivedSecret->data
 ** is set to the address of the newly allocated buffer containing the
@@ -522,17 +522,17 @@ cleanup:
 SECStatus 
 ECDH_Derive(SECItem  *publicValue, 
             ECParams *ecParams,
             SECItem  *privateValue,
             PRBool    withCofactor,
             SECItem  *derivedSecret)
 {
     SECStatus rv = SECFailure;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     unsigned int len = 0;
     SECItem pointQ = {siBuffer, NULL, 0};
     mp_int k; /* to hold the private value */
     mp_int cofactor;
     mp_err err = MP_OKAY;
 #if EC_DEBUG
     int i;
 #endif
@@ -591,31 +591,31 @@ cleanup:
 	MP_TO_SEC_ERROR(err);
     }
 
     if (pointQ.data) {
 	PORT_ZFree(pointQ.data, 2*len + 1);
     }
 #else
     PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     return rv;
 }
 
 /* Computes the ECDSA signature (a concatenation of two values r and s)
  * on the digest using the given key and the random value kb (used in
  * computing s).
  */
 SECStatus 
 ECDSA_SignDigestWithSeed(ECPrivateKey *key, SECItem *signature, 
     const SECItem *digest, const unsigned char *kb, const int kblen)
 {
     SECStatus rv = SECFailure;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     mp_int x1;
     mp_int d, k;     /* private key, random integer */
     mp_int r, s;     /* tuple (r, s) is the signature */
     mp_int n;
     mp_err err = MP_OKAY;
     ECParams *ecParams = NULL;
     SECItem kGpoint = { siBuffer, NULL, 0};
     int flen = 0;    /* length in bytes of the field size */
@@ -817,30 +817,30 @@ cleanup:
     }
 
 #if EC_DEBUG
     printf("ECDSA signing with seed %s\n",
 	(rv == SECSuccess) ? "succeeded" : "failed");
 #endif
 #else
     PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
    return rv;
 }
 
 /*
 ** Computes the ECDSA signature on the digest using the given key 
 ** and a random seed.
 */
 SECStatus 
 ECDSA_SignDigest(ECPrivateKey *key, SECItem *signature, const SECItem *digest)
 {
     SECStatus rv = SECFailure;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     int len;
     unsigned char *kBytes= NULL;
 
     if (!key) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
 	return SECFailure;
     }
 
@@ -858,30 +858,30 @@ cleanup:
     }
 
 #if EC_DEBUG
     printf("ECDSA signing %s\n",
 	(rv == SECSuccess) ? "succeeded" : "failed");
 #endif
 #else
     PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     return rv;
 }
 
 /*
 ** Checks the signature on the given digest using the key provided.
 */
 SECStatus 
 ECDSA_VerifyDigest(ECPublicKey *key, const SECItem *signature, 
                  const SECItem *digest)
 {
     SECStatus rv = SECFailure;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     mp_int r_, s_;           /* tuple (r', s') is received signature) */
     mp_int c, u1, u2, v;     /* intermediate values used in verification */
     mp_int x1;
     mp_int n;
     mp_err err = MP_OKAY;
     ECParams *ecParams = NULL;
     SECItem pointC = { siBuffer, NULL, 0 };
     int slen;       /* length in bytes of a half signature (r or s) */
@@ -1068,13 +1068,13 @@ cleanup:
     }
 
 #if EC_DEBUG
     printf("ECDSA verification %s\n",
 	(rv == SECSuccess) ? "succeeded" : "failed");
 #endif
 #else
     PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     return rv;
 }
 
--- a/security/nss/lib/freebl/loader.c
+++ b/security/nss/lib/freebl/loader.c
@@ -75,16 +75,18 @@ getLibName(void)
     }
     if (found_int_hybrid) {
 	return int_hybrid_shared_lib;
     }
     return non_hybrid_shared_lib;
 }
 
 #elif defined(HPUX) && !defined(NSS_USE_64) && !defined(__ia64)
+#include <unistd.h>
+
 /* This code tests to see if we're running on a PA2.x CPU.
 ** It returns true (1) if so, and false (0) otherwise.
 */
 static const char *
 getLibName(void)
 {
     long cpu = sysconf(_SC_CPU_VERSION);
     return (cpu == CPU_PA_RISC2_0) 
--- a/security/nss/lib/freebl/manifest.mn
+++ b/security/nss/lib/freebl/manifest.mn
@@ -64,17 +64,17 @@ PRIVATE_EXPORTS = \
 	ecl-curve.h \
 	$(NULL)
 
 MPI_HDRS = mpi-config.h mpi.h mpi-priv.h mplogic.h mpprime.h logtab.h mp_gf2m.h
 MPI_SRCS = mpprime.c mpmontg.c mplogic.c mpi.c mp_gf2m.c
 
 
 ECL_HDRS = ecl-exp.h ecl.h ec2.h ecp.h ecl-priv.h
-ifdef NSS_ENABLE_ECC
+ifndef NSS_DISABLE_ECC
 ECL_SRCS = ecl.c ecl_curve.c ecl_mult.c ecl_gf.c \
 	ecp_aff.c ecp_jac.c ecp_mont.c \
 	ec_naf.c ecp_jm.c ecp_256.c ecp_384.c ecp_521.c \
 	ecp_256_32.c
 ifdef NSS_ECC_MORE_THAN_SUITE_B
 ECL_SRCS += ec2_aff.c ec2_mont.c ec2_proj.c \
 	ec2_163.c ec2_193.c ec2_233.c \
 	ecp_192.c ecp_224.c
--- a/security/nss/lib/freebl/mpi/target.mk
+++ b/security/nss/lib/freebl/mpi/target.mk
@@ -200,32 +200,32 @@ MPICMN += $(MP_CONFIG)
 mpi_amd64_asm.o: mpi_amd64_sun.s
 	$(AS) -xarch=generic64 -P -D_ASM mpi_amd64_sun.s
 endif
 
 ifeq ($(TARGET),WIN32)
 ifeq ($(CPU_ARCH),x86_64)
 AS_OBJS = mpi_amd64.obj mpi_amd64_masm.obj mp_comba_amd64_masm.asm
 CFLAGS  = -Od -Z7 -MDd -W3 -nologo -DDEBUG -D_DEBUG -UNDEBUG -DDEBUG_$(USER)
-CFLAGS += -DWIN32 -DWIN64 -D_WINDOWS -D_AMD_64_ -D_M_AMD64 -DWIN95 -DXP_PC -DNSS_ENABLE_ECC 
+CFLAGS += -DWIN32 -DWIN64 -D_WINDOWS -D_AMD_64_ -D_M_AMD64 -DWIN95 -DXP_PC
 CFLAGS += $(MPICMN)
 
 $(AS_OBJS): %.obj : %.asm
 	ml64 -Cp -Sn -Zi -coff -nologo -c $<
 
 $(LIBOBJS): %.obj : %.c 
 	cl $(CFLAGS) -Fo$@ -c $<
 else
 AS_OBJS = mpi_x86.obj
 MPICMN += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE -DMP_ASSEMBLY_DIV_2DX1D
 MPICMN += -DMP_USE_UINT_DIGIT -DMP_NO_MP_WORD -DMP_API_COMPATIBLE 
 MPICMN += -DMP_MONT_USE_MP_MUL 
 MPICMN += -DMP_CHAR_STORE_SLOW -DMP_IS_LITTLE_ENDIAN
 CFLAGS  = -Od -Z7 -MDd -W3 -nologo -DDEBUG -D_DEBUG -UNDEBUG -DDEBUG_$(USER)
-CFLAGS += -DWIN32 -D_WINDOWS -D_X86_ -DWIN95 -DXP_PC -DNSS_ENABLE_ECC 
+CFLAGS += -DWIN32 -D_WINDOWS -D_X86_ -DWIN95 -DXP_PC
 CFLAGS += $(MPICMN)
 
 $(AS_OBJS): %.obj : %.asm
 	ml -Cp -Sn -Zi -coff -nologo -c $<
 
 $(LIBOBJS): %.obj : %.c 
 	cl $(CFLAGS) -Fo$@ -c $<
 
--- a/security/nss/lib/nss/nss.h
+++ b/security/nss/lib/nss/nss.h
@@ -4,17 +4,17 @@
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef __nss_h_
 #define __nss_h_
 
 /* The private macro _NSS_ECC_STRING is for NSS internal use only. */
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #ifdef NSS_ECC_MORE_THAN_SUITE_B
 #define _NSS_ECC_STRING " Extended ECC"
 #else
 #define _NSS_ECC_STRING " Basic ECC"
 #endif
 #else
 #define _NSS_ECC_STRING ""
 #endif
--- a/security/nss/lib/softoken/ecdecode.c
+++ b/security/nss/lib/softoken/ecdecode.c
@@ -1,13 +1,13 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 
 #include "blapi.h"
 #include "secoid.h"
 #include "secitem.h"
 #include "secerr.h"
 #include "ec.h"
 #include "ecl-curve.h"
 
@@ -598,9 +598,9 @@ EC_DecodeParams(const SECItem *encodedPa
 	PORT_FreeArena(arena, PR_TRUE);	
 	return SECFailure;
     } else {
 	*ecparams = params;;
 	return SECSuccess;
     }
 }
 
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
--- a/security/nss/lib/softoken/fipstest.c
+++ b/security/nss/lib/softoken/fipstest.c
@@ -8,17 +8,17 @@
 #include "softoken.h"   /* Required for RC2-ECB, RC2-CBC, RC4, DES-ECB,  */
                         /*              DES-CBC, DES3-ECB, DES3-CBC, RSA */
                         /*              and DSA.                         */
 #include "seccomon.h"   /* Required for RSA and DSA. */
 #include "lowkeyi.h"    /* Required for RSA and DSA. */
 #include "pkcs11.h"     /* Required for PKCS #11. */
 #include "secerr.h"
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #include "ec.h"         /* Required for ECDSA */
 #endif
 
 
 /* FIPS preprocessor directives for RC2-ECB and RC2-CBC.        */
 #define FIPS_RC2_KEY_LENGTH                      5  /*  40-bits */
 #define FIPS_RC2_ENCRYPT_LENGTH                  8  /*  64-bits */
 #define FIPS_RC2_DECRYPT_LENGTH                  8  /*  64-bits */
@@ -1607,17 +1607,17 @@ sftk_fips_RSA_PowerUpSelfTest( void )
 rsa_loser:
 
     nsslowkey_DestroyPublicKey( rsa_public_key );
     nsslowkey_DestroyPrivateKey( rsa_private_key );
 
     return( CKR_DEVICE_ERROR );
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 
 static CK_RV
 sftk_fips_ECDSA_Test(const PRUint8 *encodedParams, 
                      unsigned int encodedParamsLen,
                      const PRUint8 *knownSignature, 
                      unsigned int knownSignatureLen) {
 
     /* ECDSA Known Seed info for curves nistp256 and nistk283  */
@@ -1790,17 +1790,17 @@ sftk_fips_ECDSA_PowerUpSelfTest() {
     if (crv != CKR_OK) {
         return( CKR_DEVICE_ERROR );
     }
 #endif
 
     return( CKR_OK );
 }
 
-#endif    /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 static CK_RV
 sftk_fips_DSA_PowerUpSelfTest( void )
 {
     /* DSA Known P (1024-bits), Q (160-bits), and G (1024-bits) Values. */
     static const PRUint8 dsa_P[] = {
          0x80,0xb0,0xd1,0x9d,0x6e,0xa4,0xf3,0x28, 
          0x9f,0x24,0xa9,0x8a,0x49,0xd0,0x0c,0x63, 
@@ -2075,17 +2075,17 @@ sftk_fipsPowerUpSelfTest( void )
         return rv;
 
     /* RNG Power-Up SelfTest(s). */
     rv = sftk_fips_RNG_PowerUpSelfTest();
 
     if( rv != CKR_OK )
         return rv;
     
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     /* ECDSA Power-Up SelfTest(s). */
     rv = sftk_fips_ECDSA_PowerUpSelfTest();
 
     if( rv != CKR_OK )
         return rv;
 #endif
 
     /* Software/Firmware Integrity Test. */
--- a/security/nss/lib/softoken/legacydb/keydb.c
+++ b/security/nss/lib/softoken/legacydb/keydb.c
@@ -1138,22 +1138,22 @@ nsslowkey_KeyForCertExists(NSSLOWKEYDBHa
       case NSSLOWKEYDSAKey:
 	namekey.data = pubkey->u.dsa.publicValue.data;
 	namekey.size = pubkey->u.dsa.publicValue.len;
 	break;
       case NSSLOWKEYDHKey:
 	namekey.data = pubkey->u.dh.publicValue.data;
 	namekey.size = pubkey->u.dh.publicValue.len;
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
       case NSSLOWKEYECKey:
 	namekey.data = pubkey->u.ec.publicValue.data;
 	namekey.size = pubkey->u.ec.publicValue.len;
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
       default:
 	/* XXX We don't do Fortezza or DH yet. */
 	return PR_FALSE;
     }
 
     if (handle->version != 3) {
 	unsigned char buf[SHA1_LENGTH];
 	SHA1_HashBuf(buf,namekey.data,namekey.size);
@@ -1470,17 +1470,17 @@ seckey_encrypt_private_key( PLArenaPool 
 			    SDB *sdbpw, SECItem *result)
 {
     NSSLOWKEYPrivateKeyInfo *pki = NULL;
     SECStatus rv = SECFailure;
     PLArenaPool *temparena = NULL;
     SECItem *der_item = NULL;
     SECItem *cipherText = NULL;
     SECItem *dummy = NULL;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     SECItem *fordebug = NULL;
     int savelen;
 #endif
 
     temparena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
     if(temparena == NULL)
 	goto loser;
 
@@ -1550,17 +1550,17 @@ seckey_encrypt_private_key( PLArenaPool 
 	}
 
 	rv = SECOID_SetAlgorithmID(temparena, &(pki->algorithm),
 				   SEC_OID_X942_DIFFIE_HELMAN_KEY, dummy);
 	if (rv == SECFailure) {
 	    goto loser;
 	}
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
       case NSSLOWKEYECKey:
 	lg_prepare_low_ec_priv_key_for_asn1(pk);
 	/* Public value is encoded as a bit string so adjust length
 	 * to be in bits before ASN encoding and readjust 
 	 * immediately after.
 	 *
 	 * Since the SECG specification recommends not including the
 	 * parameters as part of ECPrivateKey, we zero out the curveOID
@@ -1589,17 +1589,17 @@ seckey_encrypt_private_key( PLArenaPool 
 	    goto loser;
 	}
 	
 	fordebug = &(pki->privateKey);
 	SEC_PRINT("seckey_encrypt_private_key()", "PrivateKey", 
 		  pk->keyType, fordebug);
 
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
       default:
 	/* We don't support DH or Fortezza private keys yet */
 	PORT_Assert(PR_FALSE);
 	break;
     }
 
     /* setup encrypted private key info */
     dummy = SEC_ASN1EncodeItem(temparena, der_item, pki, 
@@ -1699,17 +1699,17 @@ static NSSLOWKEYPrivateKey *
 seckey_decrypt_private_key(SECItem*epki,
 			   SDB *sdbpw)
 {
     NSSLOWKEYPrivateKey *pk = NULL;
     NSSLOWKEYPrivateKeyInfo *pki = NULL;
     SECStatus rv = SECFailure;
     PLArenaPool *temparena = NULL, *permarena = NULL;
     SECItem *dest = NULL;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     SECItem *fordebug = NULL;
 #endif
 
     if((epki == NULL) || (sdbpw == NULL))
 	goto loser;
 
     temparena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
     permarena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
@@ -1807,17 +1807,17 @@ seckey_decrypt_private_key(SECItem*epki,
 		pk->keyType = NSSLOWKEYDHKey;
 		lg_prepare_low_dh_priv_key_for_asn1(pk);
                 if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey,
                     &pki->privateKey) ) break;
 		rv = SEC_QuickDERDecodeItem(permarena, pk,
 					lg_nsslowkey_DHPrivateKeyTemplate,
 					&newPrivateKey);
 		break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	      case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
 		pk->keyType = NSSLOWKEYECKey;
 		lg_prepare_low_ec_priv_key_for_asn1(pk);
 
 		fordebug = &pki->privateKey;
 		SEC_PRINT("seckey_decrypt_private_key()", "PrivateKey", 
 			  pk->keyType, fordebug);
                 if (SECSuccess != SECITEM_CopyItem(permarena, &newPrivateKey,
@@ -1844,17 +1844,17 @@ seckey_decrypt_private_key(SECItem*epki,
 		if (rv != SECSuccess)
 		    goto loser;
 
 		if (pk->u.ec.publicValue.len != 0) {
 		    pk->u.ec.publicValue.len >>= 3;
 		}
 
 		break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	      default:
 		rv = SECFailure;
 		break;
 	    }
 	}
 	else if(PORT_GetError() == SEC_ERROR_BAD_DER)
 	{
 	    PORT_SetError(SEC_ERROR_BAD_PASSWORD);
--- a/security/nss/lib/softoken/legacydb/lgattr.c
+++ b/security/nss/lib/softoken/legacydb/lgattr.c
@@ -418,21 +418,21 @@ lg_GetPubItem(NSSLOWKEYPublicKey *pubKey
 	    pubItem = &pubKey->u.rsa.modulus;
 	    break;
     case NSSLOWKEYDSAKey:
 	    pubItem = &pubKey->u.dsa.publicValue;
 	    break;
     case NSSLOWKEYDHKey:
 	    pubItem = &pubKey->u.dh.publicValue;
 	    break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case NSSLOWKEYECKey:
 	    pubItem = &pubKey->u.ec.publicValue;
 	    break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     default:
 	    break;
     }
     return pubItem;
 }
 
 static const SEC_ASN1Template lg_SerialTemplate[] = {
     { SEC_ASN1_INTEGER, offsetof(NSSLOWCERTCertificate,serialNumber) },
@@ -546,17 +546,17 @@ lg_FindDHPublicKeyAttribute(NSSLOWKEYPub
 	return lg_CopyAttributeSigned(attribute,type,key->u.dh.base.data,
 					key->u.dh.base.len);
     default:
 	break;
     }
     return lg_invalidAttribute(attribute);
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 static CK_RV
 lg_FindECPublicKeyAttribute(NSSLOWKEYPublicKey *key, CK_ATTRIBUTE_TYPE type,
 				CK_ATTRIBUTE *attribute)
 {
     unsigned char hash[SHA1_LENGTH];
     CK_KEY_TYPE keyType = CKK_EC;
 
     switch (type) {
@@ -596,17 +596,17 @@ lg_FindECPublicKeyAttribute(NSSLOWKEYPub
 	    SECITEM_FreeItem(pubValue, PR_TRUE);
 	    return crv;
 	}
     default:
 	break;
     }
     return lg_invalidAttribute(attribute);
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 
 static CK_RV
 lg_FindPublicKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type,
 				CK_ATTRIBUTE *attribute)
 {
     NSSLOWKEYPublicKey   *key;
     CK_RV crv;
@@ -648,20 +648,20 @@ lg_FindPublicKeyAttribute(LGObjectCache 
 
     switch (key->keyType) {
     case NSSLOWKEYRSAKey:
 	return lg_FindRSAPublicKeyAttribute(key,type,attribute);
     case NSSLOWKEYDSAKey:
 	return lg_FindDSAPublicKeyAttribute(key,type,attribute);
     case NSSLOWKEYDHKey:
 	return lg_FindDHPublicKeyAttribute(key,type,attribute);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case NSSLOWKEYECKey:
 	return lg_FindECPublicKeyAttribute(key,type,attribute);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     default:
 	break;
     }
 
     return lg_invalidAttribute(attribute);
 }
 
 static CK_RV
@@ -940,17 +940,17 @@ lg_FindDHPrivateKeyAttribute(NSSLOWKEYPr
 					key->u.dh.publicValue.data,
 					key->u.dh.publicValue.len);
     default:
 	break;
     }
     return lg_invalidAttribute(attribute);
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 static CK_RV
 lg_FindECPrivateKeyAttribute(NSSLOWKEYPrivateKey *key, CK_ATTRIBUTE_TYPE type,
 				CK_ATTRIBUTE *attribute, SDB *sdbpw)
 {
     unsigned char hash[SHA1_LENGTH];
     CK_KEY_TYPE keyType = CKK_EC;
 
     switch (type) {
@@ -978,17 +978,17 @@ lg_FindECPrivateKeyAttribute(NSSLOWKEYPr
 	return lg_CopyAttributeSigned(attribute, type,
 					key->u.ec.publicValue.data,
 					key->u.ec.publicValue.len);
     default:
 	break;
     }
     return lg_invalidAttribute(attribute);
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 static CK_RV
 lg_FindPrivateKeyAttribute(LGObjectCache *obj, CK_ATTRIBUTE_TYPE type,
 				CK_ATTRIBUTE *attribute)
 {
     NSSLOWKEYPrivateKey  *key;
     char *label;
     CK_RV crv;
@@ -1025,20 +1025,20 @@ lg_FindPrivateKeyAttribute(LGObjectCache
     }
     switch (key->keyType) {
     case NSSLOWKEYRSAKey:
 	return lg_FindRSAPrivateKeyAttribute(key,type,attribute,obj->sdb);
     case NSSLOWKEYDSAKey:
 	return lg_FindDSAPrivateKeyAttribute(key,type,attribute,obj->sdb);
     case NSSLOWKEYDHKey:
 	return lg_FindDHPrivateKeyAttribute(key,type,attribute,obj->sdb);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case NSSLOWKEYECKey:
 	return lg_FindECPrivateKeyAttribute(key,type,attribute,obj->sdb);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     default:
 	break;
     }
 
     return lg_invalidAttribute(attribute);
 }
 
 static CK_RV
--- a/security/nss/lib/softoken/legacydb/lgcreate.c
+++ b/security/nss/lib/softoken/legacydb/lgcreate.c
@@ -394,45 +394,45 @@ static CK_RV
 lg_createPublicKeyObject(SDB *sdb, CK_KEY_TYPE key_type,
      CK_OBJECT_HANDLE *handle, const CK_ATTRIBUTE *templ, CK_ULONG count)
 {
     CK_ATTRIBUTE_TYPE pubKeyAttr = CKA_VALUE;
     CK_RV crv = CKR_OK;
     NSSLOWKEYPrivateKey *priv;
     SECItem pubKeySpace = {siBuffer, NULL, 0};
     SECItem *pubKey;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     SECItem pubKey2Space = {siBuffer, NULL, 0};
     PLArenaPool *arena = NULL;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     NSSLOWKEYDBHandle *keyHandle = NULL;
 	
 
     switch (key_type) {
     case CKK_RSA:
 	pubKeyAttr = CKA_MODULUS;
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKK_EC:
 	pubKeyAttr = CKA_EC_POINT;
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     case CKK_DSA:
     case CKK_DH:
 	break;
     default:
 	return CKR_ATTRIBUTE_VALUE_INVALID;
     }
 
 
     pubKey = &pubKeySpace;
     crv = lg_Attribute2SSecItem(NULL,pubKeyAttr,templ,count,pubKey);
     if (crv != CKR_OK) return crv;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     if (key_type == CKK_EC) {
 	SECStatus rv;
 	/*
 	 * for ECC, use the decoded key first.
 	 */
 	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
 	if (arena == NULL) {
 	    crv = CKR_HOST_MEMORY;
@@ -445,17 +445,17 @@ lg_createPublicKeyObject(SDB *sdb, CK_KE
 	    /* decode didn't work, just try the pubKey */
 	    PORT_FreeArena(arena, PR_FALSE);
 	    arena = NULL;
 	} else {
 	    /* try the decoded pub key first */
 	    pubKey = &pubKey2Space;
 	}
     }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     PORT_Assert(pubKey->data);
     if (pubKey->data == NULL) {
 	crv = CKR_ATTRIBUTE_VALUE_INVALID;
 	goto done;
     }
     keyHandle = lg_getKeyDB(sdb);
     if (keyHandle == NULL) {
@@ -466,17 +466,17 @@ lg_createPublicKeyObject(SDB *sdb, CK_KE
 	unsigned char buf[SHA1_LENGTH];
 	SHA1_HashBuf(buf,pubKey->data,pubKey->len);
 	PORT_Memcpy(pubKey->data,buf,sizeof(buf));
 	pubKey->len = sizeof(buf);
     }
     /* make sure the associated private key already exists */
     /* only works if we are logged in */
     priv = nsslowkey_FindKeyByPublicKey(keyHandle, pubKey, sdb /*password*/);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     if (priv == NULL && pubKey == &pubKey2Space) {
 	/* no match on the decoded key, match the original pubkey */
 	pubKey = &pubKeySpace;
     	priv = nsslowkey_FindKeyByPublicKey(keyHandle, pubKey, 
 					    sdb /*password*/);
     }
 #endif
     if (priv == NULL) {
@@ -487,17 +487,17 @@ lg_createPublicKeyObject(SDB *sdb, CK_KE
     }
     lg_nsslowkey_DestroyPrivateKey(priv);
     crv = CKR_OK;
 
     *handle = lg_mkHandle(sdb, pubKey, LG_TOKEN_TYPE_PUB);
 
 done:
     PORT_Free(pubKeySpace.data);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     if (arena) 
 	PORT_FreeArena(arena, PR_FALSE);
 #endif
 
     return crv;
 }
 
 /* make a private key from a verified object */
@@ -594,17 +594,17 @@ lg_mkPrivKey(SDB *sdb, const CK_ATTRIBUT
 	if (lg_hasAttribute(CKA_NETSCAPE_DB, templ, count)) {
 	    crv = lg_Attribute2SSecItem(arena, CKA_NETSCAPE_DB,templ,count,
 					&privKey->u.dh.publicValue);
 	    /* privKey was zero'd so public value is already set to NULL, 0
 	     * if we don't set it explicitly */
 	}
 	break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKK_EC:
 	privKey->keyType = NSSLOWKEYECKey;
 	crv = lg_Attribute2SSecItem(arena, CKA_EC_PARAMS,templ,count,
 	                              &privKey->u.ec.ecParams.DEREncoding);
     	if (crv != CKR_OK) break;
 
 	/* Fill out the rest of the ecParams structure
 	 * based on the encoded params
@@ -623,17 +623,17 @@ lg_mkPrivKey(SDB *sdb, const CK_ATTRIBUT
 	    if (crv != CKR_OK) break;
 	    /* privKey was zero'd so public value is already set to NULL, 0
 	     * if we don't set it explicitly */
 	}
         rv = DER_SetUInteger(privKey->arena, &privKey->u.ec.version,
                           NSSLOWKEY_EC_PRIVATE_KEY_VERSION);
 	if (rv != SECSuccess) crv = CKR_HOST_MEMORY;
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     default:
 	crv = CKR_KEY_TYPE_INCONSISTENT;
 	break;
     }
     *crvp = crv;
     if (crv != CKR_OK) {
 	PORT_FreeArena(arena,PR_FALSE);
--- a/security/nss/lib/softoken/legacydb/lowcert.c
+++ b/security/nss/lib/softoken/legacydb/lowcert.c
@@ -788,17 +788,17 @@ nsslowcert_ExtractPublicKey(NSSLOWCERTCe
         break;
       case SEC_OID_X942_DIFFIE_HELMAN_KEY:
         pubk->keyType = NSSLOWKEYDHKey;
         prepare_low_dh_pub_key_for_asn1(pubk);
         rv = SEC_QuickDERDecodeItem(arena, pubk,
 				 nsslowcert_DHPublicKeyTemplate, &os);
         if (rv == SECSuccess) return pubk;
         break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
       case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
         pubk->keyType = NSSLOWKEYECKey;
 	/* Since PKCS#11 directly takes the DER encoding of EC params
 	 * and public value, we don't need any decoding here.
 	 */
         rv = SECITEM_CopyItem(arena, &pubk->u.ec.ecParams.DEREncoding, 
 	    &spki.algorithm.parameters);
         if ( rv != SECSuccess )
@@ -809,17 +809,17 @@ nsslowcert_ExtractPublicKey(NSSLOWCERTCe
 	 */
 	if (LGEC_FillParams(arena, &pubk->u.ec.ecParams.DEREncoding,
 	    &pubk->u.ec.ecParams) != SECSuccess) 
 	    break;
 
         rv = SECITEM_CopyItem(arena, &pubk->u.ec.publicValue, &os);
 	if (rv == SECSuccess) return pubk;
         break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
       default:
         rv = SECFailure;
         break;
     }
 
     lg_nsslowkey_DestroyPublicKey (pubk);
     return NULL;
 }
--- a/security/nss/lib/softoken/legacydb/lowkey.c
+++ b/security/nss/lib/softoken/legacydb/lowkey.c
@@ -94,17 +94,17 @@ const SEC_ASN1Template lg_nsslowkey_DHPr
     { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.publicValue) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.privateValue) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.base) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.prime) },
     { 0, }
 };
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 
 /* XXX This is just a placeholder for later when we support
  * generic curves and need full-blown support for parsing EC
  * parameters. For now, we only support named curves in which
  * EC params are simply encoded as an object ID and we don't
  * use lg_nsslowkey_ECParamsTemplate.
  */
 const SEC_ASN1Template lg_nsslowkey_ECParamsTemplate[] = {
@@ -211,17 +211,17 @@ LGEC_CopyParams(PLArenaPool *arena, ECPa
 	goto loser;
     }
 
     return SECSuccess;
 
 loser:
     return SECFailure;
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 /*
  * See bugzilla bug 125359
  * Since NSS (via PKCS#11) wants to handle big integers as unsigned ints,
  * all of the templates above that en/decode into integers must be converted
  * from ASN.1's signed integer type.  This is done by marking either the
  * source or destination (encoding or decoding, respectively) type as
  * siUnsignedInteger.
  */
@@ -261,34 +261,34 @@ void
 lg_prepare_low_dh_priv_key_for_asn1(NSSLOWKEYPrivateKey *key)
 {
     key->u.dh.prime.type = siUnsignedInteger;
     key->u.dh.base.type = siUnsignedInteger;
     key->u.dh.publicValue.type = siUnsignedInteger;
     key->u.dh.privateValue.type = siUnsignedInteger;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 void
 lg_prepare_low_ecparams_for_asn1(ECParams *params)
 {
     params->DEREncoding.type = siUnsignedInteger;
     params->curveOID.type = siUnsignedInteger;
 }
 
 void
 lg_prepare_low_ec_priv_key_for_asn1(NSSLOWKEYPrivateKey *key)
 {
     key->u.ec.version.type = siUnsignedInteger;
     key->u.ec.ecParams.DEREncoding.type = siUnsignedInteger;
     key->u.ec.ecParams.curveOID.type = siUnsignedInteger;
     key->u.ec.privateValue.type = siUnsignedInteger;
     key->u.ec.publicValue.type = siUnsignedInteger;
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 void
 lg_nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *privk)
 {
     if (privk && privk->arena) {
 	PORT_FreeArena(privk->arena, PR_TRUE);
     }
 }
@@ -373,17 +373,17 @@ lg_nsslowkey_ConvertToPublicKey(NSSLOWKE
 	    rv = SECITEM_CopyItem(arena, &pubk->u.dh.prime,
 				  &privk->u.dh.prime);
 	    if (rv != SECSuccess) break;
 	    rv = SECITEM_CopyItem(arena, &pubk->u.dh.base,
 				  &privk->u.dh.base);
 	    if (rv == SECSuccess) return pubk;
 	}
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
       case NSSLOWKEYECKey:
 	pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena,
 						    sizeof(NSSLOWKEYPublicKey));
 	if (pubk != NULL) {
 	    SECStatus rv;
 
 	    pubk->arena = arena;
 	    pubk->keyType = privk->keyType;
@@ -392,17 +392,17 @@ lg_nsslowkey_ConvertToPublicKey(NSSLOWKE
 	    if (rv != SECSuccess) break;
 	    pubk->u.ec.ecParams.arena = arena;
 	    /* Copy the rest of the params */
 	    rv = LGEC_CopyParams(arena, &(pubk->u.ec.ecParams),
 			       &(privk->u.ec.ecParams));
 	    if (rv == SECSuccess) return pubk;
 	}
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	/* No Fortezza in Low Key implementations (Fortezza keys aren't
 	 * stored in our data base */
     default:
 	break;
     }
 
     PORT_FreeArena (arena, PR_FALSE);
     return NULL;
--- a/security/nss/lib/softoken/legacydb/lowkeyi.h
+++ b/security/nss/lib/softoken/legacydb/lowkeyi.h
@@ -21,20 +21,20 @@ SEC_BEGIN_PROTOS
  * from ASN.1's signed integer type.  This is done by marking either the
  * source or destination (encoding or decoding, respectively) type as
  * siUnsignedInteger.
  */
 extern void lg_prepare_low_rsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
 extern void lg_prepare_low_pqg_params_for_asn1(PQGParams *params);
 extern void lg_prepare_low_dsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
 extern void lg_prepare_low_dh_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 extern void lg_prepare_low_ec_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
 extern void lg_prepare_low_ecparams_for_asn1(ECParams *params);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 typedef char * (* NSSLOWKEYDBNameFunc)(void *arg, int dbVersion);
     
 /*
 ** Open a key database.
 */
 extern NSSLOWKEYDBHandle *nsslowkey_OpenKeyDB(PRBool readOnly,
 					   const char *domain,
@@ -130,17 +130,17 @@ nsslowkey_StoreKeyByPublicKeyAlg(NSSLOWK
 extern NSSLOWKEYPrivateKey *
 nsslowkey_FindKeyByPublicKey(NSSLOWKEYDBHandle *handle, SECItem *modulus, 
 			  SDB *sdb);
 
 extern char *
 nsslowkey_FindKeyNicknameByPublicKey(NSSLOWKEYDBHandle *handle,
                                         SECItem *modulus, SDB *sdb);
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 /*
  * smaller version of EC_FillParams. In this code, we only need
  * oid and DER data.
  */
 SECStatus LGEC_FillParams(PLArenaPool *arena, const SECItem *encodedParams,
     ECParams *params);
 
 /* Copy all of the fields from srcParams into dstParams */
--- a/security/nss/lib/softoken/legacydb/lowkeyti.h
+++ b/security/nss/lib/softoken/legacydb/lowkeyti.h
@@ -38,21 +38,21 @@ typedef struct NSSLOWKEYDBHandleStr NSSL
 ** Typedef for callback to get a password "key".
 */
 extern const SEC_ASN1Template lg_nsslowkey_PQGParamsTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_RSAPrivateKeyTemplate2[];
 extern const SEC_ASN1Template lg_nsslowkey_DSAPrivateKeyTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_DHPrivateKeyExportTemplate[];
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #define NSSLOWKEY_EC_PRIVATE_KEY_VERSION   1  /* as per SECG 1 C.4 */
 extern const SEC_ASN1Template lg_nsslowkey_ECParamsTemplate[];
 extern const SEC_ASN1Template lg_nsslowkey_ECPrivateKeyTemplate[];
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 extern const SEC_ASN1Template lg_nsslowkey_PrivateKeyInfoTemplate[];
 extern const SEC_ASN1Template nsslowkey_EncryptedPrivateKeyInfoTemplate[];
 
 /*
  * PKCS #8 attributes
  */
 struct NSSLOWKEYAttributeStr {
--- a/security/nss/lib/softoken/lowkey.c
+++ b/security/nss/lib/softoken/lowkey.c
@@ -4,17 +4,17 @@
 #include "lowkeyi.h"
 #include "secoid.h"
 #include "secitem.h"
 #include "secder.h"
 #include "base64.h"
 #include "secasn1.h"
 #include "secerr.h"
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #include "softoken.h"
 #endif
 
 SEC_ASN1_MKSUB(SEC_AnyTemplate)
 SEC_ASN1_MKSUB(SEC_BitStringTemplate)
 SEC_ASN1_MKSUB(SEC_ObjectIDTemplate)
 SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate)
 
@@ -86,17 +86,17 @@ const SEC_ASN1Template nsslowkey_DHPriva
     { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(NSSLOWKEYPrivateKey) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.publicValue) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.privateValue) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.base) },
     { SEC_ASN1_INTEGER, offsetof(NSSLOWKEYPrivateKey,u.dh.prime) },
     { 0, }
 };
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 
 /* XXX This is just a placeholder for later when we support
  * generic curves and need full-blown support for parsing EC
  * parameters. For now, we only support named curves in which
  * EC params are simply encoded as an object ID and we don't
  * use nsslowkey_ECParamsTemplate.
  */
 const SEC_ASN1Template nsslowkey_ECParamsTemplate[] = {
@@ -135,17 +135,17 @@ const SEC_ASN1Template nsslowkey_ECPriva
 #endif
     { SEC_ASN1_OPTIONAL | SEC_ASN1_CONSTRUCTED |
       SEC_ASN1_EXPLICIT | SEC_ASN1_CONTEXT_SPECIFIC |
       SEC_ASN1_XTRN | 1, 
       offsetof(NSSLOWKEYPrivateKey,u.ec.publicValue),
       SEC_ASN1_SUB(SEC_BitStringTemplate) }, 
     { 0, }
 };
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 /*
  * See bugzilla bug 125359
  * Since NSS (via PKCS#11) wants to handle big integers as unsigned ints,
  * all of the templates above that en/decode into integers must be converted
  * from ASN.1's signed integer type.  This is done by marking either the
  * source or destination (encoding or decoding, respectively) type as
  * siUnsignedInteger.
  */
@@ -191,34 +191,34 @@ void
 prepare_low_dh_priv_key_for_asn1(NSSLOWKEYPrivateKey *key)
 {
     key->u.dh.prime.type = siUnsignedInteger;
     key->u.dh.base.type = siUnsignedInteger;
     key->u.dh.publicValue.type = siUnsignedInteger;
     key->u.dh.privateValue.type = siUnsignedInteger;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 void
 prepare_low_ecparams_for_asn1(ECParams *params)
 {
     params->DEREncoding.type = siUnsignedInteger;
     params->curveOID.type = siUnsignedInteger;
 }
 
 void
 prepare_low_ec_priv_key_for_asn1(NSSLOWKEYPrivateKey *key)
 {
     key->u.ec.version.type = siUnsignedInteger;
     key->u.ec.ecParams.DEREncoding.type = siUnsignedInteger;
     key->u.ec.ecParams.curveOID.type = siUnsignedInteger;
     key->u.ec.privateValue.type = siUnsignedInteger;
     key->u.ec.publicValue.type = siUnsignedInteger;
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 void
 nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *privk)
 {
     if (privk && privk->arena) {
 	PORT_FreeArena(privk->arena, PR_TRUE);
     }
 }
@@ -336,17 +336,17 @@ nsslowkey_ConvertToPublicKey(NSSLOWKEYPr
 	    rv = SECITEM_CopyItem(arena, &pubk->u.dh.prime,
 				  &privk->u.dh.prime);
 	    if (rv != SECSuccess) break;
 	    rv = SECITEM_CopyItem(arena, &pubk->u.dh.base,
 				  &privk->u.dh.base);
 	    if (rv == SECSuccess) return pubk;
 	}
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
       case NSSLOWKEYECKey:
 	pubk = (NSSLOWKEYPublicKey *)PORT_ArenaZAlloc(arena,
 						    sizeof(NSSLOWKEYPublicKey));
 	if (pubk != NULL) {
 	    SECStatus rv;
 
 	    pubk->arena = arena;
 	    pubk->keyType = privk->keyType;
@@ -355,17 +355,17 @@ nsslowkey_ConvertToPublicKey(NSSLOWKEYPr
 	    if (rv != SECSuccess) break;
 	    pubk->u.ec.ecParams.arena = arena;
 	    /* Copy the rest of the params */
 	    rv = EC_CopyParams(arena, &(pubk->u.ec.ecParams),
 			       &(privk->u.ec.ecParams));
 	    if (rv == SECSuccess) return pubk;
 	}
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	/* No Fortezza in Low Key implementations (Fortezza keys aren't
 	 * stored in our data base */
     default:
 	break;
     }
 
     PORT_FreeArena (arena, PR_FALSE);
     return NULL;
@@ -454,34 +454,34 @@ nsslowkey_CopyPrivateKey(NSSLOWKEYPrivat
 	    returnKey->u.dsa.params.arena = poolp;
 	    rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.prime),
 					&(privKey->u.dh.prime));
 	    if(rv != SECSuccess) break;
 	    rv = SECITEM_CopyItem(poolp, &(returnKey->u.dh.base),
 					&(privKey->u.dh.base));
 	    if(rv != SECSuccess) break;
 	    break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	case NSSLOWKEYECKey:
 	    rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.version),
 	    				&(privKey->u.ec.version));
 	    if(rv != SECSuccess) break;
 	    rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.publicValue),
 	    				&(privKey->u.ec.publicValue));
 	    if(rv != SECSuccess) break;
 	    rv = SECITEM_CopyItem(poolp, &(returnKey->u.ec.privateValue),
 	    				&(privKey->u.ec.privateValue));
 	    if(rv != SECSuccess) break;
 	    returnKey->u.ec.ecParams.arena = poolp;
 	    /* Copy the rest of the params */
 	    rv = EC_CopyParams(poolp, &(returnKey->u.ec.ecParams),
 			       &(privKey->u.ec.ecParams));
 	    if (rv != SECSuccess) break;
 	    break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	default:
 	    rv = SECFailure;
     }
 
 loser:
 
     if(rv != SECSuccess) {
 	PORT_FreeArena(poolp, PR_TRUE);
--- a/security/nss/lib/softoken/lowkeyi.h
+++ b/security/nss/lib/softoken/lowkeyi.h
@@ -20,20 +20,20 @@ SEC_BEGIN_PROTOS
  * source or destination (encoding or decoding, respectively) type as
  * siUnsignedInteger.
  */
 extern void prepare_low_rsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
 extern void prepare_low_pqg_params_for_asn1(PQGParams *params);
 extern void prepare_low_dsa_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
 extern void prepare_low_dsa_priv_key_export_for_asn1(NSSLOWKEYPrivateKey *key);
 extern void prepare_low_dh_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 extern void prepare_low_ec_priv_key_for_asn1(NSSLOWKEYPrivateKey *key);
 extern void prepare_low_ecparams_for_asn1(ECParams *params);
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 /*
 ** Destroy a private key object.
 **	"key" the object
 **	"freeit" if PR_TRUE then free the object as well as its sub-objects
 */
 extern void nsslowkey_DestroyPrivateKey(NSSLOWKEYPrivateKey *key);
 
--- a/security/nss/lib/softoken/lowkeyti.h
+++ b/security/nss/lib/softoken/lowkeyti.h
@@ -15,21 +15,21 @@
 ** Typedef for callback to get a password "key".
 */
 extern const SEC_ASN1Template nsslowkey_PQGParamsTemplate[];
 extern const SEC_ASN1Template nsslowkey_RSAPrivateKeyTemplate[];
 extern const SEC_ASN1Template nsslowkey_DSAPrivateKeyTemplate[];
 extern const SEC_ASN1Template nsslowkey_DSAPrivateKeyExportTemplate[];
 extern const SEC_ASN1Template nsslowkey_DHPrivateKeyTemplate[];
 extern const SEC_ASN1Template nsslowkey_DHPrivateKeyExportTemplate[];
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #define NSSLOWKEY_EC_PRIVATE_KEY_VERSION   1  /* as per SECG 1 C.4 */
 extern const SEC_ASN1Template nsslowkey_ECParamsTemplate[];
 extern const SEC_ASN1Template nsslowkey_ECPrivateKeyTemplate[];
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 extern const SEC_ASN1Template nsslowkey_PrivateKeyInfoTemplate[];
 extern const SEC_ASN1Template nsslowkey_EncryptedPrivateKeyInfoTemplate[];
 
 /*
  * PKCS #8 attributes
  */
 struct NSSLOWKEYAttributeStr {
--- a/security/nss/lib/softoken/pkcs11.c
+++ b/security/nss/lib/softoken/pkcs11.c
@@ -297,27 +297,27 @@ static const struct mechanismList mechan
      {CKM_DSA_SHA1,		{DSA_MIN_P_BITS, DSA_MAX_P_BITS,
 				 CKF_SN_VR},              PR_TRUE},
      /* -------------------- Diffie Hellman Operations --------------------- */
      /* no diffie hellman yet */
      {CKM_DH_PKCS_KEY_PAIR_GEN,	{DH_MIN_P_BITS, DH_MAX_P_BITS, 
 				 CKF_GENERATE_KEY_PAIR}, PR_TRUE}, 
      {CKM_DH_PKCS_DERIVE,	{DH_MIN_P_BITS, DH_MAX_P_BITS,
 				 CKF_DERIVE}, 	PR_TRUE}, 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
      /* -------------------- Elliptic Curve Operations --------------------- */
      {CKM_EC_KEY_PAIR_GEN,      {EC_MIN_KEY_BITS, EC_MAX_KEY_BITS,
 				 CKF_GENERATE_KEY_PAIR|CKF_EC_BPNU}, PR_TRUE}, 
      {CKM_ECDH1_DERIVE,         {EC_MIN_KEY_BITS, EC_MAX_KEY_BITS,
 				 CKF_DERIVE|CKF_EC_BPNU}, PR_TRUE}, 
      {CKM_ECDSA,                {EC_MIN_KEY_BITS, EC_MAX_KEY_BITS,
 				 CKF_SN_VR|CKF_EC_BPNU}, PR_TRUE}, 
      {CKM_ECDSA_SHA1,           {EC_MIN_KEY_BITS, EC_MAX_KEY_BITS,
 				 CKF_SN_VR|CKF_EC_BPNU}, PR_TRUE}, 
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
      /* ------------------------- RC2 Operations --------------------------- */
      {CKM_RC2_KEY_GEN,		{1, 128, CKF_GENERATE},		PR_TRUE},
      {CKM_RC2_ECB,		{1, 128, CKF_EN_DE_WR_UN},	PR_TRUE},
      {CKM_RC2_CBC,		{1, 128, CKF_EN_DE_WR_UN},	PR_TRUE},
      {CKM_RC2_MAC,		{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_RC2_MAC_GENERAL,	{1, 128, CKF_SN_VR},		PR_TRUE},
      {CKM_RC2_CBC_PAD,		{1, 128, CKF_EN_DE_WR_UN},	PR_TRUE},
      /* ------------------------- RC4 Operations --------------------------- */
@@ -922,31 +922,31 @@ sftk_handlePublicKeyObject(SFTKSession *
 	    return crv;
 	}
 	verify = CK_FALSE;
 	derive = CK_TRUE;
 	encrypt = CK_FALSE;
 	recover = CK_FALSE;
 	wrap = CK_FALSE;
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKK_EC:
 	if ( !sftk_hasAttribute(object, CKA_EC_PARAMS)) {
 	    return CKR_TEMPLATE_INCOMPLETE;
 	}
 	if ( !sftk_hasAttribute(object, CKA_EC_POINT)) {
 	    return CKR_TEMPLATE_INCOMPLETE;
 	}
 	derive = CK_TRUE;    /* for ECDH */
 	verify = CK_TRUE;    /* for ECDSA */
 	encrypt = CK_FALSE;
 	recover = CK_FALSE;
 	wrap = CK_FALSE;
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     default:
 	return CKR_ATTRIBUTE_VALUE_INVALID;
     }
 
     /* make sure the required fields exist */
     crv = sftk_defaultAttribute(object,CKA_SUBJECT,NULL,0);
     if (crv != CKR_OK)  return crv; 
     crv = sftk_defaultAttribute(object,CKA_ENCRYPT,&encrypt,sizeof(CK_BBOOL));
@@ -1083,30 +1083,30 @@ sftk_handlePrivateKeyObject(SFTKSession 
 	}
 	if ( !sftk_hasAttribute(object, CKA_VALUE)) {
 	    return CKR_TEMPLATE_INCOMPLETE;
 	}
 	encrypt = CK_FALSE;
 	recover = CK_FALSE;
 	wrap = CK_FALSE;
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKK_EC:
 	if ( !sftk_hasAttribute(object, CKA_EC_PARAMS)) {
 	    return CKR_TEMPLATE_INCOMPLETE;
 	}
 	if ( !sftk_hasAttribute(object, CKA_VALUE)) {
 	    return CKR_TEMPLATE_INCOMPLETE;
 	}
 	encrypt = CK_FALSE;
 	sign = CK_TRUE;
 	recover = CK_FALSE;
 	wrap = CK_FALSE;
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     case CKK_NSS_JPAKE_ROUND1:
         if (!sftk_hasAttribute(object, CKA_PRIME) ||
             !sftk_hasAttribute(object, CKA_SUBPRIME) ||
             !sftk_hasAttribute(object, CKA_BASE)) {
             return CKR_TEMPLATE_INCOMPLETE;
         }
         /* fall through */
     case CKK_NSS_JPAKE_ROUND2:
@@ -1703,17 +1703,17 @@ NSSLOWKEYPublicKey *sftk_GetPubKey(SFTKO
 							object,CKA_PRIME);
     	if (crv != CKR_OK) break;
 	crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dh.base,
 							object,CKA_BASE);
     	if (crv != CKR_OK) break;
     	crv = sftk_Attribute2SSecItem(arena,&pubKey->u.dh.publicValue,
 							object,CKA_VALUE);
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKK_EC:
 	pubKey->keyType = NSSLOWKEYECKey;
 	crv = sftk_Attribute2SSecItem(arena,
 	                              &pubKey->u.ec.ecParams.DEREncoding,
 	                              object,CKA_EC_PARAMS);
 	if (crv != CKR_OK) break;
 
 	/* Fill out the rest of the ecParams structure 
@@ -1763,17 +1763,17 @@ NSSLOWKEYPublicKey *sftk_GetPubKey(SFTKO
 		}
 		/* replace our previous with the decoded key */
 		pubKey->u.ec.publicValue = publicValue;
 		break;
 	    }
 	   crv = CKR_ATTRIBUTE_VALUE_INVALID;
 	}
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     default:
 	crv = CKR_KEY_TYPE_INCONSISTENT;
 	break;
     }
     *crvp = crv;
     if (crv != CKR_OK) {
     	PORT_FreeArena(arena,PR_FALSE);
 	return NULL;
@@ -1872,17 +1872,17 @@ sftk_mkPrivKey(SFTKObject *object, CK_KE
 	itemTemplateCount++;
 	SFTK_SET_ITEM_TEMPLATE(itemTemplate, itemTemplateCount,
 		&privKey->u.dh.privateValue, CKA_VALUE);
 	itemTemplateCount++;
 	/* privKey was zero'd so public value is already set to NULL, 0
 	 * if we don't set it explicitly */
 	break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKK_EC:
 	privKey->keyType = NSSLOWKEYECKey;
 	crv = sftk_Attribute2SSecItem(arena, 
 				      &privKey->u.ec.ecParams.DEREncoding,
 				      object,CKA_EC_PARAMS);
     	if (crv != CKR_OK) break;
 
 	/* Fill out the rest of the ecParams structure
@@ -1914,17 +1914,17 @@ sftk_mkPrivKey(SFTKObject *object, CK_KE
 	     * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=56561
 	     */
 #if defined (__arm__) && !defined(__thumb__) && defined (__GNUC__)
 	    *crvp = CKR_HOST_MEMORY;
 	    break;
 #endif
 	}
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     default:
 	crv = CKR_KEY_TYPE_INCONSISTENT;
 	break;
     }
     if (crv == CKR_OK && itemTemplateCount != 0) {
 	PORT_Assert(itemTemplateCount > 0);
 	PORT_Assert(itemTemplateCount <= SFTK_MAX_ITEM_TEMPLATE);
--- a/security/nss/lib/softoken/pkcs11c.c
+++ b/security/nss/lib/softoken/pkcs11c.c
@@ -57,29 +57,29 @@ typedef struct {
     PRUint8 random[46];
 } SSL3RSAPreMasterSecret;
 
 static void sftk_Null(void *data, PRBool freeit)
 {
     return;
 } 
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #ifdef EC_DEBUG
 #define SEC_PRINT(str1, str2, num, sitem) \
     printf("pkcs11c.c:%s:%s (keytype=%d) [len=%d]\n", \
             str1, str2, num, sitem->len); \
     for (i = 0; i < sitem->len; i++) { \
 	    printf("%02x:", sitem->data[i]); \
     } \
     printf("\n") 
 #else
 #define SEC_PRINT(a, b, c, d) 
 #endif
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 /*
  * free routines.... Free local type  allocated data, and convert
  * other free routines to the destroy signature.
  */
 static void
 sftk_FreePrivKey(NSSLOWKEYPrivateKey *key, PRBool freeit)
 {
@@ -115,17 +115,17 @@ sftk_MapCryptError(int error)
 	case SEC_ERROR_BAD_SIGNATURE:
 	    return CKR_SIGNATURE_INVALID;
 	case SEC_ERROR_INVALID_KEY:
 	    return CKR_KEY_SIZE_RANGE;
 	case SEC_ERROR_BAD_KEY:  /* an EC public key that fails validation */
 	    return CKR_KEY_SIZE_RANGE;  /* the closest error code */
 	case SEC_ERROR_UNSUPPORTED_EC_POINT_FORM:
 	    return CKR_TEMPLATE_INCONSISTENT;
-	/* EC functions set this error if NSS_ENABLE_ECC is not defined */
+	/* EC functions set this error if NSS_DISABLE_ECC is defined */
 	case SEC_ERROR_UNSUPPORTED_KEYALG:
 	    return CKR_MECHANISM_INVALID;
 	case SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE:
 	    return CKR_DOMAIN_PARAMS_INVALID;
 	/* key pair generation failed after max number of attempts */
 	case SEC_ERROR_NEED_RANDOM:
 	    return CKR_FUNCTION_FAILED;
     }
@@ -2237,17 +2237,17 @@ nsc_DSA_Sign_Stub(void *ctx, void *sigBu
     rv = DSA_SignDigest(&(key->u.dsa), &signature, &digest);
     if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
 	sftk_fatalError = PR_TRUE;
     }
     *sigLen = signature.len;
     return rv;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 static SECStatus
 nsc_ECDSAVerifyStub(void *ctx, void *sigBuf, unsigned int sigLen,
                     void *dataBuf, unsigned int dataLen)
 {
     SECItem signature, digest;
     NSSLOWKEYPublicKey *key = (NSSLOWKEYPublicKey *)ctx;
 
     signature.data = (unsigned char *)sigBuf;
@@ -2272,17 +2272,17 @@ nsc_ECDSASignStub(void *ctx, void *sigBu
     digest.len = dataLen;
     rv = ECDSA_SignDigest(&(key->u.ec), &signature, &digest);
     if (rv != SECSuccess && PORT_GetError() == SEC_ERROR_LIBRARY_FAILURE) {
 	sftk_fatalError = PR_TRUE;
     }
     *sigLen = signature.len;
     return rv;
 }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 /* NSC_SignInit setups up the signing operations. There are three basic
  * types of signing:
  *	(1) the tradition single part, where "Raw RSA" or "Raw DSA" is applied
  *  to data in a single Sign operation (which often looks a lot like an
  *  encrypt, with data coming in and data going out).
  *	(2) Hash based signing, where we continually hash the data, then apply
  *  some sort of signature to the end.
@@ -2424,17 +2424,17 @@ finish_rsa:
 	context->cipherInfo = privKey;
 	context->update     = (SFTKCipher) nsc_DSA_Sign_Stub;
 	context->destroy    = (privKey == key->objectInfo) ?
 		(SFTKDestroy) sftk_Null:(SFTKDestroy)sftk_FreePrivKey;
 	context->maxLen     = DSA_MAX_SIGNATURE_LEN;
 
 	break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKM_ECDSA_SHA1:
 	context->multi = PR_TRUE;
 	crv = sftk_doSubSHA1(context);
 	if (crv != CKR_OK) break;
 	/* fall through */
     case CKM_ECDSA:
 	if (key_type != CKK_EC) {
 	    crv = CKR_KEY_TYPE_INCONSISTENT;
@@ -2447,17 +2447,17 @@ finish_rsa:
 	}
 	context->cipherInfo = privKey;
 	context->update     = (SFTKCipher) nsc_ECDSASignStub;
 	context->destroy    = (privKey == key->objectInfo) ?
 		(SFTKDestroy) sftk_Null:(SFTKDestroy)sftk_FreePrivKey;
 	context->maxLen     = MAX_ECKEY_LEN * 2;
 
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 #define INIT_HMAC_MECH(mmm) \
     case CKM_ ## mmm ## _HMAC_GENERAL: \
 	crv = sftk_doHMACInit(context, HASH_Alg ## mmm ,key, \
 				*(CK_ULONG *)pMechanism->pParameter); \
 	break; \
     case CKM_ ## mmm ## _HMAC: \
 	crv = sftk_doHMACInit(context, HASH_Alg ## mmm ,key, mmm ## _LENGTH); \
@@ -3055,17 +3055,17 @@ finish_rsa:
 	pubKey = sftk_GetPubKey(key,CKK_DSA,&crv);
 	if (pubKey == NULL) {
 	    break;
 	}
 	context->cipherInfo = pubKey;
 	context->verify     = (SFTKVerify) nsc_DSA_Verify_Stub;
 	context->destroy    = sftk_Null;
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKM_ECDSA_SHA1:
 	context->multi = PR_TRUE;
 	crv = sftk_doSubSHA1(context);
 	if (crv != CKR_OK) break;
 	/* fall through */
     case CKM_ECDSA:
 	if (key_type != CKK_EC) {
 	    crv = CKR_KEY_TYPE_INCONSISTENT;
@@ -3075,17 +3075,17 @@ finish_rsa:
 	if (pubKey == NULL) {
 	    crv = CKR_HOST_MEMORY;
 	    break;
 	}
 	context->cipherInfo = pubKey;
 	context->verify     = (SFTKVerify) nsc_ECDSAVerifyStub;
 	context->destroy    = sftk_Null;
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     INIT_HMAC_MECH(MD2)
     INIT_HMAC_MECH(MD5)
     INIT_HMAC_MECH(SHA224)
     INIT_HMAC_MECH(SHA256)
     INIT_HMAC_MECH(SHA384)
     INIT_HMAC_MECH(SHA512)
 
@@ -4204,17 +4204,17 @@ sftk_PairwiseConsistencyCheck(CK_SESSION
 	    signature_length = modulusLen;
 	    mech.mechanism = CKM_RSA_PKCS;
 	    break;
 	case CKK_DSA:
 	    signature_length = DSA_MAX_SIGNATURE_LEN;
 	    pairwise_digest_length = subPrimeLen;
 	    mech.mechanism = CKM_DSA;
 	    break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	case CKK_EC:
 	    signature_length = MAX_ECKEY_LEN * 2;
 	    mech.mechanism = CKM_ECDSA;
 	    break;
 #endif
 	default:
 	    return CKR_DEVICE_ERROR;
 	}
@@ -4327,22 +4327,22 @@ CK_RV NSC_GenerateKeyPair (CK_SESSION_HA
     PQGParams 		pqgParam;
     DHParams  		dhParam;
     DSAPrivateKey *	dsaPriv;
 
     /* Diffie Hellman */
     int 		private_value_bits = 0;
     DHPrivateKey *	dhPriv;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     /* Elliptic Curve Cryptography */
     SECItem  		ecEncodedParams;  /* DER Encoded parameters */
     ECPrivateKey *	ecPriv;
     ECParams *          ecParams;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     CHECK_FORK();
 
     if (!slot) {
         return CKR_SESSION_HANDLE_INVALID;
     }
     /*
      * now lets create an object to hang the attributes off of
@@ -4662,17 +4662,17 @@ dsagn_done:
 	crv=sftk_AddAttributeType(privateKey, CKA_VALUE, 
 			      sftk_item_expand(&dhPriv->privateValue));
 
 dhgn_done:
 	/* should zeroize, since this function doesn't. */
 	PORT_FreeArena(dhPriv->arena, PR_TRUE);
 	break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKM_EC_KEY_PAIR_GEN:
 	sftk_DeleteAttributeType(privateKey,CKA_EC_PARAMS);
 	sftk_DeleteAttributeType(privateKey,CKA_VALUE);
     	sftk_DeleteAttributeType(privateKey,CKA_NETSCAPE_DB);
 	key_type = CKK_EC;
 
 	/* extract the necessary parameters and copy them to private keys */
 	crv = sftk_Attribute2SSecItem(NULL, &ecEncodedParams, publicKey, 
@@ -4725,17 +4725,17 @@ dhgn_done:
 	if (crv != CKR_OK) goto ecgn_done;
 
         crv = sftk_AddAttributeType(privateKey,CKA_NETSCAPE_DB,
 			   sftk_item_expand(&ecPriv->publicValue));
 ecgn_done:
 	/* should zeroize, since this function doesn't. */
 	PORT_FreeArena(ecPriv->ecParams.arena, PR_TRUE);
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     default:
 	crv = CKR_MECHANISM_INVALID;
     }
 
     if (crv != CKR_OK) {
 	sftk_FreeObject(privateKey);
 	sftk_FreeObject(publicKey);
@@ -4845,17 +4845,17 @@ static SECItem *sftk_PackagePrivateKey(S
     NSSLOWKEYPrivateKey *lk = NULL;
     NSSLOWKEYPrivateKeyInfo *pki = NULL;
     SFTKAttribute *attribute = NULL;
     PLArenaPool *arena = NULL;
     SECOidTag algorithm = SEC_OID_UNKNOWN;
     void *dummy, *param = NULL;
     SECStatus rv = SECSuccess;
     SECItem *encodedKey = NULL;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     SECItem *fordebug;
     int savelen;
 #endif
 
     if(!key) {
 	*crvp = CKR_KEY_HANDLE_INVALID; /* really can't happen */
 	return NULL;
     }
@@ -4900,17 +4900,17 @@ static SECItem *sftk_PackagePrivateKey(S
             prepare_low_dsa_priv_key_export_for_asn1(lk);
 	    dummy = SEC_ASN1EncodeItem(arena, &pki->privateKey, lk,
 				       nsslowkey_DSAPrivateKeyExportTemplate);
 	    prepare_low_pqg_params_for_asn1(&lk->u.dsa.params);
 	    param = SEC_ASN1EncodeItem(NULL, NULL, &(lk->u.dsa.params),
 				       nsslowkey_PQGParamsTemplate);
 	    algorithm = SEC_OID_ANSIX9_DSA_SIGNATURE;
 	    break;
-#ifdef NSS_ENABLE_ECC	    
+#ifndef NSS_DISABLE_ECC
         case NSSLOWKEYECKey:
             prepare_low_ec_priv_key_for_asn1(lk);
 	    /* Public value is encoded as a bit string so adjust length
 	     * to be in bits before ASN encoding and readjust 
 	     * immediately after.
 	     *
 	     * Since the SECG specification recommends not including the
 	     * parameters as part of ECPrivateKey, we zero out the curveOID
@@ -4927,17 +4927,17 @@ static SECItem *sftk_PackagePrivateKey(S
 	    fordebug = &pki->privateKey;
 	    SEC_PRINT("sftk_PackagePrivateKey()", "PrivateKey", lk->keyType,
 		      fordebug);
 
 	    param = SECITEM_DupItem(&lk->u.ec.ecParams.DEREncoding);
 
 	    algorithm = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
 	    break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	case NSSLOWKEYDHKey:
 	default:
 	    dummy = NULL;
 	    break;
     }
  
     if(!dummy || ((lk->keyType == NSSLOWKEYDSAKey) && !param)) {
 	*crvp = CKR_DEVICE_ERROR; /* should map NSS SECError */
@@ -4960,17 +4960,17 @@ static SECItem *sftk_PackagePrivateKey(S
 	rv = SECFailure;
 	goto loser;
     }
 
     encodedKey = SEC_ASN1EncodeItem(NULL, NULL, pki, 
 				    nsslowkey_PrivateKeyInfoTemplate);
     *crvp = encodedKey ? CKR_OK : CKR_DEVICE_ERROR;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     fordebug = encodedKey;
     SEC_PRINT("sftk_PackagePrivateKey()", "PrivateKeyInfo", lk->keyType,
 	      fordebug);
 #endif
 loser:
     if(arena) {
 	PORT_FreeArena(arena, PR_TRUE);
     }
@@ -5186,52 +5186,52 @@ sftk_unwrapPrivateKey(SFTKObject *key, S
 	    keyTemplate = nsslowkey_DSAPrivateKeyExportTemplate;
 	    paramTemplate = nsslowkey_PQGParamsTemplate;
 	    paramDest = &(lpk->u.dsa.params);
 	    lpk->keyType = NSSLOWKEYDSAKey;
 	    prepare_low_dsa_priv_key_export_for_asn1(lpk);
 	    prepare_low_pqg_params_for_asn1(&lpk->u.dsa.params);
 	    break;
 	/* case NSSLOWKEYDHKey: */
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
         case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
 	    keyTemplate = nsslowkey_ECPrivateKeyTemplate;
 	    paramTemplate = NULL;
 	    paramDest = &(lpk->u.ec.ecParams.DEREncoding);
 	    lpk->keyType = NSSLOWKEYECKey;
 	    prepare_low_ec_priv_key_for_asn1(lpk);
 	    prepare_low_ecparams_for_asn1(&lpk->u.ec.ecParams);
 	    break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	default:
 	    keyTemplate = NULL;
 	    paramTemplate = NULL;
 	    paramDest = NULL;
 	    break;
     }
 
     if(!keyTemplate) {
 	goto loser;
     }
 
     /* decode the private key and any algorithm parameters */
     rv = SEC_QuickDERDecodeItem(arena, lpk, keyTemplate, &pki->privateKey);
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     if (lpk->keyType == NSSLOWKEYECKey) {
         /* convert length in bits to length in bytes */
 	lpk->u.ec.publicValue.len >>= 3;
         rv = SECITEM_CopyItem(arena, 
 			      &(lpk->u.ec.ecParams.DEREncoding),
 	                      &(pki->algorithm.parameters));
 	if(rv != SECSuccess) {
 	    goto loser;
 	}
     }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     if(rv != SECSuccess) {
 	goto loser;
     }
     if(paramDest && paramTemplate) {
 	rv = SEC_QuickDERDecodeItem(arena, paramDest, paramTemplate, 
 				 &(pki->algorithm.parameters));
 	if(rv != SECSuccess) {
@@ -5316,17 +5316,17 @@ sftk_unwrapPrivateKey(SFTKObject *key, S
 #ifdef notdef
         case NSSLOWKEYDHKey:
 	    template = dhTemplate;
 	    templateCount = sizeof(dhTemplate)/sizeof(CK_ATTRIBUTE);
 	    keyType = CKK_DH;
 	    break;
 #endif
 	/* what about fortezza??? */
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
         case NSSLOWKEYECKey:
 	    keyType = CKK_EC;
 	    crv = (sftk_hasAttribute(key, CKA_NETSCAPE_DB)) ? CKR_OK :
 						CKR_KEY_TYPE_INCONSISTENT;
 	    if(crv != CKR_OK) break;
 	    crv = sftk_AddAttributeType(key, CKA_KEY_TYPE, &keyType, 
 						sizeof(keyType));
 	    if(crv != CKR_OK) break;
@@ -5342,17 +5342,17 @@ sftk_unwrapPrivateKey(SFTKObject *key, S
 	    crv = sftk_AddAttributeType(key, CKA_EC_PARAMS,
 				 sftk_item_expand(&lpk->u.ec.ecParams.DEREncoding));
 	    if(crv != CKR_OK) break;
 	    crv = sftk_AddAttributeType(key, CKA_VALUE, 
 			sftk_item_expand(&lpk->u.ec.privateValue));
 	    if(crv != CKR_OK) break;
 	    /* XXX Do we need to decode the EC Params here ?? */
 	    break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	default:
 	    crv = CKR_KEY_TYPE_INCONSISTENT;
 	    break;
     }
 
 loser:
     if(lpk) {
 	nsslowkey_DestroyPrivateKey(lpk);
@@ -5652,17 +5652,17 @@ sftk_MapKeySize(CK_KEY_TYPE keyType)
 	return 24;
     /* IDEA and CAST need to be added */
     default:
 	break;
     }
     return 0;
 }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 /* Inputs:
  *  key_len: Length of derived key to be generated.
  *  SharedSecret: a shared secret that is the output of a key agreement primitive.
  *  SharedInfo: (Optional) some data shared by the entities computing the secret key.
  *  SharedInfoLen: the length in octets of SharedInfo
  *  Hash: The hash function to be used in the KDF
  *  HashLen: the length in octets of the output of Hash
  * Output:
@@ -5763,17 +5763,17 @@ static CK_RV sftk_ANSI_X9_63_kdf(CK_BYTE
 	return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo,
 		   		 SharedInfoLen, SHA384_HashBuf, SHA384_LENGTH);
     else if (kdf == CKD_SHA512_KDF)
 	return sftk_compute_ANSI_X9_63_kdf(key, key_len, SharedSecret, SharedInfo,
 		   		 SharedInfoLen, SHA512_HashBuf, SHA512_LENGTH);
     else
 	return CKR_MECHANISM_INVALID;
 }
-#endif
+#endif /* NSS_DISABLE_ECC */
 
 /*
  * SSL Key generation given pre master secret
  */
 #define NUM_MIXERS 9
 static const char * const mixers[NUM_MIXERS] = { 
     "A", 
     "BB", 
@@ -6709,17 +6709,17 @@ key_and_mac_derive_fail:
 	    sftk_forceAttribute(key, CKA_VALUE, derived.data, derived.len);
 	    PORT_ZFree(derived.data, derived.len);
 	} else
 	    crv = CKR_HOST_MEMORY;
 	    
 	break;
       }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKM_ECDH1_DERIVE:
     case CKM_ECDH1_COFACTOR_DERIVE:
       {
 	SECItem  ecScalar, ecPoint;
 	SECItem  tmp;
 	PRBool   withCofactor = PR_FALSE;
 	unsigned char *secret;
 	unsigned char *keyData = NULL;
@@ -6867,17 +6867,17 @@ ec_loser:
 	if (privKey != sourceKey->objectInfo)
 	    nsslowkey_DestroyPrivateKey(privKey);
 	if (arena) {
 	    PORT_FreeArena(arena, PR_FALSE);
 	}
 	break;
 
       }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     /* See RFC 5869 and CK_NSS_HKDFParams for documentation. */
     case CKM_NSS_HKDF_SHA1:   hashType = HASH_AlgSHA1;   goto hkdf;
     case CKM_NSS_HKDF_SHA256: hashType = HASH_AlgSHA256; goto hkdf;
     case CKM_NSS_HKDF_SHA384: hashType = HASH_AlgSHA384; goto hkdf;
     case CKM_NSS_HKDF_SHA512: hashType = HASH_AlgSHA512; goto hkdf;
 hkdf: {
         const CK_NSS_HKDFParams * params =
--- a/security/nss/lib/softoken/pkcs11u.c
+++ b/security/nss/lib/softoken/pkcs11u.c
@@ -1241,17 +1241,17 @@ static const CK_ATTRIBUTE_TYPE dsaPubKey
 static const CK_ULONG dsaPubKeyAttrsCount = 
 			sizeof(dsaPubKeyAttrs)/sizeof(dsaPubKeyAttrs[0]);
 
 static const CK_ATTRIBUTE_TYPE dhPubKeyAttrs[] = {
     CKA_PRIME, CKA_BASE, CKA_VALUE
 };
 static const CK_ULONG dhPubKeyAttrsCount = 
 			sizeof(dhPubKeyAttrs)/sizeof(dhPubKeyAttrs[0]);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 static const CK_ATTRIBUTE_TYPE ecPubKeyAttrs[] = {
     CKA_EC_PARAMS, CKA_EC_POINT
 };
 static const CK_ULONG ecPubKeyAttrsCount = 
 			sizeof(ecPubKeyAttrs)/sizeof(ecPubKeyAttrs[0]);
 #endif
 
 static const CK_ATTRIBUTE_TYPE commonPrivKeyAttrs[] = {
@@ -1274,17 +1274,17 @@ static const CK_ATTRIBUTE_TYPE dsaPrivKe
 static const CK_ULONG dsaPrivKeyAttrsCount = 
 			sizeof(dsaPrivKeyAttrs)/sizeof(dsaPrivKeyAttrs[0]);
 
 static const CK_ATTRIBUTE_TYPE dhPrivKeyAttrs[] = {
     CKA_PRIME, CKA_BASE, CKA_VALUE
 };
 static const CK_ULONG dhPrivKeyAttrsCount = 
 			sizeof(dhPrivKeyAttrs)/sizeof(dhPrivKeyAttrs[0]);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 static const CK_ATTRIBUTE_TYPE ecPrivKeyAttrs[] = {
     CKA_EC_PARAMS, CKA_VALUE
 };
 static const CK_ULONG ecPrivKeyAttrsCount = 
 			sizeof(ecPrivKeyAttrs)/sizeof(ecPrivKeyAttrs[0]);
 #endif
 
 static const CK_ATTRIBUTE_TYPE certAttrs[] = {
@@ -1385,17 +1385,17 @@ stfk_CopyTokenPrivateKey(SFTKObject *des
     case CKK_DSA:
 	crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPrivKeyAttrs,
 							dsaPrivKeyAttrsCount);
 	break;
     case CKK_DH:
 	crv = stfk_CopyTokenAttributes(destObject, src_to, dhPrivKeyAttrs,
 							dhPrivKeyAttrsCount);
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKK_EC:
 	crv = stfk_CopyTokenAttributes(destObject, src_to, ecPrivKeyAttrs,
 							ecPrivKeyAttrsCount);
 	break;
 #endif
      default:
 	crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types
 				* of token keys into our database. */
@@ -1447,17 +1447,17 @@ stfk_CopyTokenPublicKey(SFTKObject *dest
     case CKK_DSA:
 	crv = stfk_CopyTokenAttributes(destObject, src_to, dsaPubKeyAttrs,
 							dsaPubKeyAttrsCount);
 	break;
     case CKK_DH:
 	crv = stfk_CopyTokenAttributes(destObject, src_to, dhPubKeyAttrs,
 							dhPubKeyAttrsCount);
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case CKK_EC:
 	crv = stfk_CopyTokenAttributes(destObject, src_to, ecPubKeyAttrs,
 							ecPubKeyAttrsCount);
 	break;
 #endif
      default:
 	crv = CKR_DEVICE_ERROR; /* shouldn't happen unless we store more types
 				* of token keys into our database. */
--- a/security/nss/lib/softoken/softkver.h
+++ b/security/nss/lib/softoken/softkver.h
@@ -3,17 +3,17 @@
  *
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef _SOFTKVER_H_
 #define _SOFTKVER_H_
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #ifdef NSS_ECC_MORE_THAN_SUITE_B
 #define SOFTOKEN_ECC_STRING " Extended ECC"
 #else
 #define SOFTOKEN_ECC_STRING " Basic ECC"
 #endif
 #else
 #define SOFTOKEN_ECC_STRING ""
 #endif
--- a/security/nss/lib/softoken/softoken.h
+++ b/security/nss/lib/softoken/softoken.h
@@ -30,17 +30,17 @@ RSA_HashSign(SECOidTag hashOid, NSSLOWKE
              unsigned char *sig, unsigned int *sigLen, unsigned int maxLen,
              const unsigned char *hash, unsigned int hashLen);
 
 extern SECStatus
 RSA_HashCheckSign(SECOidTag hashOid, NSSLOWKEYPublicKey *key,
                   const unsigned char *sig, unsigned int sigLen,
                   const unsigned char *hash, unsigned int hashLen);
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 /*
 ** pepare an ECParam structure from DEREncoded params
  */
 extern SECStatus EC_FillParams(PLArenaPool *arena,
                                const SECItem *encodedParams, ECParams *params);
 extern SECStatus EC_DecodeParams(const SECItem *encodedParams, 
 				ECParams **ecparams);
 extern SECStatus EC_CopyParams(PLArenaPool *arena, ECParams *dstParams,
--- a/security/nss/lib/ssl/derive.c
+++ b/security/nss/lib/ssl/derive.c
@@ -612,17 +612,17 @@ SSL_CanBypass(CERTCertificate *cert, SEC
     CK_MECHANISM_TYPE mechanism_array[2];
     SECItem           enc_pms = {siBuffer, NULL, 0};
     PRBool	      isTLS = PR_FALSE;
     SSLCipherSuiteInfo csdef;
     PRBool	      testrsa = PR_FALSE;
     PRBool	      testrsa_export = PR_FALSE;
     PRBool	      testecdh = PR_FALSE;
     PRBool	      testecdhe = PR_FALSE;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     SECKEYECParams ecParams = { siBuffer, NULL, 0 };
 #endif
 
     if (!cert || !srvPrivkey || !ciphersuites || !pcanbypass) {
 	PORT_SetError(SEC_ERROR_INVALID_ARGS);
         return SECFailure;
     }
     
@@ -750,17 +750,17 @@ SSL_CanBypass(CERTCertificate *cert, SEC
 	}
 
 	/* Check for NULL to avoid double free. 
 	 * SECItem_FreeItem sets data NULL in secitem.c#265 
 	 */
 	if (enc_pms.data != NULL) {
 	    SECITEM_FreeItem(&enc_pms, PR_FALSE);
         }
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	for (; (privKeytype == ecKey && ( testecdh || testecdhe)) ||
 	       (privKeytype == rsaKey && testecdhe); ) {
 	    CK_MECHANISM_TYPE target;
 	    SECKEYPublicKey  *keapub = NULL;
 	    SECKEYPrivateKey *keapriv;
 	    SECKEYPublicKey  *cpub = NULL; /* client's ephemeral ECDH keys */
 	    SECKEYPrivateKey *cpriv = NULL;
 	    SECKEYECParams   *pecParams = NULL;
@@ -854,17 +854,17 @@ SSL_CanBypass(CERTCertificate *cert, SEC
 		goto done;
 	    break;
 	}
 	/* Check for NULL to avoid double free. */
 	if (ecParams.data != NULL) {
 	    PORT_Free(ecParams.data);
 	    ecParams.data = NULL;
 	}
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	if (pms)
 	    PK11_FreeSymKey(pms);
     }
 
     /* *pcanbypass has been set */
     rv = SECSuccess;
     
   done:
@@ -872,22 +872,22 @@ SSL_CanBypass(CERTCertificate *cert, SEC
 	PK11_FreeSymKey(pms);
 
     /* Check for NULL to avoid double free. 
      * SECItem_FreeItem sets data NULL in secitem.c#265 
      */
     if (enc_pms.data != NULL) {
     	SECITEM_FreeItem(&enc_pms, PR_FALSE);
     }
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     if (ecParams.data != NULL) {
         PORT_Free(ecParams.data);
         ecParams.data = NULL;
     }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     if (srvPubkey) {
     	SECKEY_DestroyPublicKey(srvPubkey);
 	srvPubkey = NULL;
     }
 
 
     return rv;
--- a/security/nss/lib/ssl/dtlscon.c
+++ b/security/nss/lib/ssl/dtlscon.c
@@ -25,25 +25,25 @@ static const PRUint16 COMMON_MTU_VALUES[
     576 - 28,   /* Common assumption */
     256 - 28    /* We're in serious trouble now */
 };
 
 #define DTLS_COOKIE_BYTES 32
 
 /* List copied from ssl3con.c:cipherSuites */
 static const ssl3CipherSuite nonDTLSSuites[] = {
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
     TLS_ECDHE_RSA_WITH_RC4_128_SHA,
-#endif  /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     TLS_DHE_DSS_WITH_RC4_128_SHA,
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     TLS_ECDH_RSA_WITH_RC4_128_SHA,
     TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
-#endif  /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     SSL_RSA_WITH_RC4_128_MD5,
     SSL_RSA_WITH_RC4_128_SHA,
     TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
     SSL_RSA_EXPORT_WITH_RC4_40_MD5,
     0 /* End of list marker */
 };
 
 /* Map back and forth between TLS and DTLS versions in wire format.
--- a/security/nss/lib/ssl/ssl3con.c
+++ b/security/nss/lib/ssl/ssl3con.c
@@ -84,59 +84,59 @@ static SECStatus ssl3_AESGCMBypass(ssl3K
  * in this table must match the ordering in SSL_ImplementedCiphers (sslenum.c)
  *
  * Important: See bug 946147 before enabling, reordering, or adding any cipher
  * suites to this list.
  */
 static ssl3CipherSuiteCfg cipherSuites[ssl_V3_SUITES_IMPLEMENTED] = {
    /*      cipher_suite                     policy       enabled   isPresent */
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
  { TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
    /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is out of order to work around
     * bug 946147.
     */
  { TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,        SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_RSA_WITH_RC4_128_SHA,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
  { TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_DHE_DSS_WITH_AES_128_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_DHE_DSS_WITH_AES_256_CBC_SHA,        SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,     SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,   SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,       SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_DHE_DSS_WITH_RC4_128_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
  { TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,    SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_ECDSA_WITH_RC4_128_SHA,         SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_RSA_WITH_RC4_128_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
  /* RSA */
  { TLS_RSA_WITH_AES_128_GCM_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_RSA_WITH_AES_128_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_RSA_WITH_AES_128_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,       SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_RSA_WITH_AES_256_CBC_SHA,            SSL_ALLOWED, PR_TRUE,  PR_FALSE},
  { TLS_RSA_WITH_AES_256_CBC_SHA256,         SSL_ALLOWED, PR_TRUE,  PR_FALSE},
@@ -157,22 +157,22 @@ static ssl3CipherSuiteCfg cipherSuites[s
  { TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,     SSL_ALLOWED, PR_FALSE, PR_FALSE},
 
  /* export ciphersuites with 512-bit public key exchange keys */
  { SSL_RSA_EXPORT_WITH_RC4_40_MD5,          SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,      SSL_ALLOWED, PR_FALSE, PR_FALSE},
 
  /* ciphersuites with no encryption */
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
  { TLS_ECDHE_ECDSA_WITH_NULL_SHA,           SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDHE_RSA_WITH_NULL_SHA,             SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_RSA_WITH_NULL_SHA,              SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_ECDH_ECDSA_WITH_NULL_SHA,            SSL_ALLOWED, PR_FALSE, PR_FALSE},
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
  { SSL_RSA_WITH_NULL_SHA,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { TLS_RSA_WITH_NULL_SHA256,                SSL_ALLOWED, PR_FALSE, PR_FALSE},
  { SSL_RSA_WITH_NULL_MD5,                   SSL_ALLOWED, PR_FALSE, PR_FALSE},
 };
 
 /* Verify that SSL_ImplementedCiphers and cipherSuites are in consistent order.
  */
 #ifdef DEBUG
@@ -219,31 +219,31 @@ compressionEnabled(sslSocket *ss, SSLCom
 #endif
     default:
 	return PR_FALSE;
     }
 }
 
 static const /*SSL3ClientCertificateType */ PRUint8 certificate_types [] = {
     ct_RSA_sign,
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     ct_ECDSA_sign,
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     ct_DSS_sign,
 };
 
 /* This block is the contents of the supported_signature_algorithms field of
  * our TLS 1.2 CertificateRequest message, in wire format. See
  * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1
  *
  * This block contains only sha256 entries because we only support TLS 1.2
  * CertificateVerify messages that use the handshake hash. */
 static const PRUint8 supported_signature_algorithms[] = {
     tls_hash_sha256, tls_sig_rsa,
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     tls_hash_sha256, tls_sig_ecdsa,
 #endif
     tls_hash_sha256, tls_sig_dsa,
 };
 
 #define EXPORT_RSA_KEY_LENGTH 64	/* bytes */
 
 
@@ -294,23 +294,23 @@ static const ssl3KEADef kea_defs[] =
     {kea_dh_rsa_export,  kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
     {kea_dhe_dss,        kt_dh,       sign_dsa,  PR_FALSE,   0, PR_FALSE},
     {kea_dhe_dss_export, kt_dh,       sign_dsa,  PR_TRUE,  512, PR_FALSE},
     {kea_dhe_rsa,        kt_dh,       sign_rsa,  PR_FALSE,   0, PR_FALSE},
     {kea_dhe_rsa_export, kt_dh,       sign_rsa,  PR_TRUE,  512, PR_FALSE},
     {kea_dh_anon,        kt_dh,       sign_null, PR_FALSE,   0, PR_FALSE},
     {kea_dh_anon_export, kt_dh,       sign_null, PR_TRUE,  512, PR_FALSE},
     {kea_rsa_fips,       kt_rsa,      sign_rsa,  PR_FALSE,   0, PR_TRUE },
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     {kea_ecdh_ecdsa,     kt_ecdh,     sign_ecdsa,  PR_FALSE, 0, PR_FALSE},
     {kea_ecdhe_ecdsa,    kt_ecdh,     sign_ecdsa,  PR_FALSE,   0, PR_FALSE},
     {kea_ecdh_rsa,       kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
     {kea_ecdhe_rsa,      kt_ecdh,     sign_rsa,  PR_FALSE,   0, PR_FALSE},
     {kea_ecdh_anon,      kt_ecdh,     sign_null,  PR_FALSE,   0, PR_FALSE},
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 };
 
 /* must use ssl_LookupCipherSuiteDef to access */
 static const ssl3CipherSuiteDef cipher_suite_defs[] = 
 {
 /*  cipher_suite                    bulk_cipher_alg mac_alg key_exchange_alg */
 
     {SSL_NULL_WITH_NULL_NULL,       cipher_null,   mac_null, kea_null},
@@ -400,17 +400,17 @@ static const ssl3CipherSuiteDef cipher_s
     {SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_rsa_fips},
     {SSL_RSA_FIPS_WITH_DES_CBC_SHA, cipher_des,    mac_sha, kea_rsa_fips},
 
     {TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_dhe_rsa},
     {TLS_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_rsa},
     {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_rsa},
     {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, cipher_aes_128_gcm, mac_aead, kea_ecdhe_ecdsa},
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     {TLS_ECDH_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdh_ecdsa},
     {TLS_ECDH_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdh_ecdsa},
     {TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, cipher_3des, mac_sha, kea_ecdh_ecdsa},
     {TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, cipher_aes_128, mac_sha, kea_ecdh_ecdsa},
     {TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, cipher_aes_256, mac_sha, kea_ecdh_ecdsa},
 
     {TLS_ECDHE_ECDSA_WITH_NULL_SHA,        cipher_null, mac_sha, kea_ecdhe_ecdsa},
     {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,      cipher_rc4, mac_sha, kea_ecdhe_ecdsa},
@@ -434,17 +434,17 @@ static const ssl3CipherSuiteDef cipher_s
 
 #if 0
     {TLS_ECDH_anon_WITH_NULL_SHA,         cipher_null,    mac_sha, kea_ecdh_anon},
     {TLS_ECDH_anon_WITH_RC4_128_SHA,      cipher_rc4,     mac_sha, kea_ecdh_anon},
     {TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA, cipher_3des,    mac_sha, kea_ecdh_anon},
     {TLS_ECDH_anon_WITH_AES_128_CBC_SHA,  cipher_aes_128, mac_sha, kea_ecdh_anon},
     {TLS_ECDH_anon_WITH_AES_256_CBC_SHA,  cipher_aes_256, mac_sha, kea_ecdh_anon},
 #endif
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 };
 
 static const CK_MECHANISM_TYPE kea_alg_defs[] = {
     0x80000000L,
     CKM_RSA_PKCS,
     CKM_DH_PKCS_DERIVE,
     CKM_KEA_KEY_DERIVE,
     CKM_ECDH1_DERIVE
@@ -507,17 +507,17 @@ const char * const ssl3_cipherName[] = {
     "AES-256",
     "Camellia-128",
     "Camellia-256",
     "SEED-CBC",
     "AES-128-GCM",
     "missing"
 };
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 /* The ECCWrappedKeyInfo structure defines how various pieces of 
  * information are laid out within wrappedSymmetricWrappingkey 
  * for ECDH key exchange. Since wrappedSymmetricWrappingkey is 
  * a 512-byte buffer (see sslimpl.h), the variable length field 
  * in ECCWrappedKeyInfo can be at most (512 - 8) = 504 bytes.
  *
  * XXX For now, NSS only supports named elliptic curves of size 571 bits 
  * or smaller. The public value will fit within 145 bytes and EC params
@@ -529,17 +529,17 @@ const char * const ssl3_cipherName[] = {
 typedef struct ECCWrappedKeyInfoStr {
     PRUint16 size;            /* EC public key size in bits */
     PRUint16 encodedParamLen; /* length (in bytes) of DER encoded EC params */
     PRUint16 pubValueLen;     /* length (in bytes) of EC public value */
     PRUint16 wrappedKeyLen;   /* length (in bytes) of the wrapped key */
     PRUint8 var[MAX_EC_WRAPPED_KEY_BUFLEN]; /* this buffer contains the */
     /* EC public-key params, the EC public value and the wrapped key  */
 } ECCWrappedKeyInfo;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 #if defined(TRACE)
 
 static char *
 ssl3_DecodeHandshakeType(int msgType)
 {
     char * rv;
     static char line[40];
@@ -726,17 +726,17 @@ ssl3_config_match_init(sslSocket *ss)
 	    	suite->isPresent = PR_FALSE;
 		continue;
 	    }
 	    cipher_alg = bulk_cipher_defs[cipher_def->bulk_cipher_alg].calg;
 	    PORT_Assert(  alg2Mech[cipher_alg].calg == cipher_alg);
 	    cipher_mech = alg2Mech[cipher_alg].cmech;
 	    exchKeyType =
 	    	    kea_defs[cipher_def->key_exchange_alg].exchKeyType;
-#ifndef NSS_ENABLE_ECC
+#ifdef NSS_DISABLE_ECC
 	    svrAuth = ss->serverCerts + exchKeyType;
 #else
 	    /* XXX SSLKEAType isn't really a good choice for 
 	     * indexing certificates. It doesn't work for
 	     * (EC)DHE-* ciphers. Here we use a hack to ensure
 	     * that the server uses an RSA cert for (EC)DHE-RSA.
 	     */
 	    switch (cipher_def->key_exchange_alg) {
@@ -760,17 +760,17 @@ ssl3_config_match_init(sslSocket *ss)
 		 * we could support both key exchange mechanisms
 		 * simultaneously. For now, both of them use
 		 * whatever is in the certificate slot for kt_ecdh
 		 */
 	    default:
 		svrAuth = ss->serverCerts + exchKeyType;
 		break;
 	    }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 	    /* Mark the suites that are backed by real tokens, certs and keys */
 	    suite->isPresent = (PRBool)
 		(((exchKeyType == kt_null) ||
 		   ((!isServer || (svrAuth->serverKeyPair &&
 		                   svrAuth->SERVERKEY &&
 				   svrAuth->serverCertChain)) &&
 		    PK11_TokenExists(kea_alg_defs[exchKeyType]))) &&
@@ -919,30 +919,30 @@ ssl3_SignHashes(SSL3Hashes *hash, SECKEY
 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
 	    hashItem.data = hash->u.s.sha;
 	    hashItem.len = sizeof(hash->u.s.sha);
 	} else {
 	    hashItem.data = hash->u.raw;
 	    hashItem.len = hash->len;
 	}
 	break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case ecKey:
 	doDerEncode = PR_TRUE;
 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
 	 * In that case, we use just the SHA1 part. */
 	if (hash->hashAlg == SEC_OID_UNKNOWN) {
 	    hashItem.data = hash->u.s.sha;
 	    hashItem.len = sizeof(hash->u.s.sha);
 	} else {
 	    hashItem.data = hash->u.raw;
 	    hashItem.len = hash->len;
 	}
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     default:
 	PORT_SetError(SEC_ERROR_INVALID_KEY);
 	goto done;
     }
     PRINT_BUF(60, (NULL, "hash(es) to be signed", hashItem.data, hashItem.len));
 
     if (hash->hashAlg == SEC_OID_UNKNOWN) {
 	signatureLen = PK11_SignatureLen(key);
@@ -1030,17 +1030,17 @@ ssl3_VerifySignedHashes(SSL3Hashes *hash
 	    if (!signature) {
 	    	PORT_SetError(SSL_ERROR_BAD_HANDSHAKE_HASH_VALUE);
 		return SECFailure;
 	    }
 	    buf = signature;
 	}
 	break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case ecKey:
 	encAlg = SEC_OID_ANSIX962_EC_PUBLIC_KEY;
 	/* SEC_OID_UNKNOWN is used to specify the MD5/SHA1 concatenated hash.
 	 * In that case, we use just the SHA1 part.
 	 * ECDSA signatures always encode the integers r and s using ASN.1
 	 * (unlike DSA where ASN.1 encoding is used with TLS but not with
 	 * SSL3). So we can use VFY_VerifyDigestDirect for ECDSA.
 	 */
@@ -1048,17 +1048,17 @@ ssl3_VerifySignedHashes(SSL3Hashes *hash
 	    hashAlg = SEC_OID_SHA1;
 	    hashItem.data = hash->u.s.sha;
 	    hashItem.len = sizeof(hash->u.s.sha);
 	} else {
 	    hashItem.data = hash->u.raw;
 	    hashItem.len = hash->len;
 	}
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     default:
     	SECKEY_DestroyPublicKey(key);
 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
 	return SECFailure;
     }
 
     PRINT_BUF(60, (NULL, "hash(es) to be verified",
@@ -5073,22 +5073,22 @@ ssl3_SendClientHello(sslSocket *ss, PRBo
 	}
 	maxBytes        -= extLen;
 	total_exten_len += extLen;
 
 	if (total_exten_len > 0)
 	    total_exten_len += 2;
     }
 
-#if defined(NSS_ENABLE_ECC)
+#ifndef NSS_DISABLE_ECC
     if (!total_exten_len || !isTLS) {
 	/* not sending the elliptic_curves and ec_point_formats extensions */
     	ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
     }
-#endif
+#endif /* NSS_DISABLE_ECC */
 
     if (IS_DTLS(ss)) {
 	ssl3_DisableNonDTLSSuites(ss);
     }
 
     /* how many suites are permitted by policy and user preference? */
     num_suites = count_cipher_suites(ss, ss->ssl3.policy, PR_TRUE);
     if (!num_suites) {
@@ -5389,21 +5389,21 @@ ssl_UnwrapSymWrappingKey(
 	SSLWrappedSymWrappingKey *pWswk,
 	SECKEYPrivateKey *        svrPrivKey,
 	SSL3KEAType               exchKeyType,
 	CK_MECHANISM_TYPE         masterWrapMech,
 	void *                    pwArg)
 {
     PK11SymKey *             unwrappedWrappingKey  = NULL;
     SECItem                  wrappedKey;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     PK11SymKey *             Ks;
     SECKEYPublicKey          pubWrapKey;
     ECCWrappedKeyInfo        *ecWrapped;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     /* found the wrapping key on disk. */
     PORT_Assert(pWswk->symWrapMechanism == masterWrapMech);
     PORT_Assert(pWswk->exchKeyType      == exchKeyType);
     if (pWswk->symWrapMechanism != masterWrapMech ||
 	pWswk->exchKeyType      != exchKeyType) {
 	goto loser;
     }
@@ -5415,17 +5415,17 @@ ssl_UnwrapSymWrappingKey(
     switch (exchKeyType) {
 
     case kt_rsa:
 	unwrappedWrappingKey =
 	    PK11_PubUnwrapSymKey(svrPrivKey, &wrappedKey,
 				 masterWrapMech, CKA_UNWRAP, 0);
 	break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case kt_ecdh:
         /* 
          * For kt_ecdh, we first create an EC public key based on
          * data stored with the wrappedSymmetricWrappingkey. Next,
          * we do an ECDH computation involving this public key and
          * the SSL server's (long-term) EC private key. The resulting
          * shared secret is treated the same way as Fortezza's Ks, i.e.,
          * it is used to recover the symmetric wrapping key.
@@ -5554,22 +5554,22 @@ getWrappingKey( sslSocket *       ss,
     PK11SymKey *             unwrappedWrappingKey  = NULL;
     PK11SymKey **            pSymWrapKey;
     CK_MECHANISM_TYPE        asymWrapMechanism = CKM_INVALID_MECHANISM;
     int                      length;
     int                      symWrapMechIndex;
     SECStatus                rv;
     SECItem                  wrappedKey;
     SSLWrappedSymWrappingKey wswk;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     PK11SymKey *      Ks = NULL;
     SECKEYPublicKey   *pubWrapKey = NULL;
     SECKEYPrivateKey  *privWrapKey = NULL;
     ECCWrappedKeyInfo *ecWrapped;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     svrPrivKey  = ss->serverCerts[exchKeyType].SERVERKEY;
     PORT_Assert(svrPrivKey != NULL);
     if (!svrPrivKey) {
     	return NULL;	/* why are we here?!? */
     }
 
     symWrapMechIndex = ssl_FindIndexByWrapMechanism(masterWrapMech);
@@ -5642,17 +5642,17 @@ getWrappingKey( sslSocket *       ss,
     /* wrap symmetric wrapping key in server's public key. */
     switch (exchKeyType) {
     case kt_rsa:
 	asymWrapMechanism = CKM_RSA_PKCS;
 	rv = PK11_PubWrapSymKey(asymWrapMechanism, svrPubKey,
 	                        unwrappedWrappingKey, &wrappedKey);
 	break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case kt_ecdh:
 	/*
 	 * We generate an ephemeral EC key pair. Perform an ECDH
 	 * computation involving this ephemeral EC public key and
 	 * the SSL server's (long-term) EC private key. The resulting
 	 * shared secret is treated in the same way as Fortezza's Ks, 
 	 * i.e., it is used to wrap the wrapping key. To facilitate
 	 * unwrapping in ssl_UnwrapWrappingKey, we also store all
@@ -5728,17 +5728,17 @@ getWrappingKey( sslSocket *       ss,
 	ecWrapped->wrappedKeyLen = wrappedKey.len;
 
 ec_cleanup:
 	if (privWrapKey) SECKEY_DestroyPrivateKey(privWrapKey);
 	if (pubWrapKey) SECKEY_DestroyPublicKey(pubWrapKey);
 	if (Ks) PK11_FreeSymKey(Ks);
 	asymWrapMechanism = masterWrapMech;
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     default:
 	rv = SECFailure;
 	break;
     }
 
     if (rv != SECSuccess) {
 	ssl_MapLowLevelError(SSL_ERROR_CLIENT_KEY_EXCHANGE_FAILURE);
@@ -6041,21 +6041,21 @@ ssl3_SendClientKeyExchange(sslSocket *ss
     case kt_rsa:
 	rv = sendRSAClientKeyExchange(ss, serverKey);
 	break;
 
     case kt_dh:
 	rv = sendDHClientKeyExchange(ss, serverKey);
 	break;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case kt_ecdh:
 	rv = ssl3_SendECDHClientKeyExchange(ss, serverKey);
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     default:
 	/* got an unknown or unsupported Key Exchange Algorithm.  */
 	SEND_ALERT
 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
 	break;
     }
 
@@ -6773,21 +6773,21 @@ ssl3_HandleServerKeyExchange(sslSocket *
             PORT_FreeArena(arena, PR_FALSE);
 	    goto no_memory;
         }
     	ss->sec.peerKey = peerKey;
     	ss->ssl3.hs.ws = wait_cert_request;
     	return SECSuccess;
     }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case kt_ecdh:
 	rv = ssl3_HandleECDHServerKeyExchange(ss, b, length);
 	return rv;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     default:
     	desc    = handshake_failure;
 	errCode = SEC_ERROR_UNSUPPORTED_KEYALG;
 	break;		/* goto alert_loser; */
     }
 
 alert_loser:
@@ -7515,24 +7515,24 @@ ssl3_SendServerHelloSequence(sslSocket *
 		return rv;	/* err code was set. */
 	    }
 	} else {
 #ifndef HACKED_EXPORT_SERVER
 	    PORT_SetError(SSL_ERROR_PUB_KEY_SIZE_LIMIT_EXCEEDED);
 	    return rv;
 #endif
 	}
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     } else if ((kea_def->kea == kea_ecdhe_rsa) ||
 	       (kea_def->kea == kea_ecdhe_ecdsa)) {
 	rv = ssl3_SendServerKeyExchange(ss);
 	if (rv != SECSuccess) {
 	    return rv;	/* err code was set. */
 	}
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     }
 
     if (ss->opt.requestCertificate) {
 	rv = ssl3_SendCertificateRequest(ss);
 	if (rv != SECSuccess) {
 	    return rv;		/* err code is set. */
 	}
     }
@@ -7810,17 +7810,17 @@ ssl3_HandleClientHello(sslSocket *ss, SS
 	    SSL_AtomicIncrementLong(& ssl3stats.hch_sid_cache_not_ok );
 	    if (ss->sec.uncache)
                 ss->sec.uncache(sid);
 	    ssl_FreeSID(sid);
 	    sid = NULL;
 	}
     }
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     /* Disable any ECC cipher suites for which we have no cert. */
     ssl3_FilterECCipherSuitesByServerCerts(ss);
 #endif
 
     if (IS_DTLS(ss)) {
 	ssl3_DisableNonDTLSSuites(ss);
     }
 
@@ -8427,17 +8427,17 @@ ssl3_HandleV2ClientHello(sslSocket *ss, 
 
     PORT_Memset(&ss->ssl3.hs.client_random, 0, SSL3_RANDOM_LENGTH);
     PORT_Memcpy(
 	&ss->ssl3.hs.client_random.rand[SSL3_RANDOM_LENGTH - rand_length],
 	random, rand_length);
 
     PRINT_BUF(60, (ss, "client random:", &ss->ssl3.hs.client_random.rand[0],
 		   SSL3_RANDOM_LENGTH));
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     /* Disable any ECC cipher suites for which we have no cert. */
     ssl3_FilterECCipherSuitesByServerCerts(ss);
 #endif
     i = ssl3_config_match_init(ss);
     if (i <= 0) {
     	errCode = PORT_GetError();	/* error code is already set. */
 	goto alert_loser;
     }
@@ -8816,22 +8816,22 @@ ssl3_SendServerKeyExchange(sslSocket *ss
 	rv = ssl3_AppendHandshakeVariable(ss, signed_hash.data,
 	                                  signed_hash.len, 2);
 	if (rv != SECSuccess) {
 	    goto loser; 	/* err set by AppendHandshake. */
 	}
 	PORT_Free(signed_hash.data);
 	return SECSuccess;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case kt_ecdh: {
 	rv = ssl3_SendECDHServerKeyExchange(ss, &sigAndHash);
 	return rv;
     }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     case kt_dh:
     case kt_null:
     default:
 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
 	break;
     }
 loser:
@@ -9244,19 +9244,19 @@ double_bypass:
  */
 static SECStatus
 ssl3_HandleClientKeyExchange(sslSocket *ss, SSL3Opaque *b, PRUint32 length)
 {
     SECKEYPrivateKey *serverKey         = NULL;
     SECStatus         rv;
     const ssl3KEADef *kea_def;
     ssl3KeyPair     *serverKeyPair      = NULL;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     SECKEYPublicKey *serverPubKey       = NULL;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     SSL_TRC(3, ("%d: SSL3[%d]: handle client_key_exchange handshake",
 		SSL_GETPID(), ss->fd));
 
     PORT_Assert( ss->opt.noLocks || ssl_HaveRecvBufLock(ss) );
     PORT_Assert( ss->opt.noLocks || ssl_HaveSSL3HandshakeLock(ss) );
 
     if (ss->ssl3.hs.ws != wait_client_key) {
@@ -9276,17 +9276,17 @@ ssl3_HandleClientKeyExchange(sslSocket *
 	      ss->stepDownKeyPair == NULL) {
 	 	/* shouldn't happen, don't use step down if it does */
 		goto skip;
 	 }
     	serverKeyPair = ss->stepDownKeyPair;
 	ss->sec.keaKeyBits = EXPORT_RSA_KEY_LENGTH * BPB;
     } else 
 skip:
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     /* XXX Using SSLKEAType to index server certifiates
      * does not work for (EC)DHE ciphers. Until we have
      * an indexing mechanism general enough for all key
      * exchange algorithms, we'll need to deal with each
      * one seprately.
      */
     if ((kea_def->kea == kea_ecdhe_rsa) ||
                (kea_def->kea == kea_ecdhe_ecdsa)) {
@@ -9322,17 +9322,17 @@ skip:
 	rv = ssl3_HandleRSAClientKeyExchange(ss, b, length, serverKey);
 	if (rv != SECSuccess) {
 	    SEND_ALERT
 	    return SECFailure;	/* error code set */
 	}
 	break;
 
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     case kt_ecdh:
 	/* XXX We really ought to be able to store multiple
 	 * EC certs (a requirement if we wish to support both
 	 * ECDH-RSA and ECDH-ECDSA key exchanges concurrently).
 	 * When we make that change, we'll need an index other
 	 * than kt_ecdh to pick the right EC certificate.
 	 */
 	if (serverKeyPair) {
@@ -9344,17 +9344,17 @@ skip:
 	    return SECFailure;
 	}
 	rv = ssl3_HandleECDHClientKeyExchange(ss, b, length, 
 					      serverPubKey, serverKey);
 	if (rv != SECSuccess) {
 	    return SECFailure;	/* error code set */
 	}
 	break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     default:
 	(void) ssl3_HandshakeFailure(ss);
 	PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
 	return SECFailure;
     }
     ss->ssl3.hs.ws = ss->sec.peerCert ? wait_cert_verify : wait_change_cipher;
     return SECSuccess;
@@ -9949,17 +9949,17 @@ ssl3_AuthCertificate(sslSocket *ss)
 	** it will get fixed when we handle the server key exchange message.
 	*/
 	SECKEYPublicKey * pubKey  = CERT_ExtractPublicKey(cert);
 	ss->sec.authAlgorithm = ss->ssl3.hs.kea_def->signKeyType;
 	ss->sec.keaType       = ss->ssl3.hs.kea_def->exchKeyType;
 	if (pubKey) {
 	    ss->sec.keaKeyBits = ss->sec.authKeyBits =
 		SECKEY_PublicKeyStrengthInBits(pubKey);
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	    if (ss->sec.keaType == kt_ecdh) {
 		/* Get authKeyBits from signing key.
 		 * XXX The code below uses a quick approximation of
 		 * key size based on cert->signatureWrap.signature.data
 		 * (which contains the DER encoded signature). The field
 		 * cert->signatureWrap.signature.len contains the
 		 * length of the encoded signature in bits.
 		 */
@@ -9975,28 +9975,28 @@ ssl3_AuthCertificate(sslSocket *ss)
 		} else if (ss->ssl3.hs.kea_def->kea == kea_ecdh_rsa) {
 		    ss->sec.authKeyBits = cert->signatureWrap.signature.len;
 		    /* 
 		     * XXX: if cert is not signed by rsa we should
 		     * destroy pubKey and goto bad_cert
 		     */
 		}
 	    }
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	    SECKEY_DestroyPublicKey(pubKey); 
 	    pubKey = NULL;
     	}
 
 	ss->ssl3.hs.ws = wait_cert_request; /* disallow server_key_exchange */
 	if (ss->ssl3.hs.kea_def->is_limited ||
 	    /* XXX OR server cert is signing only. */
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	    ss->ssl3.hs.kea_def->kea == kea_ecdhe_ecdsa ||
 	    ss->ssl3.hs.kea_def->kea == kea_ecdhe_rsa ||
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 	    ss->ssl3.hs.kea_def->exchKeyType == kt_dh) {
 	    ss->ssl3.hs.ws = wait_server_key; /* allow server_key_exchange */
 	}
     } else {
 	ss->ssl3.hs.ws = wait_client_key;
     }
 
     PORT_Assert(rv == SECSuccess);
@@ -10560,17 +10560,17 @@ xmit_loser:
 	effectiveExchKeyType = ss->ssl3.hs.kea_def->exchKeyType;
     }
 
     if (sid->cached == never_cached && !ss->opt.noCache && ss->sec.cache) {
 	/* fill in the sid */
 	sid->u.ssl3.cipherSuite = ss->ssl3.hs.cipher_suite;
 	sid->u.ssl3.compression = ss->ssl3.hs.compression;
 	sid->u.ssl3.policy      = ss->ssl3.policy;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	sid->u.ssl3.negotiatedECCurves = ss->ssl3.hs.negotiatedECCurves;
 #endif
 	sid->u.ssl3.exchKeyType = effectiveExchKeyType;
 	sid->version            = ss->version;
 	sid->authAlgorithm      = ss->sec.authAlgorithm;
 	sid->authKeyBits        = ss->sec.authKeyBits;
 	sid->keaType            = ss->sec.keaType;
 	sid->keaKeyBits         = ss->sec.keaKeyBits;
@@ -11696,17 +11696,17 @@ ssl3_InitState(sslSocket *ss)
     ssl_GetSpecWriteLock(ss);
     ss->ssl3.crSpec = ss->ssl3.cwSpec = &ss->ssl3.specs[0];
     ss->ssl3.prSpec = ss->ssl3.pwSpec = &ss->ssl3.specs[1];
     ss->ssl3.hs.sendingSCSV = PR_FALSE;
     ssl3_InitCipherSpec(ss, ss->ssl3.crSpec);
     ssl3_InitCipherSpec(ss, ss->ssl3.prSpec);
 
     ss->ssl3.hs.ws = (ss->sec.isServer) ? wait_client_hello : wait_server_hello;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     ss->ssl3.hs.negotiatedECCurves = ssl3_GetSupportedECCurveMask(ss);
 #endif
     ssl_ReleaseSpecWriteLock(ss);
 
     PORT_Memset(&ss->xtnData, 0, sizeof(TLSExtensionData));
 
     if (IS_DTLS(ss)) {
 	ss->ssl3.hs.sendMessageSeq = 0;
--- a/security/nss/lib/ssl/ssl3ecc.c
+++ b/security/nss/lib/ssl/ssl3ecc.c
@@ -25,17 +25,17 @@
 #include "prthread.h"
 #include "prinit.h"
 
 #include "pk11func.h"
 #include "secmod.h"
 
 #include <stdio.h>
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 
 #ifndef PK11_SETATTRS
 #define PK11_SETATTRS(x,id,v,l) (x)->type = (id); \
 		(x)->pValue=(v); (x)->ulValueLen = (l);
 #endif
 
 #define SSL_GET_SERVER_PUBLIC_KEY(sock, type) \
     (ss->serverCerts[type].serverKeyPair ? \
@@ -1253,9 +1253,9 @@ ssl3_HandleSupportedCurvesXtn(sslSocket 
     return SECFailure;
 
 loser:
     /* no common curve supported */
     ssl3_DisableECCSuites(ss, ecSuites);
     return SECFailure;
 }
 
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
--- a/security/nss/lib/ssl/ssl3ext.c
+++ b/security/nss/lib/ssl/ssl3ext.c
@@ -225,17 +225,17 @@ ssl3_GetSessionTicketKeys(const unsigned
 
 /* Table of handlers for received TLS hello extensions, one per extension.
  * In the second generation, this table will be dynamic, and functions
  * will be registered here.
  */
 /* This table is used by the server, to handle client hello extensions. */
 static const ssl3HelloExtensionHandler clientHelloHandlers[] = {
     { ssl_server_name_xtn,        &ssl3_HandleServerNameXtn },
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     { ssl_elliptic_curves_xtn,    &ssl3_HandleSupportedCurvesXtn },
     { ssl_ec_point_formats_xtn,   &ssl3_HandleSupportedPointFormatsXtn },
 #endif
     { ssl_session_ticket_xtn,     &ssl3_ServerHandleSessionTicketXtn },
     { ssl_renegotiation_info_xtn, &ssl3_HandleRenegotiationInfoXtn },
     { ssl_next_proto_nego_xtn,    &ssl3_ServerHandleNextProtoNegoXtn },
     { ssl_use_srtp_xtn,           &ssl3_HandleUseSRTPXtn },
     { ssl_cert_status_xtn,        &ssl3_ServerHandleStatusRequestXtn },
@@ -267,17 +267,17 @@ static const ssl3HelloExtensionHandler s
  * These static tables are for the formatting of client hello extensions.
  * The server's table of hello senders is dynamic, in the socket struct,
  * and sender functions are registered there.
  */
 static const 
 ssl3HelloExtensionSender clientHelloSendersTLS[SSL_MAX_EXTENSIONS] = {
     { ssl_server_name_xtn,        &ssl3_SendServerNameXtn        },
     { ssl_renegotiation_info_xtn, &ssl3_SendRenegotiationInfoXtn },
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     { ssl_elliptic_curves_xtn,    &ssl3_SendSupportedCurvesXtn },
     { ssl_ec_point_formats_xtn,   &ssl3_SendSupportedPointFormatsXtn },
 #endif
     { ssl_session_ticket_xtn,     &ssl3_SendSessionTicketXtn },
     { ssl_next_proto_nego_xtn,    &ssl3_ClientSendNextProtoNegoXtn },
     { ssl_app_layer_protocol_xtn, &ssl3_ClientSendAppProtoXtn },
     { ssl_use_srtp_xtn,           &ssl3_SendUseSRTPXtn },
     { ssl_cert_status_xtn,        &ssl3_ClientSendStatusRequestXtn },
@@ -2214,17 +2214,17 @@ ssl3_ClientSendSigAlgsXtn(sslSocket * ss
 {
     static const unsigned char signatureAlgorithms[] = {
 	/* This block is the contents of our signature_algorithms extension, in
 	 * wire format. See
 	 * https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 */
 	tls_hash_sha256, tls_sig_rsa,
 	tls_hash_sha384, tls_sig_rsa,
 	tls_hash_sha1,   tls_sig_rsa,
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	tls_hash_sha256, tls_sig_ecdsa,
 	tls_hash_sha384, tls_sig_ecdsa,
 	tls_hash_sha1,   tls_sig_ecdsa,
 #endif
 	tls_hash_sha256, tls_sig_dsa,
 	tls_hash_sha1,   tls_sig_dsa,
     };
     PRInt32 extension_length;
--- a/security/nss/lib/ssl/sslcon.c
+++ b/security/nss/lib/ssl/sslcon.c
@@ -3096,25 +3096,25 @@ ssl2_BeginClientHandshake(sslSocket *ss)
 	ssl_GetSSL3HandshakeLock(ss);
 	ssl_GetXmitBufLock(ss);
 	rv =  ssl3_SendClientHello(ss, PR_FALSE);
 	ssl_ReleaseXmitBufLock(ss);
 	ssl_ReleaseSSL3HandshakeLock(ss);
 
 	return rv;
     }
-#if defined(NSS_ENABLE_ECC)
+#ifndef NSS_DISABLE_ECC
     /* ensure we don't neogtiate ECC cipher suites with SSL2 hello */
     ssl3_DisableECCSuites(ss, NULL); /* disable all ECC suites */
     if (ss->cipherSpecs != NULL) {
 	PORT_Free(ss->cipherSpecs);
 	ss->cipherSpecs     = NULL;
 	ss->sizeCipherSpecs = 0;
     }
-#endif
+#endif /* NSS_DISABLE_ECC */
 
     if (!ss->cipherSpecs) {
         rv = ssl2_ConstructCipherSpecs(ss);
 	if (rv < 0) {
 	    return rv;
     	}
     }
     localCipherSpecs = ss->cipherSpecs;
--- a/security/nss/lib/ssl/sslenum.c
+++ b/security/nss/lib/ssl/sslenum.c
@@ -42,59 +42,59 @@
  *      TLS_KRB5_EXPORT_WITH_RC4_40_MD5 { 0x00,0x2B }
  *      TLS_RSA_WITH_AES_128_CBC_SHA { 0x00,0x2F }
  *      TLS_RSA_WITH_3DES_EDE_CBC_SHA { 0x00,0x0A }
  *      TLS_RSA_WITH_DES_CBC_SHA { 0x00,0x09 }
  * The broken server only supports the third and fourth ones and will select
  * the third one.
  */
 const PRUint16 SSL_ImplementedCiphers[] = {
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
     TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
     /* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA must appear before
      * TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA to work around bug 946147.
      */
     TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
     TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
     TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
     TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
     TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
     TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
     TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
     TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
     TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
     TLS_ECDHE_RSA_WITH_RC4_128_SHA,
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
     TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
     TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
     TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
     TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
     TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
     TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
     TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
     TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
     TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
     TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
     SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
     SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
     TLS_DHE_DSS_WITH_RC4_128_SHA,
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
     TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
     TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
     TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
     TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
     TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
     TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
     TLS_ECDH_RSA_WITH_RC4_128_SHA,
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     TLS_RSA_WITH_AES_128_GCM_SHA256,
     TLS_RSA_WITH_AES_128_CBC_SHA,
     TLS_RSA_WITH_AES_128_CBC_SHA256,
     TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
     TLS_RSA_WITH_AES_256_CBC_SHA,
     TLS_RSA_WITH_AES_256_CBC_SHA256,
     TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
@@ -114,22 +114,22 @@ const PRUint16 SSL_ImplementedCiphers[] 
     TLS_RSA_EXPORT1024_WITH_RC4_56_SHA,
     TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA,
 
     /* export ciphersuites with 512-bit public key exchange keys */
     SSL_RSA_EXPORT_WITH_RC4_40_MD5,
     SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
 
     /* ciphersuites with no encryption */
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     TLS_ECDHE_ECDSA_WITH_NULL_SHA,
     TLS_ECDHE_RSA_WITH_NULL_SHA,
     TLS_ECDH_RSA_WITH_NULL_SHA,
     TLS_ECDH_ECDSA_WITH_NULL_SHA,
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
     SSL_RSA_WITH_NULL_SHA,
     TLS_RSA_WITH_NULL_SHA256,
     SSL_RSA_WITH_NULL_MD5,
 
     /* SSL2 cipher suites. */
     SSL_EN_RC4_128_WITH_MD5,
     SSL_EN_RC2_128_CBC_WITH_MD5,
     SSL_EN_DES_192_EDE3_CBC_WITH_MD5,  /* actually 112, not 192 */
--- a/security/nss/lib/ssl/sslimpl.h
+++ b/security/nss/lib/ssl/sslimpl.h
@@ -283,21 +283,21 @@ typedef struct {
 #else
     ssl3CipherSuite cipher_suite;
     PRUint8         policy;
     unsigned char   enabled   : 1;
     unsigned char   isPresent : 1;
 #endif
 } ssl3CipherSuiteCfg;
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 #define ssl_V3_SUITES_IMPLEMENTED 61
 #else
 #define ssl_V3_SUITES_IMPLEMENTED 37
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 #define MAX_DTLS_SRTP_CIPHER_SUITES 4
 
 typedef struct sslOptionsStr {
     /* If SSL_SetNextProtoNego has been called, then this contains the
      * list of supported protocols. */
     SECItem nextProtoNego;
 
@@ -648,19 +648,19 @@ struct sslSessionIDStr {
 	    SSLCompressionMethod  compression;
 	    int                   policy;
 	    ssl3SidKeys           keys;
 	    CK_MECHANISM_TYPE     masterWrapMech;
 				  /* mechanism used to wrap master secret */
             SSL3KEAType           exchKeyType;
 				  /* key type used in exchange algorithm,
 				   * and to wrap the sym wrapping key. */
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 	    PRUint32              negotiatedECCurves;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 	    /* The following values are NOT restored from the server's on-disk
 	     * session cache, but are restored from the client's cache.
 	     */
  	    PK11SymKey *      clientWriteKey;
 	    PK11SymKey *      serverWriteKey;
 
 	    /* The following values pertain to the slot that wrapped the 
@@ -880,19 +880,19 @@ const ssl3CipherSuiteDef *suite_def;
     NewSessionTicket      newSessionTicket;
 
     PRUint16              finishedBytes; /* size of single finished below */
     union {
 	TLSFinished       tFinished[2]; /* client, then server */
 	SSL3Finished      sFinished[2];
 	SSL3Opaque        data[72];
     }                     finishedMsgs;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     PRUint32              negotiatedECCurves; /* bit mask */
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
     PRBool                authCertificatePending;
     /* Which function should SSL_RestartHandshake* call if we're blocked?
      * One of NULL, ssl3_SendClientSecondRound, ssl3_FinishHandshake,
      * or ssl3_AlwaysFail */
     sslRestartTarget      restartTarget;
     /* Shared state between ssl3_HandleFinished and ssl3_FinishHandshake */
     PRBool                cacheSID;
@@ -1591,17 +1591,17 @@ int ssl3_GatherCompleteHandshake(sslSock
 /*
  * When talking to export clients or using export cipher suites, servers 
  * with public RSA keys larger than 512 bits need to use a 512-bit public
  * key, signed by the larger key.  The smaller key is a "step down" key.
  * Generate that key pair and keep it around.
  */
 extern SECStatus ssl3_CreateRSAStepDownKeys(sslSocket *ss);
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 extern void      ssl3_FilterECCipherSuitesByServerCerts(sslSocket *ss);
 extern PRBool    ssl3_IsECCEnabled(sslSocket *ss);
 extern SECStatus ssl3_DisableECCSuites(sslSocket * ss, 
                                        const ssl3CipherSuite * suite);
 extern PRUint32  ssl3_GetSupportedECCurveMask(sslSocket *ss);
 
 
 /* Macro for finding a curve equivalent in strength to RSA key's */
@@ -1646,17 +1646,17 @@ typedef enum { ec_noName     = 0,
 	       ec_pastLastName
 } ECName;
 
 extern SECStatus ssl3_ECName2Params(PLArenaPool *arena, ECName curve,
 				   SECKEYECParams *params);
 ECName	ssl3_GetCurveWithECKeyStrength(PRUint32 curvemsk, int requiredECCbits);
 
 
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 extern SECStatus ssl3_CipherPrefSetDefault(ssl3CipherSuite which, PRBool on);
 extern SECStatus ssl3_CipherPrefGetDefault(ssl3CipherSuite which, PRBool *on);
 extern SECStatus ssl2_CipherPrefSetDefault(PRInt32 which, PRBool enabled);
 extern SECStatus ssl2_CipherPrefGetDefault(PRInt32 which, PRBool *enabled);
 
 extern SECStatus ssl3_CipherPrefSet(sslSocket *ss, ssl3CipherSuite which, PRBool on);
 extern SECStatus ssl3_CipherPrefGet(sslSocket *ss, ssl3CipherSuite which, PRBool *on);
@@ -1681,17 +1681,17 @@ extern SECStatus ssl3_HandleHandshakeMes
 extern void ssl3_DestroySSL3Info(sslSocket *ss);
 
 extern SECStatus ssl3_NegotiateVersion(sslSocket *ss, 
 				       SSL3ProtocolVersion peerVersion,
 				       PRBool allowLargerPeerVersion);
 
 extern SECStatus ssl_GetPeerInfo(sslSocket *ss);
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 /* ECDH functions */
 extern SECStatus ssl3_SendECDHClientKeyExchange(sslSocket * ss, 
 			     SECKEYPublicKey * svrPubKey);
 extern SECStatus ssl3_HandleECDHServerKeyExchange(sslSocket *ss, 
 					SSL3Opaque *b, PRUint32 length);
 extern SECStatus ssl3_HandleECDHClientKeyExchange(sslSocket *ss, 
 				     SSL3Opaque *b, PRUint32 length,
                                      SECKEYPublicKey *srvrPubKey,
@@ -1766,17 +1766,17 @@ extern PRInt32 ssl3_SendServerNameXtn(ss
 /* Assigns new cert, cert chain and keys to ss->serverCerts
  * struct. If certChain is NULL, tries to find one. Aborts if
  * fails to do so. If cert and keyPair are NULL - unconfigures
  * sslSocket of kea type.*/
 extern SECStatus ssl_ConfigSecureServer(sslSocket *ss, CERTCertificate *cert,
                                         const CERTCertificateList *certChain,
                                         ssl3KeyPair *keyPair, SSLKEAType kea);
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 extern PRInt32 ssl3_SendSupportedCurvesXtn(sslSocket *ss,
 			PRBool append, PRUint32 maxBytes);
 extern PRInt32 ssl3_SendSupportedPointFormatsXtn(sslSocket *ss,
 			PRBool append, PRUint32 maxBytes);
 #endif
 
 /* call the registered extension handlers. */
 extern SECStatus ssl3_HandleHelloExtensions(sslSocket *ss, 
--- a/security/nss/lib/ssl/sslinfo.c
+++ b/security/nss/lib/ssl/sslinfo.c
@@ -166,17 +166,17 @@ static const SSLCipherSuiteInfo suiteInf
 {0,CS(TLS_RSA_EXPORT1024_WITH_RC4_56_SHA),    S_RSA, K_RSA, C_RC4, B_56,  M_SHA, 0, 1, 0, },
 {0,CS(TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA),   S_RSA, K_RSA, C_DES, B_DES, M_SHA, 0, 1, 0, },
 {0,CS(SSL_RSA_EXPORT_WITH_RC4_40_MD5),        S_RSA, K_RSA, C_RC4, B_40,  M_MD5, 0, 1, 0, },
 {0,CS(SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5),    S_RSA, K_RSA, C_RC2, B_40,  M_MD5, 0, 1, 0, },
 {0,CS(TLS_RSA_WITH_NULL_SHA256),              S_RSA, K_RSA, C_NULL,B_0,   M_SHA256, 0, 1, 0, },
 {0,CS(SSL_RSA_WITH_NULL_SHA),                 S_RSA, K_RSA, C_NULL,B_0,   M_SHA, 0, 1, 0, },
 {0,CS(SSL_RSA_WITH_NULL_MD5),                 S_RSA, K_RSA, C_NULL,B_0,   M_MD5, 0, 1, 0, },
 
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
 /* ECC cipher suites */
 {0,CS(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), S_RSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, },
 {0,CS(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), S_ECDSA, K_ECDHE, C_AESGCM, B_128, M_AEAD_128, 1, 0, 0, },
 
 {0,CS(TLS_ECDH_ECDSA_WITH_NULL_SHA),          S_ECDSA, K_ECDH, C_NULL, B_0, M_SHA, 0, 0, 0, },
 {0,CS(TLS_ECDH_ECDSA_WITH_RC4_128_SHA),       S_ECDSA, K_ECDH, C_RC4, B_128, M_SHA, 0, 0, 0, },
 {0,CS(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA),  S_ECDSA, K_ECDH, C_3DES, B_3DES, M_SHA, 1, 0, 0, },
 {0,CS(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA),   S_ECDSA, K_ECDH, C_AES, B_128, M_SHA, 1, 0, 0, },
@@ -196,17 +196,17 @@ static const SSLCipherSuiteInfo suiteInf
 {0,CS(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA),     S_RSA, K_ECDH, C_AES, B_256, M_SHA, 1, 0, 0, },
 
 {0,CS(TLS_ECDHE_RSA_WITH_NULL_SHA),           S_RSA, K_ECDHE, C_NULL, B_0, M_SHA, 0, 0, 0, },
 {0,CS(TLS_ECDHE_RSA_WITH_RC4_128_SHA),        S_RSA, K_ECDHE, C_RC4, B_128, M_SHA, 0, 0, 0, },
 {0,CS(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA),   S_RSA, K_ECDHE, C_3DES, B_3DES, M_SHA, 1, 0, 0, },
 {0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA),    S_RSA, K_ECDHE, C_AES, B_128, M_SHA, 1, 0, 0, },
 {0,CS(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256), S_RSA, K_ECDHE, C_AES, B_128, M_SHA256, 1, 0, 0, },
 {0,CS(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA),    S_RSA, K_ECDHE, C_AES, B_256, M_SHA, 1, 0, 0, },
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
 
 /* SSL 2 table */
 {0,CK(SSL_CK_RC4_128_WITH_MD5),               S_RSA, K_RSA, C_RC4, B_128, M_MD5, 0, 0, 0, },
 {0,CK(SSL_CK_RC2_128_CBC_WITH_MD5),           S_RSA, K_RSA, C_RC2, B_128, M_MD5, 0, 0, 0, },
 {0,CK(SSL_CK_DES_192_EDE3_CBC_WITH_MD5),      S_RSA, K_RSA, C_3DES,B_3DES,M_MD5, 0, 0, 0, },
 {0,CK(SSL_CK_DES_64_CBC_WITH_MD5),            S_RSA, K_RSA, C_DES, B_DES, M_MD5, 0, 0, 0, },
 {0,CK(SSL_CK_RC4_128_EXPORT40_WITH_MD5),      S_RSA, K_RSA, C_RC4, B_40,  M_MD5, 0, 1, 0, },
 {0,CK(SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5),  S_RSA, K_RSA, C_RC2, B_40,  M_MD5, 0, 1, 0, }
--- a/security/nss/lib/ssl/sslsecur.c
+++ b/security/nss/lib/ssl/sslsecur.c
@@ -691,21 +691,21 @@ NSS_FindCertKEAType(CERTCertificate * ce
   switch (tag) {
   case SEC_OID_X500_RSA_ENCRYPTION:
   case SEC_OID_PKCS1_RSA_ENCRYPTION:
     keaType = kt_rsa;
     break;
   case SEC_OID_X942_DIFFIE_HELMAN_KEY:
     keaType = kt_dh;
     break;
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
   case SEC_OID_ANSIX962_EC_PUBLIC_KEY:
     keaType = kt_ecdh;
     break;
-#endif /* NSS_ENABLE_ECC */
+#endif /* NSS_DISABLE_ECC */
   default:
     keaType = kt_null;
   }
   
  loser:
   
   return keaType;
 }
--- a/security/nss/lib/ssl/sslt.h
+++ b/security/nss/lib/ssl/sslt.h
@@ -176,17 +176,17 @@ typedef enum {
     SSL_sni_type_total
 } SSLSniNameType;
 
 /* Supported extensions. */
 /* Update SSL_MAX_EXTENSIONS whenever a new extension type is added. */
 typedef enum {
     ssl_server_name_xtn              = 0,
     ssl_cert_status_xtn              = 5,
-#ifdef NSS_ENABLE_ECC
+#ifndef NSS_DISABLE_ECC
     ssl_elliptic_curves_xtn          = 10,
     ssl_ec_point_formats_xtn         = 11,
 #endif
     ssl_signature_algorithms_xtn     = 13,
     ssl_use_srtp_xtn                 = 14,
     ssl_app_layer_protocol_xtn       = 16,
     ssl_session_ticket_xtn           = 35,
     ssl_next_proto_nego_xtn          = 13172,
--- a/security/nss/tests/all.sh
+++ b/security/nss/tests/all.sh
@@ -54,17 +54,17 @@
 #
 # Optional environment variables to specify build to use:
 # -------------------------------------------------------
 #   BUILT_OPT    - use optimized/debug build 
 #   USE_64       - use 64bit/32bit build
 #
 # Optional environment variables to enable specific NSS features:
 # ---------------------------------------------------------------
-#   NSS_ENABLE_ECC              - enable ECC
+#   NSS_DISABLE_ECC             - disable ECC
 #   NSS_ECC_MORE_THAN_SUITE_B   - enable extended ECC
 #
 # Optional environment variables to select which cycles/suites to test:
 # ---------------------------------------------------------------------
 #   NSS_CYCLES     - list of cycles to run (separated by space 
 #                    character)
 #                  - by default all cycles are tested
 #
--- a/security/nss/tests/cert/cert.sh
+++ b/security/nss/tests/cert/cert.sh
@@ -41,17 +41,17 @@ cert_init()
       cd ../common
       . ./init.sh
   fi
   if [ -z "${IOPR_CERT_SOURCED}" ]; then
        . ../iopr/cert_iopr.sh
   fi
   SCRIPTNAME="cert.sh"
   CRL_GRP_DATE=`date -u "+%Y%m%d%H%M%SZ"`
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       html_head "Certutil and Crlutil Tests with ECC"
   else
       html_head "Certutil and Crlutil Tests"
   fi
 
   LIBDIR="${DIST}/${OBJDIR}/lib"
 
   ROOTCERTSFILE=`ls -1 ${LIBDIR}/*nssckbi* | head -1`
@@ -287,17 +287,17 @@ cert_create_cert()
 
     CU_ACTION="Import Root CA for $CERTNAME"
     certu -A -n "TestCA" -t "TC,TC,TC" -f "${R_PWFILE}" -d "${PROFILEDIR}" \
           -i "${R_CADIR}/TestCA.ca.cert" 2>&1
     if [ "$RET" -ne 0 ]; then
         return $RET
     fi
 
-    if [ -n "$NSS_ENABLE_ECC" ] ; then
+    if [ -z "$NSS_DISABLE_ECC" ] ; then
 	CU_ACTION="Import EC Root CA for $CERTNAME"
 	certu -A -n "TestCA-ec" -t "TC,TC,TC" -f "${R_PWFILE}" \
 	    -d "${PROFILEDIR}" -i "${R_CADIR}/TestCA-ec.ca.cert" 2>&1
 	if [ "$RET" -ne 0 ]; then
             return $RET
 	fi
     fi
 
@@ -335,17 +335,17 @@ cert_add_cert()
         return $RET
     fi
 
     cert_log "SUCCESS: $CERTNAME's Cert Created"
 
 #
 #   Generate and add EC cert
 #
-    if [ -n "$NSS_ENABLE_ECC" ] ; then
+    if [ -z "$NSS_DISABLE_ECC" ] ; then
 	CURVE="secp384r1"
 	CU_ACTION="Generate EC Cert Request for $CERTNAME"
 	CU_SUBJECT="CN=$CERTNAME, E=${CERTNAME}-ec@bogus.com, O=BOGUS NSS, L=Mountain View, ST=California, C=US"
 	certu -R -k ec -q "${CURVE}" -d "${PROFILEDIR}" -f "${R_PWFILE}" \
 	    -z "${R_NOISE_FILE}" -o req  2>&1
 	if [ "$RET" -ne 0 ]; then
             return $RET
 	fi
@@ -425,17 +425,17 @@ cert_all_CA()
     ALL_CU_SUBJECT="CN=NSS Chain2 Client Test CA, O=BOGUS NSS, L=Santa Clara, ST=California, C=US"
     cert_CA $CLIENT_CADIR chain-2-clientCA "-c chain-1-clientCA" "u,u,u" ${D_CLIENT_CA} "7"
 
     rm $CLIENT_CADIR/root.cert $SERVER_CADIR/root.cert
 
     # root.cert in $CLIENT_CADIR and in $SERVER_CADIR is one of the last 
     # in the chain
 
-    if [ -n "$NSS_ENABLE_ECC" ] ; then
+    if [ -z "$NSS_DISABLE_ECC" ] ; then
 #
 #       Create EC version of TestCA
 	CA_CURVE="secp521r1"
 	ALL_CU_SUBJECT="CN=NSS Test CA (ECC), O=BOGUS NSS, L=Mountain View, ST=California, C=US"
 	cert_ec_CA $CADIR TestCA-ec -x "CTu,CTu,CTu" ${D_CA} "1" ${CA_CURVE}
 #
 #       Create EC versions of the intermediate CA certs
 	ALL_CU_SUBJECT="CN=NSS Server Test CA (ECC), O=BOGUS NSS, L=Santa Clara, ST=California, C=US"
@@ -666,17 +666,17 @@ cert_smime_client()
   CU_ACTION="Import Eve's cert into Alice's DB"
   certu -E -t ",," -d ${P_R_ALICEDIR} -f ${R_PWFILE} \
         -i ${R_EVEDIR}/Eve.cert 2>&1
 
   CU_ACTION="Import Eve's cert into Bob's DB"
   certu -E -t ",," -d ${P_R_BOBDIR} -f ${R_PWFILE} \
         -i ${R_EVEDIR}/Eve.cert 2>&1
 
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       echo "$SCRIPTNAME: Importing EC Certificates =============================="
       CU_ACTION="Import Bob's EC cert into Alice's db"
       certu -E -t ",," -d ${P_R_ALICEDIR} -f ${R_PWFILE} \
           -i ${R_BOBDIR}/Bob-ec.cert 2>&1
 
       CU_ACTION="Import Dave's EC cert into Alice's DB"
       certu -E -t ",," -d ${P_R_ALICEDIR} -f ${R_PWFILE} \
           -i ${R_DAVEDIR}/Dave-ec.cert 2>&1
@@ -737,17 +737,17 @@ cert_extended_ssl()
   CU_ACTION="Import $CERTNAME's Cert  -t u,u,u (ext)"
   certu -A -n "$CERTNAME" -t "u,u,u" -d "${PROFILEDIR}" -f "${R_PWFILE}" \
         -i "${CERTNAME}.cert" 2>&1
 
   CU_ACTION="Import Client Root CA -t T,, for $CERTNAME (ext.)"
   certu -A -n "clientCA" -t "T,," -f "${R_PWFILE}" -d "${PROFILEDIR}" \
           -i "${CLIENT_CADIR}/clientCA.ca.cert" 2>&1
 
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
 #
 #     Repeat the above for EC certs
 #
       EC_CURVE="secp256r1"
       CU_ACTION="Generate EC Cert Request for $CERTNAME (ext)"
       CU_SUBJECT="CN=$CERTNAME, E=${CERTNAME}-ec@bogus.com, O=BOGUS NSS, L=Mountain View, ST=California, C=US"
       certu -R -d "${PROFILEDIR}" -k ec -q "${EC_CURVE}" -f "${R_PWFILE}" \
 	  -z "${R_NOISE_FILE}" -o req 2>&1
@@ -825,17 +825,17 @@ cert_extended_ssl()
 
   CU_ACTION="Import $CERTNAME's Cert -t u,u,u (ext)"
   certu -A -n "$CERTNAME" -t "u,u,u" -d "${PROFILEDIR}" -f "${R_PWFILE}" \
         -i "${CERTNAME}.cert" 2>&1
   CU_ACTION="Import Server Root CA -t C,C,C for $CERTNAME (ext.)"
   certu -A -n "serverCA" -t "C,C,C" -f "${R_PWFILE}" -d "${PROFILEDIR}" \
           -i "${SERVER_CADIR}/serverCA.ca.cert" 2>&1
 
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
 #
 #     Repeat the above for EC certs
 #
       CU_ACTION="Generate EC Cert Request for $CERTNAME (ext)"
       CU_SUBJECT="CN=$CERTNAME, E=${CERTNAME}-ec@bogus.com, O=BOGUS NSS, L=Mountain View, ST=California, C=US"
       certu -R -d "${PROFILEDIR}" -k ec -q "${EC_CURVE}" -f "${R_PWFILE}" \
 	  -z "${R_NOISE_FILE}" -o req 2>&1
 
@@ -915,17 +915,17 @@ cert_ssl()
   cert_create_cert ${SERVERDIR} "${HOSTADDR}" 100 ${D_SERVER}
   echo "$SCRIPTNAME: Creating Server CA Issued Certificate for \\"
   echo "             ${HOSTADDR}-sni --------------------------------"
   CERTSERIAL=101
   CERTNAME="${HOST}-sni${sniCertCount}.${DOMSUF}"
   cert_add_cert 
   CU_ACTION="Modify trust attributes of Root CA -t TC,TC,TC"
   certu -M -n "TestCA" -t "TC,TC,TC" -d ${PROFILEDIR} -f "${R_PWFILE}"
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       CU_ACTION="Modify trust attributes of EC Root CA -t TC,TC,TC"
       certu -M -n "TestCA-ec" -t "TC,TC,TC" -d ${PROFILEDIR} -f "${R_PWFILE}"
   fi
 #  cert_init_cert ${SERVERDIR} "${HOSTADDR}" 1 ${D_SERVER}
 #  echo "************* Copying CA files to ${SERVERDIR}"
 #  cp ${CADIR}/*.db .
 #  hw_acc
 #  CU_ACTION="Creating ${CERTNAME}'s Server Cert"
@@ -1023,17 +1023,17 @@ MODSCRIPT
 
 ############################## cert_eccurves ###########################
 # local shell function to create server certs for all EC curves
 ########################################################################
 cert_eccurves()
 {
   ################# Creating Certs for EC curves test ########################
   #
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
     echo "$SCRIPTNAME: Creating Server CA Issued Certificate for "
     echo "             EC Curves Test Certificates ------------------------------------"
 
     cert_init_cert "${ECCURVES_DIR}" "EC Curves Test Certificates" 1 ${D_ECCURVES}
 
     CU_ACTION="Initializing EC Curve's Cert DB"
     certu -N -d "${PROFILEDIR}" -f "${R_PWFILE}" 2>&1
 
@@ -1083,17 +1083,17 @@ cert_eccurves()
 	
 	if [ $RET -eq 0 ] ; then
 	  CU_ACTION="Import $CERTNAME's EC Cert"
 	  certu -A -n "${CERTNAME}-ec" -t "u,u,u" -d "${PROFILEDIR}" \
 		-f "${R_PWFILE}" -i "${CERTNAME}-ec.cert" 2>&1
 	fi
     done
 
-  fi # if NSS_ENABLE_ECC=1
+  fi # $NSS_DISABLE_ECC
 }
 
 ########################### cert_extensions_test #############################
 # local shell function to test cert extensions generation
 ##############################################################################
 cert_extensions_test()
 {
     COUNT=`expr ${COUNT} + 1`
@@ -1222,17 +1222,17 @@ addcert ${CRL_GRP_1_BEGIN}-${CRL_GRP_END
 addext reasonCode 0 4
 addext issuerAltNames 0 "rfc822Name:caemail@ca.com|dnsName:ca.com|directoryName:CN=NSS Test CA,O=BOGUS NSS,L=Mountain View,ST=California,C=US|URI:http://ca.com|ipAddress:192.168.0.1|registerID=reg CA"
 EOF_CRLINI
 # This extension should be added to the list, but currently nss has bug
 #addext authKeyId 0 "CN=NSS Test CA,O=BOGUS NSS,L=Mountain View,ST=California,C=US" 1
   CRL_GEN_RES=`expr $? + $CRL_GEN_RES`
   chmod 600 ${CRL_FILE_GRP_1}_or
 
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       CU_ACTION="Generating CRL (ECC) for range ${CRL_GRP_1_BEGIN}-${CRL_GRP_END} TestCA-ec authority"
 
 #     Until Bug 292285 is resolved, do not encode x400 Addresses. After
 #     the bug is resolved, reintroduce "x400Address:x400Address" within
 #     addext issuerAltNames ...
       crlu -q -d $CADIR -G -n "TestCA-ec" -f ${R_PWFILE} \
 	  -o ${CRL_FILE_GRP_1}_or-ec <<EOF_CRLINI
 update=$CRLUPDATE
@@ -1255,17 +1255,17 @@ EOF_CRLINI
   crlu -d $CADIR -M -n "TestCA" -f ${R_PWFILE} -o ${CRL_FILE_GRP_1}_or1 \
       -i ${CRL_FILE_GRP_1}_or <<EOF_CRLINI
 update=$CRLUPDATE
 addcert ${CRL_GRP_END} $CRL_GRP_DATE
 EOF_CRLINI
   CRL_GEN_RES=`expr $? + $CRL_GEN_RES`
   chmod 600 ${CRL_FILE_GRP_1}_or1
   TEMPFILES="$TEMPFILES ${CRL_FILE_GRP_1}_or"
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       CU_ACTION="Modify CRL (ECC) by adding one more cert"
       crlu -d $CADIR -M -n "TestCA-ec" -f ${R_PWFILE} \
 	  -o ${CRL_FILE_GRP_1}_or1-ec -i ${CRL_FILE_GRP_1}_or-ec <<EOF_CRLINI
 update=$CRLUPDATE
 addcert ${CRL_GRP_END} $CRL_GRP_DATE
 EOF_CRLINI
       CRL_GEN_RES=`expr $? + $CRL_GEN_RES`
       chmod 600 ${CRL_FILE_GRP_1}_or1-ec
@@ -1279,17 +1279,17 @@ EOF_CRLINI
   CRLUPDATE=`date -u "+%Y%m%d%H%M%SZ"`
   crlu -d $CADIR -M -n "TestCA" -f ${R_PWFILE} -o ${CRL_FILE_GRP_1} \
       -i ${CRL_FILE_GRP_1}_or1 <<EOF_CRLINI
 update=$CRLUPDATE
 rmcert  ${UNREVOKED_CERT_GRP_1}
 EOF_CRLINI
   chmod 600 ${CRL_FILE_GRP_1}
   TEMPFILES="$TEMPFILES ${CRL_FILE_GRP_1}_or1"
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       CU_ACTION="Modify CRL (ECC) by removing one cert"
       crlu -d $CADIR -M -n "TestCA-ec" -f ${R_PWFILE} -o ${CRL_FILE_GRP_1}-ec \
 	  -i ${CRL_FILE_GRP_1}_or1-ec <<EOF_CRLINI
 update=$CRLUPDATE
 rmcert  ${UNREVOKED_CERT_GRP_1}
 EOF_CRLINI
       chmod 600 ${CRL_FILE_GRP_1}-ec
       TEMPFILES="$TEMPFILES ${CRL_FILE_GRP_1}_or1-ec"
@@ -1308,17 +1308,17 @@ EOF_CRLINI
           -i ${CRL_FILE_GRP_1} <<EOF_CRLINI
 update=$CRLUPDATE
 addcert ${CRL_GRP_2_BEGIN}-${CRL_GRP_END} $CRL_GRP_DATE
 addext invalidityDate 0 $CRLUPDATE
 rmcert  ${UNREVOKED_CERT_GRP_2}
 EOF_CRLINI
   CRL_GEN_RES=`expr $? + $CRL_GEN_RES`
   chmod 600 ${CRL_FILE_GRP_2}
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       CU_ACTION="Creating CRL (ECC) for groups 1 and 2"
       crlu -d $CADIR -M -n "TestCA-ec" -f ${R_PWFILE} -o ${CRL_FILE_GRP_2}-ec \
           -i ${CRL_FILE_GRP_1}-ec <<EOF_CRLINI
 update=$CRLUPDATE
 addcert ${CRL_GRP_2_BEGIN}-${CRL_GRP_END} $CRL_GRP_DATE
 addext invalidityDate 0 $CRLUPDATE
 rmcert  ${UNREVOKED_CERT_GRP_2}
 EOF_CRLINI
@@ -1341,17 +1341,17 @@ EOF_CRLINI
             -i ${CRL_FILE_GRP_2} <<EOF_CRLINI
 update=$CRLUPDATE
 addcert ${CRL_GRP_3_BEGIN}-${CRL_GRP_END} $CRL_GRP_DATE
 rmcert  ${UNREVOKED_CERT_GRP_3}
 addext crlNumber 0 2
 EOF_CRLINI
   CRL_GEN_RES=`expr $? + $CRL_GEN_RES`
   chmod 600 ${CRL_FILE_GRP_3}
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       CU_ACTION="Creating CRL (ECC) for groups 1, 2 and 3"
       crlu -d $CADIR -M -n "TestCA-ec" -f ${R_PWFILE} -o ${CRL_FILE_GRP_3}-ec \
           -i ${CRL_FILE_GRP_2}-ec <<EOF_CRLINI
 update=$CRLUPDATE
 addcert ${CRL_GRP_3_BEGIN}-${CRL_GRP_END} $CRL_GRP_DATE
 rmcert  ${UNREVOKED_CERT_GRP_3}
 addext crlNumber 0 2
 EOF_CRLINI
@@ -1361,17 +1361,17 @@ EOF_CRLINI
 
   ############ Importing Server CA Issued CRL for certs of first group #######
 
   echo "$SCRIPTNAME: Importing Server CA Issued CRL for certs ${CRL_GRP_BEGIN} trough ${CRL_GRP_END}"
   CU_ACTION="Importing CRL for groups 1"
   crlu -D -n TestCA  -f "${R_PWFILE}" -d "${R_SERVERDIR}"
   crlu -I -i ${CRL_FILE} -n "TestCA" -f "${R_PWFILE}" -d "${R_SERVERDIR}"
   CRL_GEN_RES=`expr $? + $CRL_GEN_RES`
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       CU_ACTION="Importing CRL (ECC) for groups 1"
       crlu -D -n TestCA-ec  -f "${R_PWFILE}" -d "${R_SERVERDIR}"
       crlu -I -i ${CRL_FILE}-ec -n "TestCA-ec" -f "${R_PWFILE}" \
 	  -d "${R_SERVERDIR}"
       CRL_GEN_RES=`expr $? + $CRL_GEN_RES`
   fi
 
   if [ "$CERTFAILED" != 0 -o "$CRL_GEN_RES" != 0 ] ; then
--- a/security/nss/tests/remote/Makefile
+++ b/security/nss/tests/remote/Makefile
@@ -75,17 +75,17 @@ package_for_testing:
 	cat $(PCFG)                                  >> $(RTSH)
 	echo 'export NSS_TESTS=$(NSS_TESTS)'         >> $(RTSH)
 	echo 'export NSS_SSL_TESTS=$(NSS_SSL_TESTS)' >> $(RTSH)
 	echo 'export NSS_SSL_RUN=$(NSS_SSL_RUN)'     >> $(RTSH)
 	echo 'export NSS_CYCLES=$(NSS_CYCLES)'       >> $(RTSH)
 	echo 'export USE_64=$(USE_64)'               >> $(RTSH)
 	echo 'export BUILD_OPT=$(BUILD_OPT)'         >> $(RTSH)
 	echo 'export PKITS_DATA=$(PKITS_DATA)'       >> $(RTSH)
-	echo 'export NSS_ENABLE_ECC=$(NSS_ENABLE_ECC)'                       >> $(RTSH)
+	echo 'export NSS_DISABLE_ECC=$(NSS_DISABLE_ECC)'                     >> $(RTSH)
 	echo 'export NSS_ECC_MORE_THAN_SUITE_B=$(NSS_ECC_MORE_THAN_SUITE_B)' >> $(RTSH)
 	echo 'export NSPR_LOG_MODULES=$(NSPR_LOG_MODULES)'                   >> $(RTSH)
 ifeq ($(OS_TARGET),Android)
 	# Android doesn't support FIPS tests, because
 	# dladdr does not return a full path for implicitly loaded libraries
 	echo "export NSS_TEST_DISABLE_FIPS=1" >> $(DIST)/platform.cfg
 endif
 ifeq ($(CROSS_COMPILE),1)
--- a/security/nss/tests/smime/smime.sh
+++ b/security/nss/tests/smime/smime.sh
@@ -35,17 +35,17 @@ smime_init()
       . ./init.sh
   fi
   if [ ! -r $CERT_LOG_FILE ]; then  # we need certificates here
       cd ../cert
       . ./cert.sh
   fi
   SCRIPTNAME=smime.sh
 
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       html_head "S/MIME Tests with ECC"
   else
       html_head "S/MIME Tests"
   fi
 
   grep "SUCCESS: SMIME passed" $CERT_LOG_FILE >/dev/null || {
       Exit 11 "Fatal - S/MIME of cert.sh needs to pass first"
   }
@@ -80,17 +80,17 @@ smime_sign()
   ${PROFTOOL} ${BINDIR}/cmsutil -D -i alice.${SIG} -d ${P_R_BOBDIR} -o alice.data.${HASH}
   html_msg $? 0 "Decode Alice's Attached Signature (${HASH})" "."
 
   echo "diff alice.txt alice.data.${HASH}"
   diff alice.txt alice.data.${HASH}
   html_msg $? 0 "Compare Attached Signed Data and Original (${HASH})" "."
 
 # Test ECDSA signing for all hash algorithms.
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       echo "$SCRIPTNAME: Signing Detached Message ECDSA w/ {$HASH} ------------------"
       echo "cmsutil -S -T -N Alice-ec ${HASH_CMD} -i alice.txt -d ${P_R_ALICEDIR} -p nss -o alice-ec.d${SIG}"
       ${PROFTOOL} ${BINDIR}/cmsutil -S -T -N Alice-ec ${HASH_CMD} -i alice.txt -d ${P_R_ALICEDIR} -p nss -o alice-ec.d${SIG}
       html_msg $? 0 "Create Detached Signature Alice (ECDSA w/ ${HASH})" "."
 
       echo "cmsutil -D -i alice-ec.d${SIG} -c alice.txt -d ${P_R_BOBDIR} "
       ${PROFTOOL} ${BINDIR}/cmsutil -D -i alice-ec.d${SIG} -c alice.txt -d ${P_R_BOBDIR} 
       html_msg $? 0 "Verifying Alice's Detached Signature (ECDSA w/ ${HASH})" "."
--- a/security/nss/tests/ssl/ssl.sh
+++ b/security/nss/tests/ssl/ssl.sh
@@ -77,17 +77,17 @@ ssl_init()
 
   fileout=0 #FIXME, looks like all.sh tried to turn this on but actually didn't
   #fileout=1
   #verbose="-v" #FIXME - see where this is usefull
 
   USER_NICKNAME=TestUser
   NORM_EXT=""
 
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       ECC_STRING=" - with ECC"
   else
       ECC_STRING=""
   fi
 
   CSHORT="-c ABCDEF:003B:003C:003D:0041:0084:009Ccdefgijklmnvyz"
   CLONG="-c ABCDEF:C001:C002:C003:C004:C005:C006:C007:C008:C009:C00A:C00B:C00C:C00D:C00E:C00F:C010:C011:C012:C013:C014:C023:C027:C02B:C02F:003B:003C:003D:0041:0084:009Ccdefgijklmnvyz"
 
@@ -197,17 +197,17 @@ kill_selfserv()
 # also: wait until the server is up and running
 ########################################################################
 start_selfserv()
 {
   if [ -n "$testname" ] ; then
       echo "$SCRIPTNAME: $testname ----"
   fi
   sparam=`echo $sparam | sed -e 's;_; ;g'`
-  if [ -n "$NSS_ENABLE_ECC" ] && \
+  if [ -z "$NSS_DISABLE_ECC" ] && \
      [ -z "$NO_ECC_CERTS" -o "$NO_ECC_CERTS" != "1"  ] ; then
       ECC_OPTIONS="-e ${HOSTADDR}-ec"
   else
       ECC_OPTIONS=""
   fi
   if [ "$1" = "mixed" ]; then
       ECC_OPTIONS="-e ${HOSTADDR}-ecmixed"
   fi
@@ -253,17 +253,17 @@ start_selfserv()
 ############################## ssl_cov #################################
 # local shell function to perform SSL Cipher Coverage tests
 ########################################################################
 ssl_cov()
 {
   html_head "SSL Cipher Coverage $NORM_EXT - server $SERVER_MODE/client $CLIENT_MODE $ECC_STRING"
 
   testname=""
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       sparam="$CLONG"
   else
       sparam="$CSHORT"
   fi
 
   mixed=0
   start_selfserv # Launch the server
 
@@ -287,17 +287,17 @@ ssl_cov()
           # default in libssl but it is enabled by default in tstclnt; we want
           # to test the libssl default whenever possible.
           SSL2_FLAGS=
           VMIN="ssl3"
       fi
       
       if [ "$NORM_EXT" = "Extended Test" -a "${SSL2}" -eq 0 ] ; then
           echo "$SCRIPTNAME: skipping  $testname for $NORM_EXT"
-      elif [ "$ectype" = "ECC" -a -z "$NSS_ENABLE_ECC" ] ; then
+      elif [ "$ectype" = "ECC" -a -n "$NSS_DISABLE_ECC" ] ; then
           echo "$SCRIPTNAME: skipping  $testname (ECC only)"
       elif [ "$SERVER_MODE" = "fips" -o "$CLIENT_MODE" = "fips" ] && [ "$SSL2" -eq 0 -o "$EXP" -eq 0 ] ; then
           echo "$SCRIPTNAME: skipping  $testname (non-FIPS only)"
       elif [ "`echo $ectype | cut -b 1`" != "#" ] ; then
           echo "$SCRIPTNAME: running $testname ----------------------------"
           VMAX="ssl3"
           if [ "$testmax" = "TLS10" ]; then
               VMAX="tls1.0"
@@ -369,17 +369,17 @@ ssl_auth()
       [ -z "$ectype" ] && continue
       echo "${testname}" | grep "don't require client auth" > /dev/null
       CAUTH=$?
 
       if [ "${CLIENT_MODE}" = "fips" -a "${CAUTH}" -eq 0 ] ; then
           echo "$SCRIPTNAME: skipping  $testname (non-FIPS only)"
       elif [ "$ectype" = "SNI" -a "$NORM_EXT" = "Extended Test" ] ; then
           echo "$SCRIPTNAME: skipping  $testname for $NORM_EXT"
-      elif [ "$ectype" = "ECC" -a  -z "$NSS_ENABLE_ECC" ] ; then
+      elif [ "$ectype" = "ECC" -a  -n "$NSS_DISABLE_ECC" ] ; then
           echo "$SCRIPTNAME: skipping  $testname (ECC only)"
       elif [ "`echo $ectype | cut -b 1`" != "#" ]; then
           cparam=`echo $cparam | sed -e 's;_; ;g' -e "s/TestUser/$USER_NICKNAME/g" `
           if [ "$ectype" = "SNI" ]; then
               cparam=`echo $cparam | sed -e "s/Host/$HOST/g" -e "s/Dom/$DOMSUF/g" `
               sparam=`echo $sparam | sed -e "s/Host/$HOST/g" -e "s/Dom/$DOMSUF/g" `
           fi
           start_selfserv
@@ -552,17 +552,17 @@ ssl_stress()
       SSL2=$?
       echo "${testname}" | grep "client auth" > /dev/null
       CAUTH=$?
 
       if [ "${SSL2}" -eq 0 -a "$NORM_EXT" = "Extended Test" ] ; then
           echo "$SCRIPTNAME: skipping  $testname for $NORM_EXT"
       elif [ "$ectype" = "SNI" -a "$NORM_EXT" = "Extended Test" ] ; then
           echo "$SCRIPTNAME: skipping  $testname for $NORM_EXT"
-      elif [ "$ectype" = "ECC" -a  -z "$NSS_ENABLE_ECC" ] ; then
+      elif [ "$ectype" = "ECC" -a  -n "$NSS_DISABLE_ECC" ] ; then
           echo "$SCRIPTNAME: skipping  $testname (ECC only)"
       elif [ "${SERVER_MODE}" = "fips" -o "${CLIENT_MODE}" = "fips" ] && [ "${SSL2}" -eq 0 ] ; then
           echo "$SCRIPTNAME: skipping  $testname (non-FIPS only)"
       elif [ "${CLIENT_MODE}" = "fips" -a "${CAUTH}" -ne 0 ] ; then
           echo "$SCRIPTNAME: skipping  $testname (non-FIPS only)"
       elif [ "`echo $ectype | cut -b 1`" != "#" ]; then
           cparam=`echo $cparam | sed -e 's;_; ;g' -e "s/TestUser/$USER_NICKNAME/g" `
           if [ "$ectype" = "SNI" ]; then
@@ -618,17 +618,17 @@ ssl_crl_ssl()
   CRL_GROUP_BEGIN=$CRL_GRP_1_BEGIN
   CRL_GROUP_RANGE=$CRL_GRP_1_RANGE
   UNREVOKED_CERT=$UNREVOKED_CERT_GRP_1
 
   exec < ${SSLAUTH}
   while read ectype value sparam cparam testname
   do
     [ "$ectype" = "" ] && continue
-    if [ "$ectype" = "ECC" -a  -z "$NSS_ENABLE_ECC" ] ; then
+    if [ "$ectype" = "ECC" -a  -n "$NSS_DISABLE_ECC" ] ; then
         echo "$SCRIPTNAME: skipping $testname (ECC only)"
     elif [ "$ectype" = "SNI" ]; then
         continue
     elif [ "`echo $ectype | cut -b 1`" != "#" ]; then
 	servarg=`echo $sparam | awk '{r=split($0,a,"-r") - 1;print r;}'`
 	pwd=`echo $cparam | grep nss`
 	user=`echo $cparam | grep TestUser`
 	_cparam=$cparam
@@ -811,17 +811,17 @@ ssl_crl_cache()
   while [ $? -eq 0 -a -f ${SSLAUTH_TMP} ]
     do
     sparam=$SERV_ARG
     start_selfserv
     exec < ${SSLAUTH_TMP}
     while read ectype value sparam cparam testname
       do
       [ "$ectype" = "" ] && continue
-      if [ "$ectype" = "ECC" -a  -z "$NSS_ENABLE_ECC" ] ; then
+      if [ "$ectype" = "ECC" -a  -n "$NSS_DISABLE_ECC" ] ; then
         echo "$SCRIPTNAME: skipping  $testname (ECC only)"
       elif [ "$ectype" = "SNI" ]; then
           continue
       else
         servarg=`echo $sparam | awk '{r=split($0,a,"-r") - 1;print r;}'`
         pwd=`echo $cparam | grep nss`
         user=`echo $cparam | grep TestUser`
         _cparam=$cparam
--- a/security/nss/tests/tools/tools.sh
+++ b/security/nss/tests/tools/tools.sh
@@ -71,17 +71,17 @@ tools_init()
       . ./init.sh
   fi
   if [ ! -r $CERT_LOG_FILE ]; then  # we need certificates here
       cd ../cert
       . ./cert.sh
   fi
   SCRIPTNAME=tools.sh
 
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       html_head "Tools Tests with ECC"
   else
       html_head "Tools Tests"
   fi
 
   grep "SUCCESS: SMIME passed" $CERT_LOG_FILE >/dev/null || {
       Exit 15 "Fatal - S/MIME of cert.sh needs to pass first"
   }
@@ -367,17 +367,17 @@ tools_p12_export_with_null_ciphers()
 # Repeats the test with ECC if enabled.
 ########################################################################
 tools_p12_export_list_import_with_default_ciphers()
 {
   echo "$SCRIPTNAME: Exporting Alice's email cert & key - default ciphers"
   
   export_list_import "DEFAULT" "DEFAULT"
 
-  if [ -n "$NSS_ENABLE_ECC" ] ; then
+  if [ -z "$NSS_DISABLE_ECC" ] ; then
       echo "$SCRIPTNAME: Exporting Alice's email EC cert & key---------------"
       echo "pk12util -o Alice-ec.p12 -n \"Alice-ec\" -d ${P_R_ALICEDIR} -k ${R_PWFILE} \\"
       echo "         -w ${R_PWFILE}"
       ${BINDIR}/pk12util -o Alice-ec.p12 -n "Alice-ec" -d ${P_R_ALICEDIR} -k ${R_PWFILE} \
            -w ${R_PWFILE} 2>&1 
       ret=$?
       html_msg $ret 0 "Exporting Alice's email EC cert & key (pk12util -o)"
       check_tmpfile
--- a/testing/mochitest/runtestsb2g.py
+++ b/testing/mochitest/runtestsb2g.py
@@ -141,26 +141,21 @@ class B2GMochitest(MochitestUtilsMixin):
             status = self.runner.wait()
             if status is None:
                 # the runner has timed out
                 status = 124
         except KeyboardInterrupt:
             log.info("runtests.py | Received keyboard interrupt.\n");
             status = -1
         except:
-            # XXX Bug 937684
-            time.sleep(5)
             traceback.print_exc()
             log.error("Automation Error: Received unexpected exception while running application\n")
             self.runner.check_for_crashes()
             status = 1
 
-        # XXX Bug 937684
-        time.sleep(5)
-
         self.stopWebServer(options)
         self.stopWebSocketServer(options)
 
         log.info("runtestsb2g.py | Running tests: end.")
 
         if manifest is not None:
             self.cleanup(manifest, options)
         return status
--- a/testing/mozbase/mozprocess/mozprocess/processhandler.py
+++ b/testing/mozbase/mozprocess/mozprocess/processhandler.py
@@ -892,44 +892,46 @@ falling back to not using job objects fo
     @property
     def pid(self):
         return self.proc.pid
 
 
 ### default output handlers
 ### these should be callables that take the output line
 
-def print_output(line):
-    print line
-
 class StoreOutput(object):
     """accumulate stdout"""
 
     def __init__(self):
         self.output = []
 
     def __call__(self, line):
         self.output.append(line)
 
-class LogOutput(object):
+class StreamOutput(object):
+    """pass output to a stream and flush"""
+
+    def __init__(self, stream):
+        self.stream = stream
+
+    def __call__(self, line):
+        self.stream.write(line + '\n')
+        self.stream.flush()
+
+class LogOutput(StreamOutput):
     """pass output to a file"""
 
     def __init__(self, filename):
-        self.filename = filename
-        self.file = None
-
-    def __call__(self, line):
-        if self.file is None:
-            self.file = file(self.filename, 'a')
-        self.file.write(line + '\n')
-        self.file.flush()
+        self.file_obj = open(filename, 'a')
+        StreamOutput.__init__(self, self.file_obj)
 
     def __del__(self):
-        if self.file is not None:
-            self.file.close()
+        if self.file_obj is not None:
+            self.file_obj.close()
+
 
 ### front end class with the default handlers
 
 class ProcessHandler(ProcessHandlerMixin):
     """
     Convenience class for handling processes with default output handlers.
 
     If no processOutputLine keyword argument is specified, write all
@@ -939,28 +941,32 @@ class ProcessHandler(ProcessHandlerMixin
 
     If storeOutput==True, the output produced by the process will be saved
     as self.output.
 
     If logfile is not None, the output produced by the process will be
     appended to the given file.
     """
 
-    def __init__(self, cmd, logfile=None, storeOutput=True, **kwargs):
+    def __init__(self, cmd, logfile=None, stream=None,  storeOutput=True, **kwargs):
         kwargs.setdefault('processOutputLine', [])
         if callable(kwargs['processOutputLine']):
             kwargs['processOutputLine'] = [kwargs['processOutputLine']]
 
-        # Print to standard output only if no outputline provided
-        if not kwargs['processOutputLine']:
-            kwargs['processOutputLine'].append(print_output)
-
         if logfile:
             logoutput = LogOutput(logfile)
             kwargs['processOutputLine'].append(logoutput)
 
+        if stream:
+            streamoutput = StreamOutput(stream)
+            kwargs['processOutputLine'].append(streamoutput)
+
+        # Print to standard output only if no outputline provided
+        if not kwargs['processOutputLine']:
+            kwargs['processOutputLine'].append(StreamOutput(sys.stdout))
+
         self.output = None
         if storeOutput:
             storeoutput = StoreOutput()
             self.output = storeoutput.output
             kwargs['processOutputLine'].append(storeoutput)
 
         ProcessHandlerMixin.__init__(self, cmd, **kwargs)
--- a/testing/mozbase/mozprocess/tests/manifest.ini
+++ b/testing/mozbase/mozprocess/tests/manifest.ini
@@ -8,9 +8,9 @@ skip-if = (os == "win")
 [test_mozprocess.py]
 disabled = bug 877864
 [test_mozprocess_kill.py]
 [test_mozprocess_kill_broad_wait.py]
 disabled = bug 921632
 [test_mozprocess_misc.py]
 [test_mozprocess_poll.py]
 [test_mozprocess_wait.py]
-[test_mozprocess_nonewline.py]
+[test_mozprocess_output.py]
new file mode 100644
--- /dev/null
+++ b/testing/mozbase/mozprocess/tests/proccountfive.py
@@ -0,0 +1,2 @@
+for i in range(0, 5):
+    print i
deleted file mode 100644
--- a/testing/mozbase/mozprocess/tests/test_mozprocess_nonewline.py
+++ /dev/null
@@ -1,33 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import unittest
-import proctest
-from mozprocess import processhandler
-
-here = os.path.dirname(os.path.abspath(__file__))
-
-class ProcTestMisc(proctest.ProcTest):
-    """ Class to test misc operations """
-
-    def test_process_output_nonewline(self):
-        """
-        Process is started, outputs data with no newline
-        """
-        p = processhandler.ProcessHandler([self.python, "procnonewline.py"],
-                                          cwd=here)
-
-        p.run()
-        p.processOutput(timeout=5)
-        p.wait()
-
-        detected, output = proctest.check_for_process("procnonewline.py")
-        self.determine_status(detected,
-                              output,
-                              p.proc.returncode,
-                              p.didTimeout,
-                              False,
-                              ())
-
-if __name__ == '__main__':
-    unittest.main()
new file mode 100644
--- /dev/null
+++ b/testing/mozbase/mozprocess/tests/test_mozprocess_output.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+
+import io
+import os
+import unittest
+import proctest
+from mozprocess import processhandler
+
+here = os.path.dirname(os.path.abspath(__file__))
+
+class ProcTestOutput(proctest.ProcTest):
+    """ Class to test operations related to output handling """
+
+    def test_process_output_nonewline(self):
+        """
+        Process is started, outputs data with no newline
+        """
+        p = processhandler.ProcessHandler([self.python, "procnonewline.py"],
+                                          cwd=here)
+
+        p.run()
+        p.processOutput(timeout=5)
+        p.wait()
+
+        detected, output = proctest.check_for_process("procnonewline.py")
+        self.determine_status(detected,
+                              output,
+                              p.proc.returncode,
+                              p.didTimeout,
+                              False,
+                              ())
+
+    def test_stream_process_output(self):
+        """
+        Process output stream does not buffer
+        """
+        expected = '\n'.join([str(n) for n in range(0,10)])
+
+        stream = io.BytesIO()
+        buf = io.BufferedRandom(stream)
+
+        p = processhandler.ProcessHandler([self.python, "proccountfive.py"],
+                                          cwd=here,
+                                          stream=buf)
+
+        p.run()
+        p.wait()
+        for i in range(5, 10):
+            stream.write(str(i)+'\n')
+
+        buf.flush()
+        self.assertEquals(stream.getvalue().strip(), expected)
+
+        # make sure mozprocess doesn't close the stream
+        # since mozprocess didn't create it
+        self.assertFalse(buf.closed)
+        buf.close()
+
+        detected, output = proctest.check_for_process("proccountfive.py")
+        self.determine_status(detected,
+                              output,
+                              p.proc.returncode,
+                              p.didTimeout,
+                              False,
+                              ())
+
+if __name__ == '__main__':
+    unittest.main()
--- a/testing/mozbase/mozrunner/mozrunner/remote.py
+++ b/testing/mozbase/mozrunner/mozrunner/remote.py
@@ -1,20 +1,20 @@
 # This Source Code Form is subject to the terms of the Mozilla Public
 # License, v. 2.0. If a copy of the MPL was not distributed with this file,
 # You can obtain one at http://mozilla.org/MPL/2.0/.
 
 import ConfigParser
 import os
 import posixpath
 import re
-import shutil
 import signal
 from StringIO import StringIO
 import subprocess
+import sys
 import tempfile
 import time
 
 from mozdevice import DMError
 import mozfile
 import mozlog
 
 from .base import Runner
@@ -148,18 +148,19 @@ class B2GRunner(RemoteRunner):
             self._reboot_device()
             #wait for wlan to come up
             if not self._wait_for_net():
                 raise Exception("network did not come up, please configure the network" +
                                 " prior to running before running the automation framework")
 
         self.dm.shellCheckOutput(['stop', 'b2g'])
 
-        self.kp_kwargs['processOutputLine'] = [self.on_output]
-        self.kp_kwargs['onTimeout'] = [self.on_timeout]
+        self.kp_kwargs.update({'stream': sys.stdout,
+                               'processOutputLine': self.on_output,
+                               'onTimeout': self.on_timeout,})
         self.process_handler = self.process_class(self.command, **self.kp_kwargs)
         self.process_handler.run(timeout=timeout, outputTimeout=outputTimeout)
 
         # Set up port forwarding again for Marionette, since any that
         # existed previously got wiped out by the reboot.
         if not self.marionette.emulator:
             subprocess.Popen([self.dm._adbPath,
                               'forward',
@@ -197,17 +198,16 @@ class B2GRunner(RemoteRunner):
                 script.close()
             elif isinstance(self.test_script, basestring):
                 self.marionette.execute_script(self.test_script, script_args=self.test_script_args)
         else:
             # assumes the tests are started on startup automatically
             pass
 
     def on_output(self, line):
-        print line
         match = re.findall(r"TEST-START \| ([^\s]*)", line)
         if match:
             self.last_test = match[-1]
 
     def on_timeout(self):
         self.dm.killProcess('/system/b2g/b2g', sig=signal.SIGABRT)
 
         msg = "%s | application timed out after %s seconds"
--- a/toolkit/components/places/tests/cpp/mock_Link.h
+++ b/toolkit/components/places/tests/cpp/mock_Link.h
@@ -118,19 +118,19 @@ Link::SizeOfExcludingThis(mozilla::Mallo
 
 void
 Link::URLSearchParamsUpdated()
 {
   NS_NOTREACHED("Unexpected call to Link::URLSearchParamsUpdated");
 }
 
 void
-Link::URLSearchParamsNeedsUpdates()
+Link::UpdateURLSearchParams()
 {
-  NS_NOTREACHED("Unexpected call to Link::URLSearchParamsNeedsUpdates");
+  NS_NOTREACHED("Unexpected call to Link::UpdateURLSearchParams");
 }
 
 NS_IMPL_CYCLE_COLLECTION_CLASS(URLSearchParams)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(URLSearchParams)
 NS_IMPL_CYCLE_COLLECTION_UNLINK_END
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(URLSearchParams)
 NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
 NS_IMPL_CYCLE_COLLECTION_TRACE_WRAPPERCACHE(URLSearchParams)
@@ -154,29 +154,30 @@ URLSearchParams::~URLSearchParams()
 
 JSObject*
 URLSearchParams::WrapObject(JSContext* aCx, JS::Handle<JSObject*> aScope)
 {
   return nullptr;
 }
 
 void
-URLSearchParams::ParseInput(const nsACString& aInput)
+URLSearchParams::ParseInput(const nsACString& aInput,
+                            URLSearchParamsObserver* aObserver)
 {
   NS_NOTREACHED("Unexpected call to URLSearchParams::ParseInput");
 }
 
 void
-URLSearchParams::CopyFromURLSearchParams(URLSearchParams& aSearchParams)
+URLSearchParams::AddObserver(URLSearchParamsObserver* aObserver)
 {
-  NS_NOTREACHED("Unexpected call to URLSearchParams::CopyFromURLSearchParams");
+  NS_NOTREACHED("Unexpected call to URLSearchParams::SetObserver");
 }
 
 void
-URLSearchParams::SetObserver(URLSearchParamsObserver* aObserver)
+URLSearchParams::RemoveObserver(URLSearchParamsObserver* aObserver)
 {
   NS_NOTREACHED("Unexpected call to URLSearchParams::SetObserver");
 }
 
 void
 URLSearchParams::Serialize(nsAString& aValue) const
 {
   NS_NOTREACHED("Unexpected call to URLSearchParams::Serialize");
@@ -227,24 +228,17 @@ URLSearchParams::Delete(const nsAString&
 
 void
 URLSearchParams::DeleteAll()
 {
   NS_NOTREACHED("Unexpected call to URLSearchParams::DeleteAll");
 }
 
 void
-URLSearchParams::NotifyObserver()
+URLSearchParams::NotifyObservers(URLSearchParamsObserver* aExceptObserver)
 {
-  NS_NOTREACHED("Unexpected call to URLSearchParams::NotifyObserver");
+  NS_NOTREACHED("Unexpected call to URLSearchParams::NotifyObservers");
 }
 
-void
-URLSearchParams::Invalidate()
-{
-  NS_NOTREACHED("Unexpected call to URLSearchParams::Invalidate");
-}
-
-
 } // namespace dom
 } // namespace mozilla
 
 #endif // mock_Link_h__
--- a/toolkit/library/dependentlibs.py
+++ b/toolkit/library/dependentlibs.py
@@ -101,17 +101,17 @@ def dependentlibs(lib, libpaths, func):
             continue
         for dir in libpaths:
             deppath = os.path.join(dir, dep)
             if os.path.exists(deppath):
                 deps.extend([d for d in dependentlibs(deppath, libpaths, func) if not d in deps])
                 # Black list the ICU data DLL because preloading it at startup
                 # leads to startup performance problems because of its excessive
                 # size (around 10MB).
-                if not dep.startswith("icudt"):
+                if not dep.startswith("icu"):
                     deps.append(dep)
                 break
 
     return deps
 
 def main():
     parser = OptionParser()
     parser.add_option("-L", dest="libpaths", action="append", metavar="PATH", help="Add the given path to the library search path")
--- a/tools/profiler/ProfilerMarkers.cpp
+++ b/tools/profiler/ProfilerMarkers.cpp
@@ -138,8 +138,13 @@ IOMarkerPayload::preparePayloadImp(Build
   return data;
 }
 
 template JSCustomObjectBuilder::Object
 IOMarkerPayload::preparePayloadImp<JSCustomObjectBuilder>(JSCustomObjectBuilder& b);
 template JSObjectBuilder::Object
 IOMarkerPayload::preparePayloadImp<JSObjectBuilder>(JSObjectBuilder& b);
 
+void
+ProfilerJSEventMarker(const char *event)
+{
+    PROFILER_MARKER(event);
+}
--- a/tools/profiler/PseudoStack.h
+++ b/tools/profiler/PseudoStack.h
@@ -287,16 +287,19 @@ public:
     return &mPendingUWTBuffers;
   }
 
 private:
   UWTBufferLinkedList mPendingUWTBuffers;
   volatile bool       mSignalLock;
 };
 
+// Stub eventMarker function for js-engine event generation.
+void ProfilerJSEventMarker(const char *event);
+
 // the PseudoStack members are read by signal
 // handlers, so the mutation of them needs to be signal-safe.
 struct PseudoStack
 {
 public:
   PseudoStack()
     : mStackPointer(0)
     , mRuntime(nullptr)
@@ -393,16 +396,17 @@ public:
                                  (uint32_t*) &mStackPointer,
                                  uint32_t(mozilla::ArrayLength(mStack)));
     if (mStartJSSampling)
       enableJSSampling();
   }
   void enableJSSampling() {
     if (mRuntime) {
       js::EnableRuntimeProfilingStack(mRuntime, true);
+      js::RegisterRuntimeProfilingEventMarker(mRuntime, &ProfilerJSEventMarker);
       mStartJSSampling = false;
     } else {
       mStartJSSampling = true;
     }
   }
   void jsOperationCallback() {
     if (mStartJSSampling)
       enableJSSampling();
--- a/widget/windows/winrt/FrameworkView.cpp
+++ b/widget/windows/winrt/FrameworkView.cpp
@@ -364,17 +364,19 @@ FrameworkView::SetWidget(MetroWidget* aW
 void
 FrameworkView::SendActivationEvent() 
 {
   if (mShuttingDown) {
     return;
   }
   NS_ASSERTION(mWindow, "SetWindow must be called before SendActivationEvent!");
   mWidget->Activated(mWinActiveState);
-  UpdateWidgetSizeAndPosition();
+  if (mWinActiveState) {
+    UpdateWidgetSizeAndPosition();
+  }
   EnsureAutomationProviderCreated();
 }
 
 HRESULT
 FrameworkView::OnWindowVisibilityChanged(ICoreWindow* aWindow,
                                          IVisibilityChangedEventArgs* aArgs)
 {
   // If we're visible, or we can't determine if we're visible, just store
--- a/widget/windows/winrt/MetroWidget.cpp
+++ b/widget/windows/winrt/MetroWidget.cpp
@@ -793,28 +793,16 @@ MetroWidget::WindowProcedure(HWND aWnd, 
   }
 
   nsTextStore::ProcessMessage(this, aMsg, aWParam, aLParam, msgResult);
   if (msgResult.mConsumed) {
     return processResult;
   }
 
   switch (aMsg) {
-    case WM_PAINT:
-    {
-      HRGN rgn = CreateRectRgn(0, 0, 0, 0);
-      GetUpdateRgn(mWnd, rgn, false);
-      nsIntRegion region = WinUtils::ConvertHRGNToRegion(rgn);
-      DeleteObject(rgn);
-      if (region.IsEmpty())
-        break;
-      Paint(region);
-      break;
-    }
-
     case WM_POWERBROADCAST:
     {
       switch (aWParam)
       {
         case PBT_APMSUSPEND:
           MetroApp::PostSleepWakeNotification(true);
           break;
         case PBT_APMRESUMEAUTOMATIC: