1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
15 * The Original Code is Startup Cache.
17 * The Initial Developer of the Original Code is
18 * The Mozilla Foundation <http://www.mozilla.org/>.
19 * Portions created by the Initial Developer are Copyright (C) 2009
20 * the Initial Developer. All Rights Reserved.
23 * Benedict Hsieh <bhsieh@mozilla.com>
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
37 * ***** END LICENSE BLOCK ***** */
42 #include "mozilla/scache/StartupCache.h"
44 #include "nsAutoPtr.h"
45 #include "nsClassHashtable.h"
46 #include "nsComponentManagerUtils.h"
47 #include "nsDirectoryServiceUtils.h"
48 #include "nsIClassInfo.h"
50 #include "nsILocalFile.h"
51 #include "nsIObserver.h"
52 #include "nsIObserverService.h"
53 #include "nsIOutputStream.h"
54 #include "nsIStartupCache.h"
55 #include "nsIStorageStream.h"
56 #include "nsIStreamBufferAccess.h"
57 #include "nsIStringStream.h"
58 #include "nsISupports.h"
60 #include "nsIZipWriter.h"
61 #include "nsIZipReader.h"
62 #include "nsWeakReference.h"
63 #include "nsZipArchive.h"
66 #define SC_ENDIAN "big"
68 #define SC_ENDIAN "little"
71 #if PR_BYTES_PER_WORD == 4
72 #define SC_WORDSIZE "4"
74 #define SC_WORDSIZE "8"
80 static const char sStartupCacheName
[] = "startupCache." SC_WORDSIZE
"." SC_ENDIAN
;
81 static NS_DEFINE_CID(kZipReaderCID
, NS_ZIPREADER_CID
);
84 StartupCache::GetSingleton()
87 StartupCache::InitSingleton();
89 return StartupCache::gStartupCache
;
93 StartupCache::DeleteSingleton()
95 delete StartupCache::gStartupCache
;
99 StartupCache::InitSingleton()
102 StartupCache::gStartupCache
= new StartupCache();
104 rv
= StartupCache::gStartupCache
->Init();
106 delete StartupCache::gStartupCache
;
107 StartupCache::gStartupCache
= nsnull
;
112 StartupCache
* StartupCache::gStartupCache
;
113 PRBool
StartupCache::gShutdownInitiated
;
115 StartupCache::StartupCache()
116 : mArchive(NULL
), mStartupWriteInitiated(PR_FALSE
) { }
118 StartupCache::~StartupCache()
124 // Generally, the in-memory table should be empty here,
125 // but in special cases (like Talos Ts tests) we
126 // could shut down before we write.
127 // This mechanism will change when IO is moved off-thread
128 // (bug 586859) or when Talos first-run is changed to allow
129 // our timer to work (bug 591471).
131 gStartupCache
= nsnull
;
140 mWriteObjectMap
.Init();
143 mZipW
= do_CreateInstance("@mozilla.org/zipwriter;1", &rv
);
144 NS_ENSURE_SUCCESS(rv
, rv
);
145 nsCOMPtr
<nsIFile
> file
;
146 rv
= NS_GetSpecialDirectory("ProfLDS",
147 getter_AddRefs(file
));
149 // return silently, this will fail in mochitests's xpcshell process.
153 rv
= file
->AppendNative(NS_LITERAL_CSTRING("startupCache"));
154 NS_ENSURE_SUCCESS(rv
, rv
);
156 // Try to create the directory if it's not there yet
157 rv
= file
->Create(nsIFile::DIRECTORY_TYPE
, 0777);
158 if (NS_FAILED(rv
) && rv
!= NS_ERROR_FILE_ALREADY_EXISTS
)
161 rv
= file
->AppendNative(NS_LITERAL_CSTRING(sStartupCacheName
));
162 NS_ENSURE_SUCCESS(rv
, rv
);
164 mFile
= do_QueryInterface(file
);
165 NS_ENSURE_TRUE(mFile
, NS_ERROR_UNEXPECTED
);
167 mObserverService
= do_GetService("@mozilla.org/observer-service;1");
169 if (!mObserverService
) {
170 NS_WARNING("Could not get observerService.");
171 return NS_ERROR_UNEXPECTED
;
174 mListener
= new StartupCacheListener();
175 rv
= mObserverService
->AddObserver(mListener
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
,
177 NS_ENSURE_SUCCESS(rv
, rv
);
178 rv
= mObserverService
->AddObserver(mListener
, "startupcache-invalidate",
180 NS_ENSURE_SUCCESS(rv
, rv
);
184 // Sometimes we don't have a cache yet, that's ok.
185 // If it's corrupted, just remove it and start over.
186 if (NS_FAILED(rv
) && rv
!= NS_ERROR_FILE_NOT_FOUND
) {
187 NS_WARNING("Failed to load startupcache file correctly, removing!");
191 mTimer
= do_CreateInstance("@mozilla.org/timer;1", &rv
);
192 NS_ENSURE_SUCCESS(rv
, rv
);
193 // Wait for 10 seconds, then write out the cache.
194 rv
= mTimer
->InitWithFuncCallback(StartupCache::WriteTimeout
, this, 600000,
195 nsITimer::TYPE_ONE_SHOT
);
201 StartupCache::LoadArchive()
205 nsresult rv
= mFile
->Exists(&exists
);
206 if (NS_FAILED(rv
) || !exists
)
207 return NS_ERROR_FILE_NOT_FOUND
;
209 mArchive
= new nsZipArchive();
210 return mArchive
->OpenArchive(mFile
);
213 // NOTE: this will not find a new entry until it has been written to disk!
214 // Consumer should take ownership of the resulting buffer.
216 StartupCache::GetBuffer(const char* id
, char** outbuf
, PRUint32
* length
)
221 if (!mStartupWriteInitiated
) {
223 nsDependentCString
idStr(id
);
224 mTable
.Get(idStr
, &entry
);
231 if (!data
&& mArchive
) {
232 nsZipItem
* zipItem
= mArchive
->GetItem(id
);
234 const PRUint8
* itemData
= mArchive
->GetData(zipItem
);
235 if (!itemData
|| !mArchive
->CheckCRC(zipItem
, itemData
)) {
236 NS_WARNING("StartupCache file corrupted!");
238 return NS_ERROR_FILE_CORRUPTED
;
241 len
= zipItem
->Size();
242 data
= (char*) itemData
;
247 *outbuf
= new char[len
];
248 memcpy(*outbuf
, data
, len
);
253 return NS_ERROR_NOT_AVAILABLE
;
256 // Makes a copy of the buffer, client retains ownership of inbuf.
258 StartupCache::PutBuffer(const char* id
, const char* inbuf
, PRUint32 len
)
262 if (StartupCache::gShutdownInitiated
) {
263 return NS_ERROR_NOT_AVAILABLE
;
266 nsAutoArrayPtr
<char> data(new char[len
]);
267 memcpy(data
, inbuf
, len
);
269 nsDependentCString
idStr(id
);
270 if (!mStartupWriteInitiated
) {
271 // Cache it for now, we'll write all together later.
275 mTable
.Get(idStr
, &entry
);
276 NS_ASSERTION(entry
== nsnull
, "Existing entry in StartupCache.");
279 nsZipItem
* zipItem
= mArchive
->GetItem(id
);
280 NS_ASSERTION(zipItem
== nsnull
, "Existing entry in disk StartupCache.");
284 entry
= new CacheEntry(data
.forget(), len
);
285 mTable
.Put(idStr
, entry
);
289 rv
= mZipW
->Open(mFile
, PR_RDWR
| PR_CREATE_FILE
);
290 NS_ENSURE_SUCCESS(rv
, rv
);
292 // XXX We need to think about whether to write this out every time,
293 // or somehow detect a good time to write. We need to finish writing
294 // before shutdown though, and writing also requires a reload of the
295 // reader's archive, which probably can't handle having the underlying
296 // file change underneath it. Potentially could reload on the next
297 // read request, if this is a problem. See Bug 586859.
300 rv
= mZipW
->HasEntry(idStr
, &hasEntry
);
301 NS_ENSURE_SUCCESS(rv
, rv
);
302 NS_ASSERTION(hasEntry
== PR_FALSE
, "Existing entry in disk StartupCache.");
305 nsCOMPtr
<nsIStringInputStream
> stream
306 = do_CreateInstance("@mozilla.org/io/string-input-stream;1",
308 NS_ENSURE_SUCCESS(rv
, rv
);
310 rv
= stream
->AdoptData(data
, len
);
311 NS_ENSURE_SUCCESS(rv
, rv
);
314 rv
= mZipW
->AddEntryStream(idStr
, 0, 0, stream
, false);
315 NS_ENSURE_SUCCESS(rv
, rv
);
317 // Close the archive so Windows doesn't choke.
320 NS_ENSURE_SUCCESS(rv
, rv
);
322 // our reader's view of the archive is outdated now, reload it.
323 return LoadArchive();
326 struct CacheWriteHolder
328 nsCOMPtr
<nsIZipWriter
> writer
;
329 nsCOMPtr
<nsIStringInputStream
> stream
;
333 CacheCloseHelper(const nsACString
& key
, nsAutoPtr
<CacheEntry
>& data
,
338 CacheWriteHolder
* holder
= (CacheWriteHolder
*) closure
;
339 nsIStringInputStream
* stream
= holder
->stream
;
340 nsIZipWriter
* writer
= holder
->writer
;
342 stream
->ShareData(data
->data
, data
->size
);
346 rv
= writer
->HasEntry(key
, &hasEntry
);
347 NS_ASSERTION(NS_SUCCEEDED(rv
) && hasEntry
== PR_FALSE
,
348 "Existing entry in disk StartupCache.");
350 rv
= writer
->AddEntryStream(key
, 0, 0, stream
, false);
353 NS_WARNING("cache entry deleted but not written to disk.");
355 return PL_DHASH_REMOVE
;
359 StartupCache::WriteToDisk()
362 mStartupWriteInitiated
= PR_TRUE
;
364 if (mTable
.Count() == 0)
367 rv
= mZipW
->Open(mFile
, PR_RDWR
| PR_CREATE_FILE
);
369 NS_WARNING("could not open zipfile for write");
373 nsCOMPtr
<nsIStringInputStream
> stream
374 = do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv
);
376 NS_WARNING("Couldn't create string input stream.");
380 CacheWriteHolder holder
;
381 holder
.stream
= stream
;
382 holder
.writer
= mZipW
;
384 mTable
.Enumerate(CacheCloseHelper
, &holder
);
386 // Close the archive so Windows doesn't choke.
390 // our reader's view of the archive is outdated now, reload it.
397 StartupCache::InvalidateCache()
402 // This is usually closed, but it's possible to get into
403 // an inconsistent state.
405 mFile
->Remove(false);
410 StartupCache::WriteTimeout(nsITimer
*aTimer
, void *aClosure
)
412 StartupCache
* sc
= (StartupCache
*) aClosure
;
416 // We don't want to refcount StartupCache, so we'll just
417 // hold a ref to this and pass it to observerService instead.
418 NS_IMPL_THREADSAFE_ISUPPORTS1(StartupCacheListener
, nsIObserver
)
421 StartupCacheListener::Observe(nsISupports
*subject
, const char* topic
, const PRUnichar
* data
)
424 if (strcmp(topic
, NS_XPCOM_SHUTDOWN_OBSERVER_ID
) == 0) {
425 StartupCache::gShutdownInitiated
= PR_TRUE
;
426 } else if (strcmp(topic
, "startupcache-invalidate") == 0) {
427 StartupCache
* sc
= StartupCache::GetSingleton();
429 sc
->InvalidateCache();
435 StartupCache::GetDebugObjectOutputStream(nsIObjectOutputStream
* aStream
,
436 nsIObjectOutputStream
** aOutStream
)
438 NS_ENSURE_ARG_POINTER(aStream
);
440 StartupCacheDebugOutputStream
* stream
441 = new StartupCacheDebugOutputStream(aStream
, &mWriteObjectMap
);
442 NS_ADDREF(*aOutStream
= stream
);
444 NS_ADDREF(*aOutStream
= aStream
);
450 // StartupCacheDebugOutputStream implementation
452 NS_IMPL_ISUPPORTS3(StartupCacheDebugOutputStream
, nsIObjectOutputStream
,
453 nsIBinaryOutputStream
, nsIOutputStream
)
456 StartupCacheDebugOutputStream::CheckReferences(nsISupports
* aObject
)
460 nsCOMPtr
<nsIClassInfo
> classInfo
= do_QueryInterface(aObject
);
462 NS_ERROR("aObject must implement nsIClassInfo");
467 rv
= classInfo
->GetFlags(&flags
);
468 NS_ENSURE_SUCCESS(rv
, rv
);
469 if (flags
& nsIClassInfo::SINGLETON
)
472 nsISupportsHashKey
* key
= mObjectMap
->GetEntry(aObject
);
474 NS_ERROR("non-singleton aObject is referenced multiple times in this"
475 "serialization, we don't support that.");
479 mObjectMap
->PutEntry(aObject
);
483 // nsIObjectOutputStream implementation
485 StartupCacheDebugOutputStream::WriteObject(nsISupports
* aObject
, PRBool aIsStrongRef
)
489 nsCOMPtr
<nsISupports
> rootObject(do_QueryInterface(aObject
));
491 NS_ASSERTION(rootObject
.get() == aObject
,
492 "bad call to WriteObject -- call WriteCompoundObject!");
493 PRBool check
= CheckReferences(aObject
);
494 NS_ENSURE_TRUE(check
, NS_ERROR_FAILURE
);
495 return mBinaryStream
->WriteObject(aObject
, aIsStrongRef
);
499 StartupCacheDebugOutputStream::WriteSingleRefObject(nsISupports
* aObject
)
502 nsCOMPtr
<nsISupports
> rootObject(do_QueryInterface(aObject
));
504 NS_ASSERTION(rootObject
.get() == aObject
,
505 "bad call to WriteSingleRefObject -- call WriteCompoundObject!");
506 PRBool check
= CheckReferences(aObject
);
507 NS_ENSURE_TRUE(check
, NS_ERROR_FAILURE
);
508 return mBinaryStream
->WriteSingleRefObject(aObject
);
512 StartupCacheDebugOutputStream::WriteCompoundObject(nsISupports
* aObject
,
517 nsCOMPtr
<nsISupports
> rootObject(do_QueryInterface(aObject
));
519 nsCOMPtr
<nsISupports
> roundtrip
;
520 rootObject
->QueryInterface(aIID
, getter_AddRefs(roundtrip
));
521 NS_ASSERTION(roundtrip
.get() == aObject
,
522 "bad aggregation or multiple inheritance detected by call to "
523 "WriteCompoundObject!");
525 PRBool check
= CheckReferences(aObject
);
526 NS_ENSURE_TRUE(check
, NS_ERROR_FAILURE
);
527 return mBinaryStream
->WriteCompoundObject(aObject
, aIID
, aIsStrongRef
);
531 StartupCacheDebugOutputStream::WriteID(nsID
const& aID
)
533 return mBinaryStream
->WriteID(aID
);
537 StartupCacheDebugOutputStream::GetBuffer(PRUint32 aLength
, PRUint32 aAlignMask
)
539 return mBinaryStream
->GetBuffer(aLength
, aAlignMask
);
543 StartupCacheDebugOutputStream::PutBuffer(char* aBuffer
, PRUint32 aLength
)
545 mBinaryStream
->PutBuffer(aBuffer
, aLength
);
549 StartupCacheWrapper
* StartupCacheWrapper::gStartupCacheWrapper
= nsnull
;
551 NS_IMPL_THREADSAFE_ISUPPORTS1(StartupCacheWrapper
, nsIStartupCache
)
553 StartupCacheWrapper
* StartupCacheWrapper::GetSingleton()
555 if (!gStartupCacheWrapper
)
556 gStartupCacheWrapper
= new StartupCacheWrapper();
558 NS_ADDREF(gStartupCacheWrapper
);
559 return gStartupCacheWrapper
;
563 StartupCacheWrapper::GetBuffer(const char* id
, char** outbuf
, PRUint32
* length
)
565 StartupCache
* sc
= StartupCache::GetSingleton();
567 return NS_ERROR_NOT_INITIALIZED
;
569 return sc
->GetBuffer(id
, outbuf
, length
);
573 StartupCacheWrapper::PutBuffer(const char* id
, char* inbuf
, PRUint32 length
)
575 StartupCache
* sc
= StartupCache::GetSingleton();
577 return NS_ERROR_NOT_INITIALIZED
;
579 return sc
->PutBuffer(id
, inbuf
, length
);
583 StartupCacheWrapper::InvalidateCache()
585 StartupCache
* sc
= StartupCache::GetSingleton();
587 return NS_ERROR_NOT_INITIALIZED
;
589 sc
->InvalidateCache();
594 StartupCacheWrapper::GetDebugObjectOutputStream(nsIObjectOutputStream
* stream
,
595 nsIObjectOutputStream
** outStream
)
597 StartupCache
* sc
= StartupCache::GetSingleton();
599 return NS_ERROR_NOT_INITIALIZED
;
601 return sc
->GetDebugObjectOutputStream(stream
, outStream
);
605 StartupCacheWrapper::StartupWriteComplete(PRBool
*complete
)
607 StartupCache
* sc
= StartupCache::GetSingleton();
609 return NS_ERROR_NOT_INITIALIZED
;
611 *complete
= sc
->mStartupWriteInitiated
&& sc
->mTable
.Count() == 0;
616 StartupCacheWrapper::ResetStartupWriteTimer()
618 StartupCache
* sc
= StartupCache::GetSingleton();
620 return NS_ERROR_NOT_INITIALIZED
;
622 sc
->mStartupWriteInitiated
= PR_FALSE
;
624 // Init with a shorter timer, for testing convenience.
625 sc
->mTimer
->Cancel();
626 sc
->mTimer
->InitWithFuncCallback(StartupCache::WriteTimeout
, sc
, 10000,
627 nsITimer::TYPE_ONE_SHOT
);
632 StartupCacheWrapper::GetObserver(nsIObserver
** obv
) {
633 StartupCache
* sc
= StartupCache::GetSingleton();
635 return NS_ERROR_NOT_INITIALIZED
;
637 NS_ADDREF(*obv
= sc
->mListener
);
641 } // namespace scache
642 } // namespace mozilla