Backout 2838ba825479, 991404facac2, 7f6e22f10b99, 30a4e0cf7130, ad2c42efbe57, and 1f07f04ec01d (Bug 760067, Bug 767096, Bug 765158, Bug 729182) due to xpcshell orange.
authorRyan VanderMeulen <ryanvm@gmail.com>
Tue, 10 Jul 2012 19:21:54 -0400
changeset 103693 981ac887f6e209bf14c8eb7a40cb770010641539
parent 103692 af7b12206c01ace146fd1329ccb822097e473ba4
child 103694 a22d693c1ea16e5f4b87d981c41a3c5a0ea30cb8
push idunknown
push userunknown
push dateunknown
bugs760067, 767096, 765158, 729182
milestone16.0a1
backs out2838ba825479dc2022170933ae23750422c359b8
Backout 2838ba825479, 991404facac2, 7f6e22f10b99, 30a4e0cf7130, ad2c42efbe57, and 1f07f04ec01d (Bug 760067, Bug 767096, Bug 765158, Bug 729182) due to xpcshell orange.
docshell/base/nsDocShell.cpp
netwerk/base/public/nsIApplicationCache.idl
netwerk/base/public/nsIApplicationCacheChannel.idl
netwerk/base/public/nsICachingChannel.idl
netwerk/base/src/nsSocketTransport2.cpp
netwerk/cache/nsCacheService.cpp
netwerk/cache/nsCacheService.h
netwerk/cache/nsDiskCacheDeviceSQL.cpp
netwerk/cache/nsDiskCacheDeviceSQL.h
netwerk/dns/nsDNSService2.cpp
netwerk/dns/nsHostResolver.cpp
netwerk/protocol/http/HttpChannelChild.cpp
netwerk/protocol/http/nsHttpChannel.cpp
netwerk/protocol/http/nsHttpChannel.h
netwerk/protocol/http/nsHttpConnectionMgr.cpp
netwerk/protocol/http/nsHttpTransaction.cpp
netwerk/test/unit/test_offlinecache_custom-directory.js
uriloader/prefetch/nsOfflineCacheUpdate.cpp
uriloader/prefetch/nsOfflineCacheUpdate.h
xpcom/base/VisualEventTracer.cpp
xpcom/build/nsXPComInit.cpp
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -73,17 +73,16 @@
 #include "nsIPrivacyTransitionObserver.h"
 #include "nsCPrefetchService.h"
 #include "nsJSON.h"
 #include "IHistory.h"
 #include "mozilla/Services.h"
 #include "mozilla/Preferences.h"
 #include "mozilla/Telemetry.h"
 #include "mozilla/AutoRestore.h"
-#include "mozilla/VisualEventTracer.h"
 
 // we want to explore making the document own the load group
 // so we can associate the document URI with the load group.
 // until this point, we have an evil hack:
 #include "nsIHttpChannelInternal.h"  
 
 
 // Local Includes
@@ -6232,18 +6231,16 @@ nsDocShell::OnSecurityChange(nsIWebProgr
 
 nsresult
 nsDocShell::EndPageLoad(nsIWebProgress * aProgress,
                         nsIChannel * aChannel, nsresult aStatus)
 {
     if(!aChannel)
         return NS_ERROR_NULL_POINTER;
     
-    MOZ_EVENT_TRACER_DONE(this, "Page load");
-
     nsCOMPtr<nsIURI> url;
     nsresult rv = aChannel->GetURI(getter_AddRefs(url));
     if (NS_FAILED(rv)) return rv;
 
     nsCOMPtr<nsITimedChannel> timingChannel =
         do_QueryInterface(aChannel);
     if (timingChannel) {
         TimeStamp channelCreationTime;
@@ -8915,23 +8912,16 @@ nsDocShell::DoURILoad(nsIURI * aURI,
                       nsIInputStream * aHeadersData,
                       bool aFirstParty,
                       nsIDocShell ** aDocShell,
                       nsIRequest ** aRequest,
                       bool aIsNewWindowTarget,
                       bool aBypassClassifier,
                       bool aForceAllowCookies)
 {
-#ifdef MOZ_VISUAL_EVENT_TRACER
-    nsCAutoString urlSpec;
-    aURI->GetAsciiSpec(urlSpec);
-    MOZ_EVENT_TRACER_NAME_OBJECT(this, urlSpec.BeginReading());
-    MOZ_EVENT_TRACER_EXEC(this, "Page load");
-#endif
-
     nsresult rv;
     nsCOMPtr<nsIURILoader> uriLoader;
 
     uriLoader = do_GetService(NS_URI_LOADER_CONTRACTID, &rv);
     if (NS_FAILED(rv)) return rv;
 
     nsLoadFlags loadFlags = nsIRequest::LOAD_NORMAL;
     if (aFirstParty) {
--- a/netwerk/base/public/nsIApplicationCache.idl
+++ b/netwerk/base/public/nsIApplicationCache.idl
@@ -74,17 +74,17 @@ interface nsIApplicationCacheNamespace :
  * types, as discussed in the WHAT-WG offline applications
  * specification.
  *
  * All application caches with the same group ID belong to a cache
  * group.  Each group has one "active" cache that will service future
  * loads.  Inactive caches will be removed from the cache when they are
  * no longer referenced.
  */
-[scriptable, uuid(C3A17414-763B-4235-8BB7-B48324F95DF8)]
+[scriptable, uuid(231e1e53-05c1-41b6-b9de-dbbcce9385c9)]
 interface nsIApplicationCache : nsISupports
 {
     /**
      * Init this application cache instance to just hold the group ID and
      * the client ID to work just as a handle to the real cache. Used on
      * content process to simplify the application cache code.
      */
     void initAsHandle(in ACString groupId, in ACString clientId);
@@ -190,10 +190,10 @@ interface nsIApplicationCache : nsISuppo
      * Get the most specific namespace matching a given key.
      */
     nsIApplicationCacheNamespace getMatchingNamespace(in ACString key);
 
     /**
      * If set, this offline cache is placed in a different directory
      * than the current application profile.
      */
-    readonly attribute nsIFile profileDirectory;
+    readonly attribute nsIFile cacheDirectory;
 };
--- a/netwerk/base/public/nsIApplicationCacheChannel.idl
+++ b/netwerk/base/public/nsIApplicationCacheChannel.idl
@@ -5,17 +5,17 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 #include "nsIApplicationCacheContainer.idl"
 
 /**
  * Interface implemented by channels that support application caches.
  */
-[scriptable, uuid(6FA816B1-6D5F-4380-9704-054D0908CFA3)]
+[scriptable, uuid(8d9024e6-ab01-442d-8119-2f55d55d91b0)]
 interface nsIApplicationCacheChannel : nsIApplicationCacheContainer
 {
     /**
      * TRUE when the resource came from the application cache. This
      * might be false even there is assigned an application cache
      * e.g. in case of fallback of load of an entry matching bypass
      * namespace.
      */
@@ -44,15 +44,9 @@ interface nsIApplicationCacheChannel : n
     attribute boolean chooseApplicationCache;
 
     /**
      * A shortcut method to mark the cache item of this channel as 'foreign'.
      * See the 'cache selection algorithm' and CACHE_SELECTION_RELOAD
      * action handling in nsContentSink.
      */
     void markOfflineCacheEntryAsForeign();
-
-    /**
-     * Set offline application cache object to instruct the channel
-     * to cache for offline use using this application cache.
-     */
-    attribute nsIApplicationCache applicationCacheForWrite;
 };
--- a/netwerk/base/public/nsICachingChannel.idl
+++ b/netwerk/base/public/nsICachingChannel.idl
@@ -12,17 +12,17 @@ interface nsIFile;
  * to affect its behavior with respect to how it uses the cache service.
  *
  * This interface provides:
  *   1) Support for "stream as file" semantics (for JAR and plugins).
  *   2) Support for "pinning" cached data in the cache (for printing and save-as).
  *   3) Support for uniquely identifying cached data in cases when the URL
  *      is insufficient (e.g., HTTP form submission).
  */
-[scriptable, uuid(8456EBEE-7127-485b-9518-C2E328C09F5D)]
+[scriptable, uuid(E2143B61-62FE-4da5-BE2E-E31981095889)]
 interface nsICachingChannel : nsICacheInfoChannel
 {
     /**
      * Set/get the cache token... uniquely identifies the data in the cache.
      * Holding a reference to this token prevents the cached data from being
      * removed.
      * 
      * A cache token retrieved from a particular instance of nsICachingChannel
@@ -69,16 +69,36 @@ interface nsICachingChannel : nsICacheIn
      * may fail if the disk cache is not present.  The value of this attribute
      * is usually only settable during the processing of a channel's
      * OnStartRequest.  The default value of this attribute depends on the
      * particular implementation of nsICachingChannel.
      */
     attribute boolean cacheAsFile;
 
     /**
+     * Specifies whether or not the data should be placed in the offline cache,
+     * in addition to normal memory/disk caching.  This may fail if the offline
+     * cache is not present.  The value of this attribute should be set before
+     * opening the channel.
+     */
+    attribute boolean cacheForOfflineUse;
+
+    /**
+     * The session into which to cache offline data.  If not specified,
+     * data will be placed in "HTTP-offline"
+     */
+    attribute ACString offlineCacheClientID;
+
+    /**
+     * Override base (profile) directory to work with when accessing the cache.
+     * When not specified, the current process' profile directory will be used.
+     */
+    attribute nsIFile profileDirectory;
+
+    /**
      * Get the "file" where the cached data can be found.  This is valid for
      * as long as a reference to the cache token is held.  This may return
      * an error if cacheAsFile is false.
      */
     readonly attribute nsIFile cacheFile;
 
     /**************************************************************************
      * Caching channel specific load flags:
--- a/netwerk/base/src/nsSocketTransport2.cpp
+++ b/netwerk/base/src/nsSocketTransport2.cpp
@@ -29,18 +29,16 @@
 #include "nsISocketProviderService.h"
 #include "nsISocketProvider.h"
 #include "nsISSLSocketControl.h"
 #include "nsINSSErrorsService.h"
 #include "nsIPipe.h"
 #include "nsIProgrammingLanguage.h"
 #include "nsIClassInfoImpl.h"
 
-#include "mozilla/VisualEventTracer.h"
-
 #if defined(XP_WIN) || defined(MOZ_PLATFORM_MAEMO)
 #include "nsNativeConnectionHelper.h"
 #endif
 
 using namespace mozilla;
 
 //-----------------------------------------------------------------------------
 
@@ -722,18 +720,16 @@ nsSocketTransport::~nsSocketTransport()
     NS_RELEASE(serv); // nulls argument
 }
 
 nsresult
 nsSocketTransport::Init(const char **types, PRUint32 typeCount,
                         const nsACString &host, PRUint16 port,
                         nsIProxyInfo *givenProxyInfo)
 {
-    MOZ_EVENT_TRACER_NAME_OBJECT(this, host.BeginReading());
-
     nsCOMPtr<nsProxyInfo> proxyInfo;
     if (givenProxyInfo) {
         proxyInfo = do_QueryInterface(givenProxyInfo);
         NS_ENSURE_ARG(proxyInfo);
     }
 
     // init socket type info
 
@@ -1154,17 +1150,16 @@ nsSocketTransport::InitiateSocket()
         PR_NetAddrToString(&mNetAddr, buf, sizeof(buf));
         SOCKET_LOG(("  trying address: %s\n", buf));
     }
 #endif
 
     // 
     // Initiate the connect() to the host...  
     //
-    MOZ_EVENT_TRACER_EXEC(this, "TCP connect");
     status = PR_Connect(fd, &mNetAddr, NS_SOCKET_CONNECT_TIMEOUT);
     if (status == PR_SUCCESS) {
         // 
         // we are connected!
         //
         OnSocketConnected();
     }
     else {
@@ -1379,18 +1374,16 @@ nsSocketTransport::OnSocketConnected()
     // to trample over mFDref if mFD is already set.
     {
         MutexAutoLock lock(mLock);
         NS_ASSERTION(mFD, "no socket");
         NS_ASSERTION(mFDref == 1, "wrong socket ref count");
         mFDconnected = true;
     }
 
-    MOZ_EVENT_TRACER_DONE(this, "TCP connect");
-
     SendStatus(STATUS_CONNECTED_TO);
 }
 
 PRFileDesc *
 nsSocketTransport::GetFD_Locked()
 {
     // mFD is not available to the streams while disconnected.
     if (!mFDconnected)
@@ -2003,17 +1996,16 @@ nsSocketTransport::GetQoSBits(PRUint8 *a
 NS_IMETHODIMP
 nsSocketTransport::OnLookupComplete(nsICancelable *request,
                                     nsIDNSRecord  *rec,
                                     nsresult       status)
 {
     // flag host lookup complete for the benefit of the ResolveHost method.
     mResolving = false;
 
-    MOZ_EVENT_TRACER_WAIT(this, "TCP connect");
     nsresult rv = PostEvent(MSG_DNS_LOOKUP_COMPLETE, status, rec);
 
     // if posting a message fails, then we should assume that the socket
     // transport has been shutdown.  this should never happen!  if it does
     // it means that the socket transport service was shutdown before the
     // DNS service.
     if (NS_FAILED(rv))
         NS_WARNING("unable to post DNS lookup complete message");
--- a/netwerk/cache/nsCacheService.cpp
+++ b/netwerk/cache/nsCacheService.cpp
@@ -1583,17 +1583,16 @@ nsCacheService::GetCustomOfflineDevice(n
     nsAutoString profilePath;
     rv = aProfileDir->GetPath(profilePath);
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!mCustomOfflineDevices.Get(profilePath, aDevice)) {
         rv = CreateCustomOfflineDevice(aProfileDir, aQuota, aDevice);
         NS_ENSURE_SUCCESS(rv, rv);
 
-        (*aDevice)->SetAutoShutdown();
         mCustomOfflineDevices.Put(profilePath, *aDevice);
     }
 
     return NS_OK;
 }
 
 nsresult
 nsCacheService::CreateOfflineDevice()
@@ -1672,30 +1671,16 @@ nsCacheService::CreateMemoryDevice()
 
     MemoryCacheReporter =
         new NS_MEMORY_REPORTER_NAME(NetworkMemoryCache);
     NS_RegisterMemoryReporter(MemoryCacheReporter);
 
     return rv;
 }
 
-nsresult
-nsCacheService::RemoveCustomOfflineDevice(nsOfflineCacheDevice *aDevice)
-{
-    nsCOMPtr<nsIFile> profileDir = aDevice->BaseDirectory();
-    if (!profileDir)
-        return NS_ERROR_UNEXPECTED;
-
-    nsAutoString profilePath;
-    nsresult rv = profileDir->GetPath(profilePath);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    mCustomOfflineDevices.Remove(profilePath);
-    return NS_OK;
-}
 
 nsresult
 nsCacheService::CreateRequest(nsCacheSession *   session,
                               const nsACString & clientKey,
                               nsCacheAccessMode  accessRequested,
                               bool               blockingMode,
                               nsICacheListener * listener,
                               nsCacheRequest **  request)
--- a/netwerk/cache/nsCacheService.h
+++ b/netwerk/cache/nsCacheService.h
@@ -194,18 +194,16 @@ private:
 
     nsresult         CreateDiskDevice();
     nsresult         CreateOfflineDevice();
     nsresult         CreateCustomOfflineDevice(nsIFile *aProfileDir,
                                                PRInt32 aQuota,
                                                nsOfflineCacheDevice **aDevice);
     nsresult         CreateMemoryDevice();
 
-    nsresult         RemoveCustomOfflineDevice(nsOfflineCacheDevice *aDevice);
-
     nsresult         CreateRequest(nsCacheSession *   session,
                                    const nsACString & clientKey,
                                    nsCacheAccessMode  accessRequested,
                                    bool               blockingMode,
                                    nsICacheListener * listener,
                                    nsCacheRequest **  request);
 
     nsresult         DoomEntry_Internal(nsCacheEntry * entry,
--- a/netwerk/cache/nsDiskCacheDeviceSQL.cpp
+++ b/netwerk/cache/nsDiskCacheDeviceSQL.cpp
@@ -626,17 +626,17 @@ nsApplicationCache::GetGroupID(nsACStrin
 NS_IMETHODIMP
 nsApplicationCache::GetClientID(nsACString &out)
 {
   out = mClientID;
   return NS_OK;
 }
 
 NS_IMETHODIMP
-nsApplicationCache::GetProfileDirectory(nsIFile **out)
+nsApplicationCache::GetCacheDirectory(nsIFile **out)
 {
   if (mDevice->BaseDirectory())
       NS_ADDREF(*out = mDevice->BaseDirectory());
   else
       *out = nsnull;
 
   return NS_OK;
 }
@@ -652,42 +652,33 @@ nsApplicationCache::GetActive(bool *out)
 
 NS_IMETHODIMP
 nsApplicationCache::Activate()
 {
   NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
   NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);
 
   mDevice->ActivateCache(mGroup, mClientID);
-
-  if (mDevice->AutoShutdown(this))
-    mDevice = nsnull;
-
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsApplicationCache::Discard()
 {
   NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
   NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);
 
   mValid = false;
 
   if (mDevice->IsActiveCache(mGroup, mClientID))
   {
     mDevice->DeactivateGroup(mGroup);
   }
 
-  nsresult rv = mDevice->EvictEntries(mClientID.get());
-
-  if (mDevice->AutoShutdown(this))
-    mDevice = nsnull;
-
-  return rv;
+  return mDevice->EvictEntries(mClientID.get());
 }
 
 NS_IMETHODIMP
 nsApplicationCache::MarkEntry(const nsACString &key,
                               PRUint32 typeBits)
 {
   NS_ENSURE_TRUE(mValid, NS_ERROR_NOT_AVAILABLE);
   NS_ENSURE_TRUE(mDevice, NS_ERROR_NOT_AVAILABLE);
@@ -808,17 +799,16 @@ private:
  */
 
 NS_IMPL_THREADSAFE_ISUPPORTS0(nsOfflineCacheDevice)
 
 nsOfflineCacheDevice::nsOfflineCacheDevice()
   : mDB(nsnull)
   , mCacheCapacity(0)
   , mDeltaCounter(0)
-  , mAutoShutdown(false)
 {
 }
 
 /* static */
 bool
 nsOfflineCacheDevice::GetStrictFileOriginPolicy()
 {
     nsCOMPtr<nsIPrefBranch> prefs = do_GetService(NS_PREFSERVICE_CONTRACTID);
@@ -2397,28 +2387,8 @@ nsOfflineCacheDevice::SetCacheParentDire
   mCacheDirectory = do_QueryInterface(dir);
 }
 
 void
 nsOfflineCacheDevice::SetCapacity(PRUint32 capacity)
 {
   mCacheCapacity = capacity * 1024;
 }
-
-bool
-nsOfflineCacheDevice::AutoShutdown(nsIApplicationCache * aAppCache)
-{
-  if (!mAutoShutdown)
-    return false;
-
-  mAutoShutdown = false;
-
-  Shutdown();
-
-  nsRefPtr<nsCacheService> cacheService = nsCacheService::GlobalInstance();
-  cacheService->RemoveCustomOfflineDevice(this);
-
-  nsCAutoString clientID;
-  aAppCache->GetClientID(clientID);
-  mCaches.Remove(clientID);
-
-  return true;
-}
--- a/netwerk/cache/nsDiskCacheDeviceSQL.h
+++ b/netwerk/cache/nsDiskCacheDeviceSQL.h
@@ -162,18 +162,16 @@ public:
                                                char ***keys);
 
   /**
    * Preference accessors
    */
 
   void                    SetCacheParentDirectory(nsIFile * parentDir);
   void                    SetCapacity(PRUint32  capacity);
-  void                    SetAutoShutdown() { mAutoShutdown = true; }
-  bool                    AutoShutdown(nsIApplicationCache * aAppCache);
 
   nsIFile *               BaseDirectory() { return mBaseDirectory; }
   nsIFile *               CacheDirectory() { return mCacheDirectory; }
   PRUint32                CacheCapacity() { return mCacheCapacity; }
   PRUint32                CacheSize();
   PRUint32                EntryCount();
   
 private:
@@ -254,17 +252,16 @@ private:
   nsCOMPtr<mozIStorageStatement>  mStatement_FindClientByNamespace;
   nsCOMPtr<mozIStorageStatement>  mStatement_EnumerateGroups;
   nsCOMPtr<mozIStorageStatement>  mStatement_EnumerateGroupsTimeOrder;
 
   nsCOMPtr<nsIFile>               mBaseDirectory;
   nsCOMPtr<nsIFile>               mCacheDirectory;
   PRUint32                        mCacheCapacity; // in bytes
   PRInt32                         mDeltaCounter;
-  bool                            mAutoShutdown;
 
   nsInterfaceHashtable<nsCStringHashKey, nsIWeakReference> mCaches;
   nsClassHashtable<nsCStringHashKey, nsCString> mActiveCachesByGroup;
   nsTHashtable<nsCStringHashKey> mActiveCaches;
 
   nsCOMPtr<nsIThread> mInitThread;
 };
 
--- a/netwerk/dns/nsDNSService2.cpp
+++ b/netwerk/dns/nsDNSService2.cpp
@@ -24,17 +24,16 @@
 #include "prmon.h"
 #include "prio.h"
 #include "plstr.h"
 #include "nsIOService.h"
 #include "nsCharSeparatedTokenizer.h"
 
 #include "mozilla/FunctionTimer.h"
 #include "mozilla/Attributes.h"
-#include "mozilla/VisualEventTracer.h"
 
 using namespace mozilla;
 
 static const char kPrefDnsCacheEntries[]    = "network.dnsCacheEntries";
 static const char kPrefDnsCacheExpiration[] = "network.dnsCacheExpiration";
 static const char kPrefDnsCacheGrace[]      = "network.dnsCacheExpirationGracePeriod";
 static const char kPrefEnableIDN[]          = "network.enableIDN";
 static const char kPrefIPv4OnlyDomains[]    = "network.dns.ipv4OnlyDomains";
@@ -274,18 +273,16 @@ nsDNSAsyncRequest::OnLookupComplete(nsHo
     nsCOMPtr<nsIDNSRecord> rec;
     if (NS_SUCCEEDED(status)) {
         NS_ASSERTION(hostRecord, "no host record");
         rec = new nsDNSRecord(hostRecord);
         if (!rec)
             status = NS_ERROR_OUT_OF_MEMORY;
     }
 
-    MOZ_EVENT_TRACER_DONE(this, "DNS");
-
     mListener->OnLookupComplete(this, rec, status);
     mListener = nsnull;
 
     // release the reference to ourselves that was added before we were
     // handed off to the host resolver.
     NS_RELEASE_THIS();
 }
 
@@ -603,19 +600,16 @@ nsDNSService::AsyncResolve(const nsACStr
     PRUint16 af = GetAFForLookup(*hostPtr, flags);
 
     nsDNSAsyncRequest *req =
             new nsDNSAsyncRequest(res, *hostPtr, listener, flags, af);
     if (!req)
         return NS_ERROR_OUT_OF_MEMORY;
     NS_ADDREF(*result = req);
 
-    MOZ_EVENT_TRACER_NAME_OBJECT(req, hostname.BeginReading());
-    MOZ_EVENT_TRACER_WAIT(req, "DNS");
-
     // addref for resolver; will be released when OnLookupComplete is called.
     NS_ADDREF(req);
     rv = res->ResolveHost(req->mHost.get(), flags, af, req);
     if (NS_FAILED(rv)) {
         NS_RELEASE(req);
         NS_RELEASE(*result);
     }
     return rv;
--- a/netwerk/dns/nsHostResolver.cpp
+++ b/netwerk/dns/nsHostResolver.cpp
@@ -32,17 +32,16 @@
 #include "plstr.h"
 #include "nsURLHelper.h"
 #include "nsThreadUtils.h"
 
 #include "mozilla/HashFunctions.h"
 #include "mozilla/FunctionTimer.h"
 #include "mozilla/TimeStamp.h"
 #include "mozilla/Telemetry.h"
-#include "mozilla/VisualEventTracer.h"
 
 using namespace mozilla;
 
 //----------------------------------------------------------------------------
 
 // Use a persistent thread pool in order to avoid spinning up new threads all the time.
 // In particular, thread creation results in a res_init() call from libc which is 
 // quite expensive.
@@ -176,18 +175,16 @@ nsHostRecord::Create(const nsHostKey *ke
     size_t hostLen = strlen(key->host) + 1;
     size_t size = hostLen + sizeof(nsHostRecord);
 
     // Use placement new to create the object with room for the hostname
     // allocated after it.
     void *place = ::operator new(size);
     *result = new(place) nsHostRecord(key);
     NS_ADDREF(*result);
-
-    MOZ_EVENT_TRACER_NAME_OBJECT(*result, key->host);
     return NS_OK;
 }
 
 nsHostRecord::~nsHostRecord()
 {
     if (addr)
         free(addr);
 }
@@ -710,18 +707,16 @@ nsHostResolver::ConditionallyCreateThrea
       LOG(("lookup waiting for thread - %s ...\n", rec->host));
 #endif
     return NS_OK;
 }
 
 nsresult
 nsHostResolver::IssueLookup(nsHostRecord *rec)
 {
-    MOZ_EVENT_TRACER_WAIT(rec, "nsHostResolver");
-
     nsresult rv = NS_OK;
     NS_ASSERTION(!rec->resolving, "record is already being resolved"); 
 
     // Add rec to one of the pending queues, possibly removing it from mEvictionQ.
     // If rec is on mEvictionQ, then we can just move the owning
     // reference over to the new active queue.
     if (rec->next == rec)
         NS_ADDREF(rec);
@@ -889,18 +884,16 @@ nsHostResolver::OnLookupComplete(nsHostR
                 }
 
                 // release reference to rec owned by mEvictionQ
                 NS_RELEASE(head);
             }
         }
     }
 
-    MOZ_EVENT_TRACER_DONE(rec, "nsHostResolver");
-
     if (!PR_CLIST_IS_EMPTY(&cbs)) {
         PRCList *node = cbs.next;
         while (node != &cbs) {
             nsResolveHostCallback *callback =
                     static_cast<nsResolveHostCallback *>(node);
             node = node->next;
             callback->OnLookupComplete(this, rec, status);
             // NOTE: callback must not be dereferenced after this point!!
@@ -974,17 +967,16 @@ nsHostResolver::ThreadFunc(void *arg)
         LOG(("resolving %s ...\n", rec->host));
 
         PRIntn flags = PR_AI_ADDRCONFIG;
         if (!(rec->flags & RES_CANON_NAME))
             flags |= PR_AI_NOCANONNAME;
 
         TimeStamp startTime = TimeStamp::Now();
 
-        MOZ_EVENT_TRACER_EXEC(rec, "nsHostResolver");
         ai = PR_GetAddrInfoByName(rec->host, rec->af, flags);
 #if defined(RES_RETRY_ON_FAILURE)
         if (!ai && rs.Reset())
             ai = PR_GetAddrInfoByName(rec->host, rec->af, flags);
 #endif
 
         TimeDuration elapsed = TimeStamp::Now() - startTime;
         PRUint32 millis = static_cast<PRUint32>(elapsed.ToMilliseconds());
--- a/netwerk/protocol/http/HttpChannelChild.cpp
+++ b/netwerk/protocol/http/HttpChannelChild.cpp
@@ -1217,31 +1217,16 @@ HttpChannelChild::SetApplicationCache(ns
   return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
 // HttpChannelChild::nsIApplicationCacheChannel
 //-----------------------------------------------------------------------------
 
 NS_IMETHODIMP
-HttpChannelChild::GetApplicationCacheForWrite(nsIApplicationCache **aApplicationCache)
-{
-  *aApplicationCache = nsnull;
-  return NS_OK;
-}
-NS_IMETHODIMP
-HttpChannelChild::SetApplicationCacheForWrite(nsIApplicationCache *aApplicationCache)
-{
-  NS_ENSURE_TRUE(!mWasOpened, NS_ERROR_ALREADY_OPENED);
-
-  // Child channels are not intended to be used for cache writes
-  return NS_ERROR_NOT_IMPLEMENTED;
-}
-
-NS_IMETHODIMP
 HttpChannelChild::GetLoadedFromApplicationCache(bool *aLoadedFromApplicationCache)
 {
   *aLoadedFromApplicationCache = mLoadedFromApplicationCache;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 HttpChannelChild::GetInheritApplicationCache(bool *aInherit)
--- a/netwerk/protocol/http/nsHttpChannel.cpp
+++ b/netwerk/protocol/http/nsHttpChannel.cpp
@@ -29,17 +29,16 @@
 #include "mozilla/TimeStamp.h"
 #include "nsDOMError.h"
 #include "nsAlgorithm.h"
 #include "sampler.h"
 #include "nsIConsoleService.h"
 #include "base/compiler_specific.h"
 #include "NullHttpTransaction.h"
 #include "mozilla/Attributes.h"
-#include "mozilla/VisualEventTracer.h"
 
 namespace mozilla { namespace net {
  
 namespace {
 
 // Device IDs for various cache types
 const char kDiskDeviceID[] = "disk";
 const char kMemoryDeviceID[] = "memory";
@@ -175,24 +174,19 @@ AutoRedirectVetoNotifier::ReportRedirect
         return;
 
     mChannel->mRedirectChannel = nsnull;
 
     nsCOMPtr<nsIRedirectResultListener> vetoHook;
     NS_QueryNotificationCallbacks(mChannel, 
                                   NS_GET_IID(nsIRedirectResultListener), 
                                   getter_AddRefs(vetoHook));
-
-    nsHttpChannel * channel = mChannel;
     mChannel = nsnull;
-
     if (vetoHook)
         vetoHook->OnRedirectResult(succeeded);
-
-    MOZ_EVENT_TRACER_DONE(channel, "AsyncProcessRedirection");
 }
 
 class HttpCacheQuery : public nsRunnable, public nsICacheListener
 {
 public:
     HttpCacheQuery(nsHttpChannel * channel,
                    const nsACString & clientID,
                    nsCacheStoragePolicy storagePolicy,
@@ -202,17 +196,17 @@ public:
                    bool noWait,
                    bool usingSSL,
                    bool loadedFromApplicationCache)
         // in
         : mChannel(channel)
         , mHasQueryString(HasQueryString(channel->mRequestHead.Method(),
                                          channel->mURI))
         , mLoadFlags(channel->mLoadFlags)
-        , mCacheForOfflineUse(!!channel->mApplicationCacheForWrite)
+        , mCacheForOfflineUse(channel->mCacheForOfflineUse)
         , mFallbackChannel(channel->mFallbackChannel)
         , mClientID(clientID)
         , mStoragePolicy(storagePolicy)
         , mUsingPrivateBrowsing(usingPrivateBrowsing)
         , mCacheKey(cacheKey)
         , mAccessToRequest(accessToRequest)
         , mNoWait(noWait)
         , mUsingSSL(usingSSL)
@@ -311,16 +305,17 @@ nsHttpChannel::nsHttpChannel()
     , mOfflineCacheAccess(0)
     , mOfflineCacheLastModifiedTime(0)
     , mCachedContentIsValid(false)
     , mCachedContentIsPartial(false)
     , mTransactionReplaced(false)
     , mAuthRetryPending(false)
     , mResuming(false)
     , mInitedCacheEntry(false)
+    , mCacheForOfflineUse(false)
     , mFallbackChannel(false)
     , mCustomConditionalRequest(false)
     , mFallingBack(false)
     , mWaitingForRedirectCallback(false)
     , mRequestTimeInitialized(false)
     , mDidReval(false)
 {
     LOG(("Creating nsHttpChannel [this=%p]\n", this));
@@ -336,22 +331,16 @@ nsHttpChannel::~nsHttpChannel()
         mAuthProvider->Disconnect(NS_ERROR_ABORT);
 }
 
 nsresult
 nsHttpChannel::Init(nsIURI *uri,
                     PRUint8 caps,
                     nsProxyInfo *proxyInfo)
 {
-#ifdef MOZ_VISUAL_EVENT_TRACER
-    nsCAutoString url;
-    uri->GetAsciiSpec(url);
-    MOZ_EVENT_TRACER_NAME_OBJECT(this, url.BeginReading());
-#endif
-
     nsresult rv = HttpBaseChannel::Init(uri, caps, proxyInfo);
     if (NS_FAILED(rv))
         return rv;
 
     LOG(("nsHttpChannel::Init [this=%p]\n", this));
 
     mAuthProvider =
         do_CreateInstance("@mozilla.org/network/http-channel-auth-provider;1",
@@ -456,17 +445,17 @@ nsHttpChannel::Connect()
             }
             return NS_ERROR_DOCUMENT_NOT_CACHED;
         }
         // otherwise, let's just proceed without using the cache.
     }
 
     // if cacheForOfflineUse has been set, open up an offline cache
     // entry to update
-    if (mApplicationCacheForWrite) {
+    if (mCacheForOfflineUse) {
         rv = OpenOfflineCacheEntryForWriting();
         if (NS_FAILED(rv)) return rv;
 
         if (mOnCacheEntryAvailableCallback)
             return NS_OK;
     }
 
     return ContinueConnect();
@@ -1002,17 +991,17 @@ nsHttpChannel::CallOnStartRequest()
             rv = InitOfflineCacheEntry();
             if (NS_FAILED(rv)) return rv;
             
             // InitOfflineCacheEntry may have closed mOfflineCacheEntry
             if (mOfflineCacheEntry) {
                 rv = InstallOfflineCacheListener();
                 if (NS_FAILED(rv)) return rv;
             }
-        } else if (mApplicationCacheForWrite) {
+        } else if (mCacheForOfflineUse) {
             LOG(("offline cache is up to date, not updating"));
             CloseOfflineCacheEntry();
         }
     }
 
     return NS_OK;
 }
 
@@ -1374,17 +1363,17 @@ nsHttpChannel::ContinueProcessResponse(n
         DoNotifyListener();
         return rv;
     }
 
     if (NS_SUCCEEDED(rv)) {
         InitCacheEntry();
         CloseCacheEntry(false);
 
-        if (mApplicationCacheForWrite) {
+        if (mCacheForOfflineUse) {
             // Store response in the offline cache
             InitOfflineCacheEntry();
             CloseOfflineCacheEntry();
         }
         return NS_OK;
     }
 
     LOG(("ContinueProcessResponse got failure result [rv=%x]\n", rv));
@@ -2275,17 +2264,18 @@ nsHttpChannel::ProcessFallback(bool *wai
     // Kill any offline cache entry, and disable offline caching for the
     // fallback.
     if (mOfflineCacheEntry) {
         mOfflineCacheEntry->Doom();
         mOfflineCacheEntry = 0;
         mOfflineCacheAccess = 0;
     }
 
-    mApplicationCacheForWrite = nsnull;
+    mCacheForOfflineUse = false;
+    mOfflineCacheClientID.Truncate();
     mOfflineCacheEntry = 0;
     mOfflineCacheAccess = 0;
 
     // Close the current cache entry.
     CloseCacheEntry(true);
 
     // Create a new channel to load the fallback entry.
     nsRefPtr<nsIChannel> newChannel;
@@ -2374,18 +2364,16 @@ IsSubRangeRequest(nsHttpRequestHead &aRe
     nsCAutoString byteRange;
     aRequestHead.GetHeader(nsHttp::Range, byteRange);
     return !byteRange.EqualsLiteral("bytes=0-");
 }
 
 nsresult
 nsHttpChannel::OpenCacheEntry(bool usingSSL)
 {
-    MOZ_EVENT_TRACER_EXEC(this, "OpenCacheEntry");
-
     nsresult rv;
 
     NS_ASSERTION(!mOnCacheEntryAvailableCallback, "Unexpected state");
     mLoadedFromApplicationCache = false;
 
     LOG(("nsHttpChannel::OpenCacheEntry [this=%p]", this));
 
     // make sure we're not abusing this function
@@ -2511,17 +2499,17 @@ nsHttpChannel::OnOfflineCacheEntryAvaila
     if (mCanceled && NS_FAILED(mStatus)) {
         LOG(("channel was canceled [this=%p status=%x]\n", this, mStatus));
         return mStatus;
     }
 
     if (NS_SUCCEEDED(aEntryStatus))
         return NS_OK;
 
-    if (!mApplicationCacheForWrite && !mFallbackChannel) {
+    if (!mCacheForOfflineUse && !mFallbackChannel) {
         nsCAutoString cacheKey;
         GenerateCacheKey(mPostID, cacheKey);
 
         // Check for namespace match.
         nsCOMPtr<nsIApplicationCacheNamespace> namespaceEntry;
         rv = mApplicationCache->GetMatchingNamespace
             (cacheKey, getter_AddRefs(namespaceEntry));
         NS_ENSURE_SUCCESS(rv, rv);
@@ -2648,44 +2636,32 @@ nsHttpChannel::OpenOfflineCacheEntryForW
     // Don't cache byte range requests which are subranges, only cache 0-
     // byte range requests.
     if (IsSubRangeRequest(mRequestHead))
         return NS_OK;
 
     nsCAutoString cacheKey;
     GenerateCacheKey(mPostID, cacheKey);
 
-    NS_ENSURE_TRUE(mApplicationCacheForWrite,
-                   NS_ERROR_NOT_AVAILABLE);
-
-    nsCAutoString offlineCacheClientID;
-    rv = mApplicationCacheForWrite->GetClientID(offlineCacheClientID);
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    NS_ENSURE_TRUE(!offlineCacheClientID.IsEmpty(),
+    NS_ENSURE_TRUE(!mOfflineCacheClientID.IsEmpty(),
                    NS_ERROR_NOT_AVAILABLE);
 
     nsCOMPtr<nsICacheSession> session;
     nsCOMPtr<nsICacheService> serv =
         do_GetService(NS_CACHESERVICE_CONTRACTID, &rv);
     if (NS_FAILED(rv)) return rv;
 
-    rv = serv->CreateSession(offlineCacheClientID.get(),
+    rv = serv->CreateSession(mOfflineCacheClientID.get(),
                              nsICache::STORE_OFFLINE,
                              nsICache::STREAM_BASED,
                              getter_AddRefs(session));
     if (NS_FAILED(rv)) return rv;
 
-    nsCOMPtr<nsIFile> profileDirectory;
-    rv = mApplicationCacheForWrite->GetProfileDirectory(
-            getter_AddRefs(profileDirectory));
-    NS_ENSURE_SUCCESS(rv, rv);
-
-    if (profileDirectory) {
-        rv = session->SetProfileDirectory(profileDirectory);
+    if (mProfileDirectory) {
+        rv = session->SetProfileDirectory(mProfileDirectory);
         if (NS_FAILED(rv)) return rv;
     }
 
     mOnCacheEntryAvailableCallback =
         &nsHttpChannel::OnOfflineCacheEntryForWritingAvailable;
     rv = session->AsyncOpenCacheEntry(cacheKey, nsICache::ACCESS_READ_WRITE,
                                       this, true);
     if (NS_SUCCEEDED(rv))
@@ -3315,17 +3291,17 @@ HttpCacheQuery::MustValidateBasedOnQuery
     }
     return false;
 }
 
 
 bool
 nsHttpChannel::ShouldUpdateOfflineCacheEntry()
 {
-    if (!mApplicationCacheForWrite || !mOfflineCacheEntry) {
+    if (!mCacheForOfflineUse || !mOfflineCacheEntry) {
         return false;
     }
 
     // if we're updating the cache entry, update the offline cache entry too
     if (mCacheEntry && (mCacheAccess & nsICache::ACCESS_WRITE)) {
         return true;
     }
 
@@ -3506,28 +3482,28 @@ nsHttpChannel::ReadFromCache(bool alread
         // TODO: Bug 759040 - We should call HandleAsyncRedirect directly here,
         // to avoid event dispatching latency.
         MOZ_ASSERT(!mCacheInputStream);
         LOG(("Skipping skip read of cached redirect entity\n"));
         return AsyncCall(&nsHttpChannel::HandleAsyncRedirect);
     }
     
     if ((mLoadFlags & LOAD_ONLY_IF_MODIFIED) && !mCachedContentIsPartial) {
-        if (!mApplicationCacheForWrite) {
+        if (!mCacheForOfflineUse) {
             LOG(("Skipping read from cache based on LOAD_ONLY_IF_MODIFIED "
                  "load flag\n"));
             MOZ_ASSERT(!mCacheInputStream);
             // TODO: Bug 759040 - We should call HandleAsyncNotModified directly
             // here, to avoid event dispatching latency.
             return AsyncCall(&nsHttpChannel::HandleAsyncNotModified);
         }
         
         if (!ShouldUpdateOfflineCacheEntry()) {
             LOG(("Skipping read from cache based on LOAD_ONLY_IF_MODIFIED "
-                 "load flag (mApplicationCacheForWrite not null case)\n"));
+                 "load flag (mCacheForOfflineUse case)\n"));
             mCacheInputStream.CloseAndRelease();
             // TODO: Bug 759040 - We should call HandleAsyncNotModified directly
             // here, to avoid event dispatching latency.
             return AsyncCall(&nsHttpChannel::HandleAsyncNotModified);
         }
     }
 
     MOZ_ASSERT(mCacheInputStream);
@@ -4008,39 +3984,33 @@ nsHttpChannel::SetupReplacementChannel(n
             // we don't need to transfer it if it's 0.
             if (mPostID) {
                 nsCOMPtr<nsISupports> cacheKey;
                 GetCacheKey(getter_AddRefs(cacheKey));
                 if (cacheKey) {
                     cachingChannel->SetCacheKey(cacheKey);
                 }
             }
-        }
-
-        nsCOMPtr<nsIApplicationCacheChannel> appCacheChannel = do_QueryInterface(newChannel);
-        if (appCacheChannel) {
-            // app cache for write
-            appCacheChannel->SetApplicationCacheForWrite(mApplicationCacheForWrite);
+
+            // cacheClientID, cacheForOfflineUse
+            cachingChannel->SetOfflineCacheClientID(mOfflineCacheClientID);
+            cachingChannel->SetCacheForOfflineUse(mCacheForOfflineUse);
+            cachingChannel->SetProfileDirectory(mProfileDirectory);
         }
     }
 
     return NS_OK;
 }
 
 nsresult
 nsHttpChannel::AsyncProcessRedirection(PRUint32 redirectType)
 {
     LOG(("nsHttpChannel::AsyncProcessRedirection [this=%p type=%u]\n",
         this, redirectType));
 
-    // The channel is actually starting its operation now, at least because
-    // we want it to appear like being in the waiting phase until now.
-    MOZ_EVENT_TRACER_EXEC(this, "nsHttpChannel");
-    MOZ_EVENT_TRACER_EXEC(this, "AsyncProcessRedirection");
-
     const char *location = mResponseHead->PeekHeader(nsHttp::Location);
 
     // if a location header was not given, then we can't perform the redirect,
     // so just carry on as though this were a normal response.
     if (!location)
         return NS_ERROR_FAILURE;
 
     // make sure non-ASCII characters in the location header are escaped.
@@ -4376,18 +4346,16 @@ nsHttpChannel::GetSecurityInfo(nsISuppor
     *securityInfo = mSecurityInfo;
     NS_IF_ADDREF(*securityInfo);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHttpChannel::AsyncOpen(nsIStreamListener *listener, nsISupports *context)
 {
-    MOZ_EVENT_TRACER_WAIT(this, "nsHttpChannel");
-
     LOG(("nsHttpChannel::AsyncOpen [this=%p]\n", this));
 
     NS_ENSURE_ARG_POINTER(listener);
     NS_ENSURE_TRUE(!mIsPending, NS_ERROR_IN_PROGRESS);
     NS_ENSURE_TRUE(!mWasOpened, NS_ERROR_ALREADY_OPENED);
 
     nsresult rv;
 
@@ -5008,17 +4976,16 @@ nsHttpChannel::OnStopRequest(nsIRequest 
     if (mCacheEntry && (mCacheAccess & nsICache::ACCESS_WRITE) &&
         mRequestTimeInitialized){
         FinalizeCacheEntry();
     }
     
     if (mListener) {
         LOG(("  calling OnStopRequest\n"));
         mListener->OnStopRequest(this, mListenerContext, status);
-        MOZ_EVENT_TRACER_DONE(this, "nsHttpChannel");
         mListener = 0;
         mListenerContext = 0;
     }
 
     if (mCacheEntry) {
         bool asFile = false;
         if (mInitedCacheEntry && !mCachedContentIsPartial &&
             (NS_SUCCEEDED(mStatus) || contentComplete) &&
@@ -5105,18 +5072,16 @@ nsHttpChannel::OnDataAvailable(nsIReques
         OnTransportStatus(nsnull, transportStatus, progress, progressMax);
 
         //
         // we have to manually keep the logical offset of the stream up-to-date.
         // we cannot depend solely on the offset provided, since we may have 
         // already streamed some data from another source (see, for example,
         // OnDoneReadingPartialCacheEntry).
         //
-        if (!mLogicalOffset)
-            MOZ_EVENT_TRACER_EXEC(this, "nsHttpChannel");
 
         // report the current stream offset to our listener... if we've
         // streamed more than PR_UINT32_MAX, then avoid overflowing the
         // stream offset.  it's the best we can do without a 64-bit stream
         // listener API. (Copied from nsInputStreamPump::OnStateTransfer.)
         PRUint32 odaOffset = mLogicalOffset > PR_UINT32_MAX
                            ? PR_UINT32_MAX : PRUint32(mLogicalOffset);
 
@@ -5409,16 +5374,72 @@ nsHttpChannel::SetCacheAsFile(bool value
     nsCacheStoragePolicy policy;
     if (value)
         policy = nsICache::STORE_ON_DISK_AS_FILE;
     else
         policy = nsICache::STORE_ANYWHERE;
     return mCacheEntry->SetStoragePolicy(policy);
 }
 
+
+NS_IMETHODIMP
+nsHttpChannel::GetCacheForOfflineUse(bool *value)
+{
+    *value = mCacheForOfflineUse;
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHttpChannel::SetCacheForOfflineUse(bool value)
+{
+    ENSURE_CALLED_BEFORE_ASYNC_OPEN();
+
+    mCacheForOfflineUse = value;
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHttpChannel::GetOfflineCacheClientID(nsACString &value)
+{
+    value = mOfflineCacheClientID;
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHttpChannel::SetOfflineCacheClientID(const nsACString &value)
+{
+    ENSURE_CALLED_BEFORE_ASYNC_OPEN();
+
+    mOfflineCacheClientID = value;
+
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHttpChannel::GetProfileDirectory(nsIFile **_result)
+{
+    NS_ENSURE_ARG(_result);
+
+    if (!mProfileDirectory)
+        return NS_ERROR_NOT_AVAILABLE;
+
+    NS_ADDREF(*_result = mProfileDirectory);
+    return NS_OK;
+}
+
+NS_IMETHODIMP
+nsHttpChannel::SetProfileDirectory(nsIFile *value)
+{
+    mProfileDirectory = value;
+    return NS_OK;
+}
+
 NS_IMETHODIMP
 nsHttpChannel::GetCacheFile(nsIFile **cacheFile)
 {
     if (!mCacheEntry)
         return NS_ERROR_NOT_AVAILABLE;
     return mCacheEntry->GetFile(cacheFile);
 }
 
@@ -5444,20 +5465,16 @@ nsHttpChannel::ResumeAt(PRUint64 aStartP
 
 NS_IMETHODIMP
 nsHttpChannel::OnCacheEntryAvailable(nsICacheEntryDescriptor *entry,
                                      nsCacheAccessMode access,
                                      nsresult status)
 {
     MOZ_ASSERT(NS_IsMainThread());
 
-    mozilla::eventtracer::AutoEventTracer profiler(this,
-             eventtracer::eNone, eventtracer::eDone,
-             "OpenCacheEntry");
-
     nsresult rv;
 
     LOG(("nsHttpChannel::OnCacheEntryAvailable [this=%p entry=%p "
          "access=%x status=%x]\n", this, entry, access, status));
 
     if (mCacheQuery) {
         mRequestHead = mCacheQuery->mRequestHead;
         mRedirectedCachekeys = mCacheQuery->mRedirectedCachekeys.forget();
@@ -5523,19 +5540,19 @@ nsHttpChannel::OnCacheEntryAvailableInte
             if (mCanceled)
                 // If the request was canceled then don't continue without using
                 // the cache entry. See bug #764337
                 return rv;
 
             // proceed without using the cache
         }
 
-        // if app cache for write has been set, open up an offline cache entry
+        // if cacheForOfflineUse has been set, open up an offline cache entry
         // to update
-        if (mApplicationCacheForWrite) {
+        if (mCacheForOfflineUse) {
             rv = OpenOfflineCacheEntryForWriting();
             if (mOnCacheEntryAvailableCallback) {
                 NS_ASSERTION(NS_SUCCEEDED(rv), "Unexpected state");
                 return NS_OK;
             }
 
             if (NS_FAILED(rv))
                 return rv;
@@ -5611,17 +5628,16 @@ nsHttpChannel::DoAuthRetry(nsAHttpConnec
         mTransactionPump->Suspend();
 
     return NS_OK;
 }
 
 //-----------------------------------------------------------------------------
 // nsHttpChannel::nsIApplicationCacheChannel
 //-----------------------------------------------------------------------------
-
 NS_IMETHODIMP
 nsHttpChannel::GetApplicationCache(nsIApplicationCache **out)
 {
     NS_IF_ADDREF(*out = mApplicationCache);
     return NS_OK;
 }
 
 NS_IMETHODIMP
@@ -5629,32 +5645,16 @@ nsHttpChannel::SetApplicationCache(nsIAp
 {
     ENSURE_CALLED_BEFORE_ASYNC_OPEN();
 
     mApplicationCache = appCache;
     return NS_OK;
 }
 
 NS_IMETHODIMP
-nsHttpChannel::GetApplicationCacheForWrite(nsIApplicationCache **out)
-{
-    NS_IF_ADDREF(*out = mApplicationCacheForWrite);
-    return NS_OK;
-}
-
-NS_IMETHODIMP
-nsHttpChannel::SetApplicationCacheForWrite(nsIApplicationCache *appCache)
-{
-    ENSURE_CALLED_BEFORE_ASYNC_OPEN();
-
-    mApplicationCacheForWrite = appCache;
-    return NS_OK;
-}
-
-NS_IMETHODIMP
 nsHttpChannel::GetLoadedFromApplicationCache(bool *aLoadedFromApplicationCache)
 {
     *aLoadedFromApplicationCache = mLoadedFromApplicationCache;
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsHttpChannel::GetInheritApplicationCache(bool *aInherit)
@@ -5793,17 +5793,16 @@ nsHttpChannel::OnRedirectVerifyCallback(
         // and let it be propagated to pumps.
         Cancel(result);
     }
 
     if (!mWaitingForRedirectCallback) {
         // We are not waiting for the callback. At this moment we must release
         // reference to the redirect target channel, otherwise we may leak.
         mRedirectChannel = nsnull;
-        MOZ_EVENT_TRACER_DONE(this, "nsHttpChannel");
     }
 
     // We always resume the pumps here. If all functions on stack have been
     // called we need OnStopRequest to be triggered, and if we broke out of the
     // loop above (and are thus waiting for a new callback) the suspension
     // count must be balanced in the pumps.
     if (mTransactionPump)
         mTransactionPump->Resume();
--- a/netwerk/protocol/http/nsHttpChannel.h
+++ b/netwerk/protocol/http/nsHttpChannel.h
@@ -305,17 +305,19 @@ private:
 
     typedef nsresult (nsHttpChannel:: *nsOnCacheEntryAvailableCallback)(
         nsICacheEntryDescriptor *, nsCacheAccessMode, nsresult);
     nsOnCacheEntryAvailableCallback   mOnCacheEntryAvailableCallback;
 
     nsCOMPtr<nsICacheEntryDescriptor> mOfflineCacheEntry;
     nsCacheAccessMode                 mOfflineCacheAccess;
     PRUint32                          mOfflineCacheLastModifiedTime;
-    nsCOMPtr<nsIApplicationCache>     mApplicationCacheForWrite;
+    nsCString                         mOfflineCacheClientID;
+
+    nsCOMPtr<nsIFile>                 mProfileDirectory;
 
     // auth specific data
     nsCOMPtr<nsIHttpChannelAuthProvider> mAuthProvider;
 
     // Proxy info to replace with
     nsCOMPtr<nsIProxyInfo>            mTargetProxyInfo;
 
     // If the channel is associated with a cache, and the URI matched
@@ -333,16 +335,17 @@ private:
 
     // state flags
     PRUint32                          mCachedContentIsValid     : 1;
     PRUint32                          mCachedContentIsPartial   : 1;
     PRUint32                          mTransactionReplaced      : 1;
     PRUint32                          mAuthRetryPending         : 1;
     PRUint32                          mResuming                 : 1;
     PRUint32                          mInitedCacheEntry         : 1;
+    PRUint32                          mCacheForOfflineUse       : 1;
     // True if we are loading a fallback cache entry from the
     // application cache.
     PRUint32                          mFallbackChannel          : 1;
     // True if consumer added its own If-None-Match or If-Modified-Since
     // headers. In such a case we must not override them in the cache code
     // and also we want to pass possible 304 code response through.
     PRUint32                          mCustomConditionalRequest : 1;
     PRUint32                          mFallingBack              : 1;
--- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp
@@ -14,17 +14,16 @@
 
 #include "nsIServiceManager.h"
 
 #include "nsIObserverService.h"
 
 #include "nsISSLSocketControl.h"
 #include "prnetdb.h"
 #include "mozilla/Telemetry.h"
-#include "mozilla/VisualEventTracer.h"
 
 using namespace mozilla;
 using namespace mozilla::net;
 
 // defined by the socket transport service while active
 extern PRThread *gSocketThread;
 
 static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID);
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -24,17 +24,16 @@
 #include "nsMultiplexInputStream.h"
 #include "nsStringStream.h"
 
 #include "nsComponentManagerUtils.h" // do_CreateInstance
 #include "nsServiceManagerUtils.h"   // do_GetService
 #include "nsIHttpActivityObserver.h"
 
 #include "mozilla/FunctionTimer.h"
-#include "mozilla/VisualEventTracer.h"
 
 using namespace mozilla;
 
 //-----------------------------------------------------------------------------
 
 #ifdef DEBUG
 // defined by the socket transport service while active
 extern PRThread *gSocketThread;
@@ -166,23 +165,16 @@ nsHttpTransaction::Init(PRUint8 caps,
                         nsHttpRequestHead *requestHead,
                         nsIInputStream *requestBody,
                         bool requestBodyHasHeaders,
                         nsIEventTarget *target,
                         nsIInterfaceRequestor *callbacks,
                         nsITransportEventSink *eventsink,
                         nsIAsyncInputStream **responseBody)
 {
-    MOZ_EVENT_TRACER_COMPOUND_NAME(static_cast<nsAHttpTransaction*>(this),
-                                   requestHead->PeekHeader(nsHttp::Host),
-                                   requestHead->RequestURI().BeginReading());
-
-    MOZ_EVENT_TRACER_WAIT(static_cast<nsAHttpTransaction*>(this),
-                          "nsHttpTransaction");
-
     NS_TIME_FUNCTION;
 
     nsresult rv;
 
     LOG(("nsHttpTransaction::Init [this=%x caps=%x]\n", this, caps));
 
     NS_ASSERTION(cinfo, "ouch");
     NS_ASSERTION(requestHead, "ouch");
@@ -388,21 +380,16 @@ nsHttpTransaction::TakeSubTransactions(
 // nsHttpTransaction::nsAHttpTransaction
 //----------------------------------------------------------------------------
 
 void
 nsHttpTransaction::SetConnection(nsAHttpConnection *conn)
 {
     NS_IF_RELEASE(mConnection);
     NS_IF_ADDREF(mConnection = conn);
-
-    if (conn) {
-        MOZ_EVENT_TRACER_EXEC(static_cast<nsAHttpTransaction*>(this),
-                              "nsHttpTransaction");
-    }
 }
 
 void
 nsHttpTransaction::GetSecurityCallbacks(nsIInterfaceRequestor **cb,
                                         nsIEventTarget        **target)
 {
     NS_IF_ADDREF(*cb = mCallbacks);
     if (target)
@@ -524,22 +511,16 @@ nsHttpTransaction::ReadRequestSegment(ns
     nsHttpTransaction *trans = (nsHttpTransaction *) closure;
     nsresult rv = trans->mReader->OnReadSegment(buf, count, countRead);
     if (NS_FAILED(rv)) return rv;
 
     if (trans->TimingEnabled() && trans->mTimings.requestStart.IsNull()) {
         // First data we're sending -> this is requestStart
         trans->mTimings.requestStart = mozilla::TimeStamp::Now();
     }
-
-    if (!trans->mSentData) {
-        MOZ_EVENT_TRACER_MARK(static_cast<nsAHttpTransaction*>(trans),
-                              "First write");
-    }
-
     trans->mSentData = true;
     return NS_OK;
 }
 
 nsresult
 nsHttpTransaction::ReadSegments(nsAHttpSegmentReader *reader,
                                 PRUint32 count, PRUint32 *countRead)
 {
@@ -600,21 +581,16 @@ nsHttpTransaction::WritePipeSegment(nsIO
 
     nsresult rv;
     //
     // OK, now let the caller fill this segment with data.
     //
     rv = trans->mWriter->OnWriteSegment(buf, count, countWritten);
     if (NS_FAILED(rv)) return rv; // caller didn't want to write anything
 
-    if (!trans->mReceivedData) {
-        MOZ_EVENT_TRACER_MARK(static_cast<nsAHttpTransaction*>(trans),
-                              "First read");
-    }
-
     NS_ASSERTION(*countWritten > 0, "bad writer");
     trans->mReceivedData = true;
 
     // Let the transaction "play" with the buffer.  It is free to modify
     // the contents of the buffer and/or modify countWritten.
     // - Bytes in HTTP headers don't count towards countWritten, so the input
     // side of pipe (aka nsHttpChannel's mTransactionPump) won't hit
     // OnInputStreamReady until all headers have been parsed.
@@ -803,19 +779,16 @@ nsHttpTransaction::Close(nsresult reason
     mLineBuf.Truncate();
     if (mChunkedDecoder) {
         delete mChunkedDecoder;
         mChunkedDecoder = nsnull;
     }
 
     // closing this pipe triggers the channel's OnStopRequest method.
     mPipeOut->CloseWithStatus(reason);
-
-    MOZ_EVENT_TRACER_DONE(static_cast<nsAHttpTransaction*>(this),
-                          "nsHttpTransaction");
 }
 
 nsresult
 nsHttpTransaction::AddTransaction(nsAHttpTransaction *trans)
 {
     return NS_ERROR_NOT_IMPLEMENTED;
 }
 
--- a/netwerk/test/unit/test_offlinecache_custom-directory.js
+++ b/netwerk/test/unit/test_offlinecache_custom-directory.js
@@ -59,32 +59,16 @@ function finish_test(customDir)
   do_check_eq(file1.exists(), true);
 
   var file2 = offlineCacheDir.clone();
   file2.append("8");
   file2.append("6");
   file2.append("0B457F75198B29-0");
   do_check_eq(file2.exists(), true);
 
-  // This must not throw an exception.  After the update has finished
-  // the index file can be freely removed.  This way we check this process
-  // is no longer keeping the file open.  Check like this will probably
-  // work only Windows systems.
-
-  // This test could potentially randomaly fail when we start closing
-  // the offline cache database off the main thread.  Tries in a loop
-  // may be a solution then.
-  try {
-    indexSqlFile.remove(false);
-    do_check_true(true);
-  }
-  catch (ex) {
-    do_throw("Could not remove the sqlite.index file, we still keep it open \n" + ex + "\n");
-  }
-
   httpServer.stop(do_test_finished);
 }
 
 function run_test()
 {
   httpServer = new nsHttpServer();
   httpServer.registerPathHandler("/masterEntry", masterEntryHandler);
   httpServer.registerPathHandler("/manifest", manifestHandler);
--- a/uriloader/prefetch/nsOfflineCacheUpdate.cpp
+++ b/uriloader/prefetch/nsOfflineCacheUpdate.cpp
@@ -285,21 +285,23 @@ NS_IMPL_ISUPPORTS6(nsOfflineCacheUpdateI
 //-----------------------------------------------------------------------------
 // nsOfflineCacheUpdateItem <public>
 //-----------------------------------------------------------------------------
 
 nsOfflineCacheUpdateItem::nsOfflineCacheUpdateItem(nsIURI *aURI,
                                                    nsIURI *aReferrerURI,
                                                    nsIApplicationCache *aApplicationCache,
                                                    nsIApplicationCache *aPreviousApplicationCache,
+                                                   const nsACString &aClientID,
                                                    PRUint32 type)
     : mURI(aURI)
     , mReferrerURI(aReferrerURI)
     , mApplicationCache(aApplicationCache)
     , mPreviousApplicationCache(aPreviousApplicationCache)
+    , mClientID(aClientID)
     , mItemType(type)
     , mChannel(nsnull)
     , mState(nsIDOMLoadStatus::UNINITIALIZED)
     , mBytesRead(0)
 {
 }
 
 nsOfflineCacheUpdateItem::~nsOfflineCacheUpdateItem()
@@ -333,30 +335,45 @@ nsOfflineCacheUpdateItem::OpenChannel(ns
 
     // Support for nsIApplicationCacheChannel is required.
     NS_ENSURE_SUCCESS(rv, rv);
 
     // Use the existing application cache as the cache to check.
     rv = appCacheChannel->SetApplicationCache(mPreviousApplicationCache);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    // Set the new application cache as the targer for write.
-    rv = appCacheChannel->SetApplicationCacheForWrite(mApplicationCache);
-    NS_ENSURE_SUCCESS(rv, rv);
-
     // configure HTTP specific stuff
     nsCOMPtr<nsIHttpChannel> httpChannel =
         do_QueryInterface(mChannel);
     if (httpChannel) {
         httpChannel->SetReferrer(mReferrerURI);
         httpChannel->SetRequestHeader(NS_LITERAL_CSTRING("X-Moz"),
                                       NS_LITERAL_CSTRING("offline-resource"),
                                       false);
     }
 
+    nsCOMPtr<nsICachingChannel> cachingChannel =
+        do_QueryInterface(mChannel);
+    if (cachingChannel) {
+        rv = cachingChannel->SetCacheForOfflineUse(true);
+        NS_ENSURE_SUCCESS(rv, rv);
+
+        nsCOMPtr<nsIFile> cacheDirectory;
+        rv = mApplicationCache->GetCacheDirectory(getter_AddRefs(cacheDirectory));
+        NS_ENSURE_SUCCESS(rv, rv);
+
+        rv = cachingChannel->SetProfileDirectory(cacheDirectory);
+        NS_ENSURE_SUCCESS(rv, rv);
+
+        if (!mClientID.IsEmpty()) {
+            rv = cachingChannel->SetOfflineCacheClientID(mClientID);
+            NS_ENSURE_SUCCESS(rv, rv);
+        }
+    }
+
     rv = mChannel->AsyncOpen(this, nsnull);
     NS_ENSURE_SUCCESS(rv, rv);
 
     mUpdate = aUpdate;
 
     mState = nsIDOMLoadStatus::REQUESTED;
 
     return NS_OK;
@@ -483,20 +500,32 @@ nsOfflineCacheUpdateItem::AsyncOnChannel
         return NS_ERROR_ABORT;
     }
 
     nsCOMPtr<nsIURI> newURI;
     nsresult rv = aNewChannel->GetURI(getter_AddRefs(newURI));
     if (NS_FAILED(rv))
         return rv;
 
-    nsCOMPtr<nsIApplicationCacheChannel> appCacheChannel =
+    nsCOMPtr<nsICachingChannel> newCachingChannel =
         do_QueryInterface(aNewChannel);
-    if (appCacheChannel) {
-        rv = appCacheChannel->SetApplicationCacheForWrite(mApplicationCache);
+    if (newCachingChannel) {
+        rv = newCachingChannel->SetCacheForOfflineUse(true);
+        NS_ENSURE_SUCCESS(rv, rv);
+
+        if (!mClientID.IsEmpty()) {
+            rv = newCachingChannel->SetOfflineCacheClientID(mClientID);
+            NS_ENSURE_SUCCESS(rv, rv);
+        }
+
+        nsCOMPtr<nsIFile> cacheDirectory;
+        rv = mApplicationCache->GetCacheDirectory(getter_AddRefs(cacheDirectory));
+        NS_ENSURE_SUCCESS(rv, rv);
+
+        rv = newCachingChannel->SetProfileDirectory(cacheDirectory);
         NS_ENSURE_SUCCESS(rv, rv);
     }
 
     nsCAutoString oldScheme;
     mURI->GetScheme(oldScheme);
 
     bool match;
     if (NS_FAILED(newURI->SchemeIs(oldScheme.get(), &match)) || !match) {
@@ -650,19 +679,20 @@ nsOfflineCacheUpdateItem::GetStatus(PRUi
 
 //-----------------------------------------------------------------------------
 // nsOfflineManifestItem <public>
 //-----------------------------------------------------------------------------
 
 nsOfflineManifestItem::nsOfflineManifestItem(nsIURI *aURI,
                                              nsIURI *aReferrerURI,
                                              nsIApplicationCache *aApplicationCache,
-                                             nsIApplicationCache *aPreviousApplicationCache)
+                                             nsIApplicationCache *aPreviousApplicationCache,
+                                             const nsACString &aClientID)
     : nsOfflineCacheUpdateItem(aURI, aReferrerURI,
-                               aApplicationCache, aPreviousApplicationCache,
+                               aApplicationCache, aPreviousApplicationCache, aClientID,
                                nsIApplicationCache::ITEM_MANIFEST)
     , mParserState(PARSE_INIT)
     , mNeedsUpdate(true)
     , mManifestHashInitialized(false)
 {
     ReadStrictFileOriginPolicyPref();
 }
 
@@ -1229,16 +1259,19 @@ nsOfflineCacheUpdate::Init(nsIURI *aMani
                                           getter_AddRefs(mPreviousApplicationCache));
         NS_ENSURE_SUCCESS(rv, rv);
 
         rv = cacheService->CreateApplicationCache(manifestSpec,
                                                   getter_AddRefs(mApplicationCache));
         NS_ENSURE_SUCCESS(rv, rv);
     }
 
+    rv = mApplicationCache->GetClientID(mClientID);
+    NS_ENSURE_SUCCESS(rv, rv);
+
     rv = nsOfflineCacheUpdateService::OfflineAppPinnedForURI(aDocumentURI,
                                                              NULL,
                                                              &mPinned);
     NS_ENSURE_SUCCESS(rv, rv);
 
     mState = STATE_INITIALIZED;
     return NS_OK;
 }
@@ -1254,27 +1287,28 @@ nsOfflineCacheUpdate::InitPartial(nsIURI
     nsOfflineCacheUpdateService* service =
         nsOfflineCacheUpdateService::EnsureService();
     if (!service)
         return NS_ERROR_FAILURE;
 
     LOG(("nsOfflineCacheUpdate::InitPartial [%p]", this));
 
     mPartialUpdate = true;
+    mClientID = clientID;
     mDocumentURI = aDocumentURI;
 
     mManifestURI = aManifestURI;
     rv = mManifestURI->GetAsciiHost(mUpdateDomain);
     NS_ENSURE_SUCCESS(rv, rv);
 
     nsCOMPtr<nsIApplicationCacheService> cacheService =
         do_GetService(NS_APPLICATIONCACHESERVICE_CONTRACTID, &rv);
     NS_ENSURE_SUCCESS(rv, rv);
 
-    rv = cacheService->GetApplicationCache(clientID,
+    rv = cacheService->GetApplicationCache(mClientID,
                                            getter_AddRefs(mApplicationCache));
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (!mApplicationCache) {
         nsCAutoString manifestSpec;
         rv = GetCacheKey(mManifestURI, manifestSpec);
         NS_ENSURE_SUCCESS(rv, rv);
 
@@ -1591,17 +1625,18 @@ nsOfflineCacheUpdate::Begin()
     }
 
     // Start checking the manifest.
     nsCOMPtr<nsIURI> uri;
 
     mManifestItem = new nsOfflineManifestItem(mManifestURI,
                                               mDocumentURI,
                                               mApplicationCache,
-                                              mPreviousApplicationCache);
+                                              mPreviousApplicationCache,
+                                              mClientID);
     if (!mManifestItem) {
         return NS_ERROR_OUT_OF_MEMORY;
     }
 
     mState = STATE_CHECKING;
     mByteProgress = 0;
     NotifyState(nsIOfflineCacheUpdateObserver::STATE_CHECKING);
 
@@ -1859,22 +1894,18 @@ nsOfflineCacheUpdate::ScheduleImplicit()
     nsRefPtr<nsOfflineCacheUpdate> update = new nsOfflineCacheUpdate();
     NS_ENSURE_TRUE(update, NS_ERROR_OUT_OF_MEMORY);
 
     nsCAutoString clientID;
     if (mPreviousApplicationCache) {
         rv = mPreviousApplicationCache->GetClientID(clientID);
         NS_ENSURE_SUCCESS(rv, rv);
     }
-    else if (mApplicationCache) {
-        rv = mApplicationCache->GetClientID(clientID);
-        NS_ENSURE_SUCCESS(rv, rv);
-    }
     else {
-        NS_ERROR("Offline cache update not having set mApplicationCache?");
+        clientID = mClientID;
     }
 
     rv = update->InitPartial(mManifestURI, clientID, mDocumentURI);
     NS_ENSURE_SUCCESS(rv, rv);
 
     for (PRInt32 i = 0; i < mDocumentURIs.Count(); i++) {
         rv = update->AddURI(mDocumentURIs[i],
               nsIApplicationCache::ITEM_IMPLICIT);
@@ -2102,16 +2133,17 @@ nsOfflineCacheUpdate::AddURI(nsIURI *aUR
         }
     }
 
     nsRefPtr<nsOfflineCacheUpdateItem> item =
         new nsOfflineCacheUpdateItem(aURI, 
                                      mDocumentURI,
                                      mApplicationCache,
                                      mPreviousApplicationCache, 
+                                     mClientID,
                                      aType);
     if (!item) return NS_ERROR_OUT_OF_MEMORY;
 
     mItems.AppendElement(item);
     mAddedItems = true;
 
     return NS_OK;
 }
--- a/uriloader/prefetch/nsOfflineCacheUpdate.h
+++ b/uriloader/prefetch/nsOfflineCacheUpdate.h
@@ -52,23 +52,25 @@ public:
     NS_DECL_NSIRUNNABLE
     NS_DECL_NSIINTERFACEREQUESTOR
     NS_DECL_NSICHANNELEVENTSINK
 
     nsOfflineCacheUpdateItem(nsIURI *aURI,
                              nsIURI *aReferrerURI,
                              nsIApplicationCache *aApplicationCache,
                              nsIApplicationCache *aPreviousApplicationCache,
+                             const nsACString &aClientID,
                              PRUint32 aType);
     virtual ~nsOfflineCacheUpdateItem();
 
     nsCOMPtr<nsIURI>           mURI;
     nsCOMPtr<nsIURI>           mReferrerURI;
     nsCOMPtr<nsIApplicationCache> mApplicationCache;
     nsCOMPtr<nsIApplicationCache> mPreviousApplicationCache;
+    nsCString                  mClientID;
     nsCString                  mCacheKey;
     PRUint32                   mItemType;
 
     nsresult OpenChannel(nsOfflineCacheUpdate *aUpdate);
     nsresult Cancel();
     nsresult GetRequestSucceeded(bool * succeeded);
 
     bool IsInProgress();
@@ -89,17 +91,18 @@ class nsOfflineManifestItem : public nsO
 {
 public:
     NS_DECL_NSISTREAMLISTENER
     NS_DECL_NSIREQUESTOBSERVER
 
     nsOfflineManifestItem(nsIURI *aURI,
                           nsIURI *aReferrerURI,
                           nsIApplicationCache *aApplicationCache,
-                          nsIApplicationCache *aPreviousApplicationCache);
+                          nsIApplicationCache *aPreviousApplicationCache,
+                          const nsACString &aClientID);
     virtual ~nsOfflineManifestItem();
 
     nsCOMArray<nsIURI> &GetExplicitURIs() { return mExplicitURIs; }
     nsCOMArray<nsIURI> &GetFallbackURIs() { return mFallbackURIs; }
 
     nsTArray<nsCString> &GetOpportunisticNamespaces()
         { return mOpportunisticNamespaces; }
     nsIArray *GetNamespaces()
--- a/xpcom/base/VisualEventTracer.cpp
+++ b/xpcom/base/VisualEventTracer.cpp
@@ -5,18 +5,17 @@
 #include "mozilla/VisualEventTracer.h"
 #include "mozilla/Monitor.h"
 #include "mozilla/TimeStamp.h"
 #include "nscore.h"
 #include "prthread.h"
 #include "prprf.h"
 #include "prio.h"
 #include "prenv.h"
-#include "plstr.h"
-#include "nsThreadUtils.h"
+#include "plstr.h"  
 
 namespace mozilla { namespace eventtracer {
 
 #ifdef MOZ_VISUAL_EVENT_TRACER
 
 namespace {
 
 const PRUint32 kBatchSize = 0x1000;
@@ -50,41 +49,25 @@ public:
 
   PRUint32 mType;
   double mTime;
   void * mItem;
   char * mText;
   char * mText2;
 };
 
-char * DupCurrentThreadName()
-{
-  if (NS_IsMainThread())
-    return PL_strdup("Main Thread");
-
-  PRThread * currentThread = PR_GetCurrentThread();
-  const char * name = PR_GetThreadName(currentThread);
-  if (name)
-    return PL_strdup(name);
-
-  char buffer[128];
-  PR_snprintf(buffer, 127, "Nameless %p", currentThread);
-
-  return PL_strdup(buffer);
-}
-
 // An array of events, each thread keeps its own private instance
 class RecordBatch {
 public:
   RecordBatch()
     : mRecordsHead(new Record[kBatchSize])
     , mRecordsTail(mRecordsHead + kBatchSize)
     , mNextRecord(mRecordsHead)
     , mNextBatch(nsnull)
-    , mThreadNameCopy(DupCurrentThreadName())
+    , mThreadNameCopy(PL_strdup(PR_GetThreadName(PR_GetCurrentThread())))
   {
     MOZ_COUNT_CTOR(RecordBatch);
   }
 
   ~RecordBatch()
   {
     delete [] mRecordsHead;
     PL_strfree(mThreadNameCopy);
--- a/xpcom/build/nsXPComInit.cpp
+++ b/xpcom/build/nsXPComInit.cpp
@@ -310,16 +310,18 @@ NS_InitXPCOM(nsIServiceManager* *result,
 
 EXPORT_XPCOM_API(nsresult)
 NS_InitXPCOM2(nsIServiceManager* *result,
               nsIFile* binDirectory,
               nsIDirectoryServiceProvider* appFileLocationProvider)
 {
     NS_TIME_FUNCTION;
 
+    PR_SetCurrentThreadName("Main Thread");
+
     nsresult rv = NS_OK;
 
      // We are not shutting down
     gXPCOMShuttingDown = false;
 
     NS_TIME_FUNCTION_MARK("Next: AvailableMemoryTracker Init()");
 
     // Initialize the available memory tracker before other threads have had a