1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "ScriptPreloader-inl.h"
8 #include "mozilla/URLPreloader.h"
9 #include "mozilla/loader/AutoMemMap.h"
10
11 #include "mozilla/ArrayUtils.h"
12 #include "mozilla/ClearOnShutdown.h"
13 #include "mozilla/FileUtils.h"
14 #include "mozilla/IOBuffers.h"
15 #include "mozilla/Logging.h"
16 #include "mozilla/ScopeExit.h"
17 #include "mozilla/Services.h"
18 #include "mozilla/Unused.h"
19 #include "mozilla/Vector.h"
20
21 #include "MainThreadUtils.h"
22 #include "nsPrintfCString.h"
23 #include "nsDebug.h"
24 #include "nsIFile.h"
25 #include "nsIFileURL.h"
26 #include "nsNetUtil.h"
27 #include "nsPromiseFlatString.h"
28 #include "nsProxyRelease.h"
29 #include "nsThreadUtils.h"
30 #include "nsXULAppAPI.h"
31 #include "nsZipArchive.h"
32 #include "xpcpublic.h"
33
34 namespace mozilla {
35 namespace {
36 static LazyLogModule gURLLog("URLPreloader");
37
38 #define LOG(level, ...) MOZ_LOG(gURLLog, LogLevel::level, (__VA_ARGS__))
39
40 template <typename T>
StartsWith(const T & haystack,const T & needle)41 bool StartsWith(const T& haystack, const T& needle) {
42 return StringHead(haystack, needle.Length()) == needle;
43 }
44 } // anonymous namespace
45
46 using namespace mozilla::loader;
47
CollectReports(nsIHandleReportCallback * aHandleReport,nsISupports * aData,bool aAnonymize)48 nsresult URLPreloader::CollectReports(nsIHandleReportCallback* aHandleReport,
49 nsISupports* aData, bool aAnonymize) {
50 MOZ_COLLECT_REPORT("explicit/url-preloader/other", KIND_HEAP, UNITS_BYTES,
51 ShallowSizeOfIncludingThis(MallocSizeOf),
52 "Memory used by the URL preloader service itself.");
53
54 for (const auto& elem : mCachedURLs.Values()) {
55 nsAutoCString pathName;
56 pathName.Append(elem->mPath);
57 // The backslashes will automatically be replaced with slashes in
58 // about:memory, without splitting each path component into a separate
59 // branch in the memory report tree.
60 pathName.ReplaceChar('/', '\\');
61
62 nsPrintfCString path("explicit/url-preloader/cached-urls/%s/[%s]",
63 elem->TypeString(), pathName.get());
64
65 aHandleReport->Callback(
66 ""_ns, path, KIND_HEAP, UNITS_BYTES,
67 elem->SizeOfIncludingThis(MallocSizeOf),
68 nsLiteralCString("Memory used to hold cache data for files which "
69 "have been read or pre-loaded during this session."),
70 aData);
71 }
72
73 return NS_OK;
74 }
75
76 // static
Create(bool * aInitialized)77 already_AddRefed<URLPreloader> URLPreloader::Create(bool* aInitialized) {
78 // The static APIs like URLPreloader::Read work in the child process because
79 // they fall back to a synchronous read. The actual preloader must be
80 // explicitly initialized, and this should only be done in the parent.
81 MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
82
83 RefPtr<URLPreloader> preloader = new URLPreloader();
84 if (preloader->InitInternal().isOk()) {
85 *aInitialized = true;
86 RegisterWeakMemoryReporter(preloader);
87 } else {
88 *aInitialized = false;
89 }
90
91 return preloader.forget();
92 }
93
GetSingleton()94 URLPreloader& URLPreloader::GetSingleton() {
95 if (!sSingleton) {
96 sSingleton = Create(&sInitialized);
97 ClearOnShutdown(&sSingleton);
98 }
99
100 return *sSingleton;
101 }
102
103 bool URLPreloader::sInitialized = false;
104
105 StaticRefPtr<URLPreloader> URLPreloader::sSingleton;
106
~URLPreloader()107 URLPreloader::~URLPreloader() {
108 if (sInitialized) {
109 UnregisterWeakMemoryReporter(this);
110 sInitialized = false;
111 }
112 }
113
InitInternal()114 Result<Ok, nsresult> URLPreloader::InitInternal() {
115 MOZ_RELEASE_ASSERT(NS_IsMainThread());
116
117 if (Omnijar::HasOmnijar(Omnijar::GRE)) {
118 MOZ_TRY(Omnijar::GetURIString(Omnijar::GRE, mGREPrefix));
119 }
120 if (Omnijar::HasOmnijar(Omnijar::APP)) {
121 MOZ_TRY(Omnijar::GetURIString(Omnijar::APP, mAppPrefix));
122 }
123
124 nsresult rv;
125 nsCOMPtr<nsIIOService> ios = do_GetIOService(&rv);
126 MOZ_TRY(rv);
127
128 nsCOMPtr<nsIProtocolHandler> ph;
129 MOZ_TRY(ios->GetProtocolHandler("resource", getter_AddRefs(ph)));
130
131 mResProto = do_QueryInterface(ph, &rv);
132 MOZ_TRY(rv);
133
134 mChromeReg = services::GetChromeRegistry();
135 if (!mChromeReg) {
136 return Err(NS_ERROR_UNEXPECTED);
137 }
138
139 MOZ_TRY(NS_GetSpecialDirectory("ProfLDS", getter_AddRefs(mProfD)));
140
141 return Ok();
142 }
143
ReInitialize()144 URLPreloader& URLPreloader::ReInitialize() {
145 MOZ_ASSERT(sSingleton);
146 sSingleton = nullptr;
147 sSingleton = Create(&sInitialized);
148 return *sSingleton;
149 }
150
GetCacheFile(const nsAString & suffix)151 Result<nsCOMPtr<nsIFile>, nsresult> URLPreloader::GetCacheFile(
152 const nsAString& suffix) {
153 if (!mProfD) {
154 return Err(NS_ERROR_NOT_INITIALIZED);
155 }
156
157 nsCOMPtr<nsIFile> cacheFile;
158 MOZ_TRY(mProfD->Clone(getter_AddRefs(cacheFile)));
159
160 MOZ_TRY(cacheFile->AppendNative("startupCache"_ns));
161 Unused << cacheFile->Create(nsIFile::DIRECTORY_TYPE, 0777);
162
163 MOZ_TRY(cacheFile->Append(u"urlCache"_ns + suffix));
164
165 return std::move(cacheFile);
166 }
167
168 static const uint8_t URL_MAGIC[] = "mozURLcachev002";
169
FindCacheFile()170 Result<nsCOMPtr<nsIFile>, nsresult> URLPreloader::FindCacheFile() {
171 nsCOMPtr<nsIFile> cacheFile;
172 MOZ_TRY_VAR(cacheFile, GetCacheFile(u".bin"_ns));
173
174 bool exists;
175 MOZ_TRY(cacheFile->Exists(&exists));
176 if (exists) {
177 MOZ_TRY(cacheFile->MoveTo(nullptr, u"urlCache-current.bin"_ns));
178 } else {
179 MOZ_TRY(cacheFile->SetLeafName(u"urlCache-current.bin"_ns));
180 MOZ_TRY(cacheFile->Exists(&exists));
181 if (!exists) {
182 return Err(NS_ERROR_FILE_NOT_FOUND);
183 }
184 }
185
186 return std::move(cacheFile);
187 }
188
WriteCache()189 Result<Ok, nsresult> URLPreloader::WriteCache() {
190 MOZ_ASSERT(!NS_IsMainThread());
191 MOZ_DIAGNOSTIC_ASSERT(mStartupFinished);
192
193 // The script preloader might call us a second time, if it has to re-write
194 // its cache after a cache flush. We don't care about cache flushes, since
195 // our cache doesn't store any file data, only paths. And we currently clear
196 // our cached file list after the first write, which means that a second
197 // write would (aside from breaking the invariant that we never touch
198 // mCachedURLs off-main-thread after the first write, and trigger a data
199 // race) mean we get no pre-loading on the next startup.
200 if (mCacheWritten) {
201 return Ok();
202 }
203 mCacheWritten = true;
204
205 LOG(Debug, "Writing cache...");
206
207 nsCOMPtr<nsIFile> cacheFile;
208 MOZ_TRY_VAR(cacheFile, GetCacheFile(u"-new.bin"_ns));
209
210 bool exists;
211 MOZ_TRY(cacheFile->Exists(&exists));
212 if (exists) {
213 MOZ_TRY(cacheFile->Remove(false));
214 }
215
216 {
217 AutoFDClose fd;
218 MOZ_TRY(cacheFile->OpenNSPRFileDesc(PR_WRONLY | PR_CREATE_FILE, 0644,
219 &fd.rwget()));
220
221 nsTArray<URLEntry*> entries;
222 for (const auto& entry : mCachedURLs.Values()) {
223 if (entry->mReadTime) {
224 entries.AppendElement(entry.get());
225 }
226 }
227
228 entries.Sort(URLEntry::Comparator());
229
230 OutputBuffer buf;
231 for (auto entry : entries) {
232 entry->Code(buf);
233 }
234
235 uint8_t headerSize[4];
236 LittleEndian::writeUint32(headerSize, buf.cursor());
237
238 MOZ_TRY(Write(fd, URL_MAGIC, sizeof(URL_MAGIC)));
239 MOZ_TRY(Write(fd, headerSize, sizeof(headerSize)));
240 MOZ_TRY(Write(fd, buf.Get(), buf.cursor()));
241 }
242
243 MOZ_TRY(cacheFile->MoveTo(nullptr, u"urlCache.bin"_ns));
244
245 NS_DispatchToMainThread(
246 NewRunnableMethod("URLPreloader::Cleanup", this, &URLPreloader::Cleanup));
247
248 return Ok();
249 }
250
Cleanup()251 void URLPreloader::Cleanup() { mCachedURLs.Clear(); }
252
ReadCache(LinkedList<URLEntry> & pendingURLs)253 Result<Ok, nsresult> URLPreloader::ReadCache(
254 LinkedList<URLEntry>& pendingURLs) {
255 LOG(Debug, "Reading cache...");
256
257 nsCOMPtr<nsIFile> cacheFile;
258 MOZ_TRY_VAR(cacheFile, FindCacheFile());
259
260 AutoMemMap cache;
261 MOZ_TRY(cache.init(cacheFile));
262
263 auto size = cache.size();
264
265 uint32_t headerSize;
266 if (size < sizeof(URL_MAGIC) + sizeof(headerSize)) {
267 return Err(NS_ERROR_UNEXPECTED);
268 }
269
270 auto data = cache.get<uint8_t>();
271 auto end = data + size;
272
273 if (memcmp(URL_MAGIC, data.get(), sizeof(URL_MAGIC))) {
274 return Err(NS_ERROR_UNEXPECTED);
275 }
276 data += sizeof(URL_MAGIC);
277
278 headerSize = LittleEndian::readUint32(data.get());
279 data += sizeof(headerSize);
280
281 if (data + headerSize > end) {
282 return Err(NS_ERROR_UNEXPECTED);
283 }
284
285 {
286 mMonitor.AssertCurrentThreadOwns();
287
288 auto cleanup = MakeScopeExit([&]() {
289 while (auto* elem = pendingURLs.getFirst()) {
290 elem->remove();
291 }
292 mCachedURLs.Clear();
293 });
294
295 Range<uint8_t> header(data, data + headerSize);
296 data += headerSize;
297
298 InputBuffer buf(header);
299 while (!buf.finished()) {
300 CacheKey key(buf);
301
302 LOG(Debug, "Cached file: %s %s", key.TypeString(), key.mPath.get());
303
304 auto entry = mCachedURLs.GetOrInsertNew(key, key);
305 entry->mResultCode = NS_ERROR_NOT_INITIALIZED;
306
307 if (entry->isInList()) {
308 MOZ_DIAGNOSTIC_ASSERT(false, "Entry should be new and not in any list");
309 return Err(NS_ERROR_UNEXPECTED);
310 }
311
312 pendingURLs.insertBack(entry);
313 }
314
315 if (buf.error()) {
316 return Err(NS_ERROR_UNEXPECTED);
317 }
318
319 cleanup.release();
320 }
321
322 return Ok();
323 }
324
BackgroundReadFiles()325 void URLPreloader::BackgroundReadFiles() {
326 auto cleanup = MakeScopeExit([&]() {
327 auto lock = mReaderThread.Lock();
328 auto& readerThread = lock.ref();
329 NS_DispatchToMainThread(NewRunnableMethod(
330 "nsIThread::AsyncShutdown", readerThread, &nsIThread::AsyncShutdown));
331
332 readerThread = nullptr;
333 });
334
335 Vector<nsZipCursor> cursors;
336 LinkedList<URLEntry> pendingURLs;
337 {
338 MonitorAutoLock mal(mMonitor);
339
340 if (ReadCache(pendingURLs).isErr()) {
341 mReaderInitialized = true;
342 mal.NotifyAll();
343 return;
344 }
345
346 int numZipEntries = 0;
347 for (auto entry : pendingURLs) {
348 if (entry->mType != entry->TypeFile) {
349 numZipEntries++;
350 }
351 }
352 MOZ_RELEASE_ASSERT(cursors.reserve(numZipEntries));
353
354 // Initialize the zip cursors for all files in Omnijar while the monitor
355 // is locked. Omnijar is not threadsafe, so the caller of
356 // AutoBeginReading guard must ensure that no code accesses Omnijar
357 // until this segment is done. Once the cursors have been initialized,
358 // the actual reading and decompression can safely be done off-thread,
359 // as is the case for thread-retargeted jar: channels.
360 for (auto entry : pendingURLs) {
361 if (entry->mType == entry->TypeFile) {
362 continue;
363 }
364
365 RefPtr<nsZipArchive> zip = entry->Archive();
366 if (!zip) {
367 MOZ_CRASH_UNSAFE_PRINTF(
368 "Failed to get Omnijar %s archive for entry (path: \"%s\")",
369 entry->TypeString(), entry->mPath.get());
370 }
371
372 auto item = zip->GetItem(entry->mPath.get());
373 if (!item) {
374 entry->mResultCode = NS_ERROR_FILE_NOT_FOUND;
375 continue;
376 }
377
378 size_t size = item->RealSize();
379
380 entry->mData.SetLength(size);
381 auto data = entry->mData.BeginWriting();
382
383 cursors.infallibleEmplaceBack(item, zip, reinterpret_cast<uint8_t*>(data),
384 size, true);
385 }
386
387 mReaderInitialized = true;
388 mal.NotifyAll();
389 }
390
391 // Loop over the entries, read the file's contents, store them in the
392 // entry's mData pointer, and notify any waiting threads to check for
393 // completion.
394 uint32_t i = 0;
395 for (auto entry : pendingURLs) {
396 // If there is any other error code, the entry has already failed at
397 // this point, so don't bother trying to read it again.
398 if (entry->mResultCode != NS_ERROR_NOT_INITIALIZED) {
399 continue;
400 }
401
402 nsresult rv = NS_OK;
403
404 LOG(Debug, "Background reading %s file %s", entry->TypeString(),
405 entry->mPath.get());
406
407 if (entry->mType == entry->TypeFile) {
408 auto result = entry->Read();
409 if (result.isErr()) {
410 rv = result.unwrapErr();
411 }
412 } else {
413 auto& cursor = cursors[i++];
414
415 uint32_t len;
416 cursor.Copy(&len);
417 if (len != entry->mData.Length()) {
418 entry->mData.Truncate();
419 rv = NS_ERROR_FAILURE;
420 }
421 }
422
423 entry->mResultCode = rv;
424 mMonitor.NotifyAll();
425 }
426
427 // We're done reading pending entries, so clear the list.
428 pendingURLs.clear();
429 }
430
BeginBackgroundRead()431 void URLPreloader::BeginBackgroundRead() {
432 auto lock = mReaderThread.Lock();
433 auto& readerThread = lock.ref();
434 if (!readerThread && !mReaderInitialized && sInitialized) {
435 nsresult rv;
436 rv = NS_NewNamedThread("BGReadURLs", getter_AddRefs(readerThread));
437 if (NS_WARN_IF(NS_FAILED(rv))) {
438 return;
439 }
440
441 nsCOMPtr<nsIRunnable> runnable =
442 NewRunnableMethod("URLPreloader::BackgroundReadFiles", this,
443 &URLPreloader::BackgroundReadFiles);
444 rv = readerThread->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL);
445 if (NS_WARN_IF(NS_FAILED(rv))) {
446 // If we can't launch the task, just destroy the thread
447 readerThread = nullptr;
448 return;
449 }
450 }
451 }
452
ReadInternal(const CacheKey & key,ReadType readType)453 Result<nsCString, nsresult> URLPreloader::ReadInternal(const CacheKey& key,
454 ReadType readType) {
455 if (mStartupFinished || !mReaderInitialized) {
456 URLEntry entry(key);
457
458 return entry.Read();
459 }
460
461 auto entry = mCachedURLs.GetOrInsertNew(key, key);
462
463 entry->UpdateUsedTime();
464
465 return entry->ReadOrWait(readType);
466 }
467
ReadURIInternal(nsIURI * uri,ReadType readType)468 Result<nsCString, nsresult> URLPreloader::ReadURIInternal(nsIURI* uri,
469 ReadType readType) {
470 CacheKey key;
471 MOZ_TRY_VAR(key, ResolveURI(uri));
472
473 return ReadInternal(key, readType);
474 }
475
Read(const CacheKey & key,ReadType readType)476 /* static */ Result<nsCString, nsresult> URLPreloader::Read(const CacheKey& key,
477 ReadType readType) {
478 // If we're being called before the preloader has been initialized (i.e.,
479 // before the profile has been initialized), just fall back to a synchronous
480 // read. This happens when we're reading .ini and preference files that are
481 // needed to locate and initialize the profile.
482 if (!sInitialized) {
483 return URLEntry(key).Read();
484 }
485
486 return GetSingleton().ReadInternal(key, readType);
487 }
488
ReadURI(nsIURI * uri,ReadType readType)489 /* static */ Result<nsCString, nsresult> URLPreloader::ReadURI(
490 nsIURI* uri, ReadType readType) {
491 if (!sInitialized) {
492 return Err(NS_ERROR_NOT_INITIALIZED);
493 }
494
495 return GetSingleton().ReadURIInternal(uri, readType);
496 }
497
ReadFile(nsIFile * file,ReadType readType)498 /* static */ Result<nsCString, nsresult> URLPreloader::ReadFile(
499 nsIFile* file, ReadType readType) {
500 return Read(CacheKey(file), readType);
501 }
502
Read(FileLocation & location,ReadType readType)503 /* static */ Result<nsCString, nsresult> URLPreloader::Read(
504 FileLocation& location, ReadType readType) {
505 if (location.IsZip()) {
506 if (location.GetBaseZip()) {
507 nsCString path;
508 location.GetPath(path);
509 return ReadZip(location.GetBaseZip(), path);
510 }
511 return URLEntry::ReadLocation(location);
512 }
513
514 nsCOMPtr<nsIFile> file = location.GetBaseFile();
515 return ReadFile(file, readType);
516 }
517
ReadZip(nsZipArchive * zip,const nsACString & path,ReadType readType)518 /* static */ Result<nsCString, nsresult> URLPreloader::ReadZip(
519 nsZipArchive* zip, const nsACString& path, ReadType readType) {
520 // If the zip archive belongs to an Omnijar location, map it to a cache
521 // entry, and cache it as normal. Otherwise, simply read the entry
522 // synchronously, since other JAR archives are currently unsupported by the
523 // cache.
524 RefPtr<nsZipArchive> reader = Omnijar::GetReader(Omnijar::GRE);
525 if (zip == reader) {
526 CacheKey key(CacheKey::TypeGREJar, path);
527 return Read(key, readType);
528 }
529
530 reader = Omnijar::GetReader(Omnijar::APP);
531 if (zip == reader) {
532 CacheKey key(CacheKey::TypeAppJar, path);
533 return Read(key, readType);
534 }
535
536 // Not an Omnijar archive, so just read it directly.
537 FileLocation location(zip, PromiseFlatCString(path).BeginReading());
538 return URLEntry::ReadLocation(location);
539 }
540
ResolveURI(nsIURI * uri)541 Result<URLPreloader::CacheKey, nsresult> URLPreloader::ResolveURI(nsIURI* uri) {
542 nsCString spec;
543 nsCString scheme;
544 MOZ_TRY(uri->GetSpec(spec));
545 MOZ_TRY(uri->GetScheme(scheme));
546
547 nsCOMPtr<nsIURI> resolved;
548
549 // If the URI is a resource: or chrome: URI, first resolve it to the
550 // underlying URI that it wraps.
551 if (scheme.EqualsLiteral("resource")) {
552 MOZ_TRY(mResProto->ResolveURI(uri, spec));
553 MOZ_TRY(NS_NewURI(getter_AddRefs(resolved), spec));
554 } else if (scheme.EqualsLiteral("chrome")) {
555 MOZ_TRY(mChromeReg->ConvertChromeURL(uri, getter_AddRefs(resolved)));
556 MOZ_TRY(resolved->GetSpec(spec));
557 } else {
558 resolved = uri;
559 }
560 MOZ_TRY(resolved->GetScheme(scheme));
561
562 // Try the GRE and App Omnijar prefixes.
563 if (mGREPrefix.Length() && StartsWith(spec, mGREPrefix)) {
564 return CacheKey(CacheKey::TypeGREJar, Substring(spec, mGREPrefix.Length()));
565 }
566
567 if (mAppPrefix.Length() && StartsWith(spec, mAppPrefix)) {
568 return CacheKey(CacheKey::TypeAppJar, Substring(spec, mAppPrefix.Length()));
569 }
570
571 // Try for a file URI.
572 if (scheme.EqualsLiteral("file")) {
573 nsCOMPtr<nsIFileURL> fileURL = do_QueryInterface(resolved);
574 MOZ_ASSERT(fileURL);
575
576 nsCOMPtr<nsIFile> file;
577 MOZ_TRY(fileURL->GetFile(getter_AddRefs(file)));
578
579 nsString path;
580 MOZ_TRY(file->GetPath(path));
581
582 return CacheKey(CacheKey::TypeFile, NS_ConvertUTF16toUTF8(path));
583 }
584
585 // Not a file or Omnijar URI, so currently unsupported.
586 return Err(NS_ERROR_INVALID_ARG);
587 }
588
ShallowSizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf)589 size_t URLPreloader::ShallowSizeOfIncludingThis(
590 mozilla::MallocSizeOf mallocSizeOf) {
591 return (mallocSizeOf(this) +
592 mAppPrefix.SizeOfExcludingThisEvenIfShared(mallocSizeOf) +
593 mGREPrefix.SizeOfExcludingThisEvenIfShared(mallocSizeOf) +
594 mCachedURLs.ShallowSizeOfExcludingThis(mallocSizeOf));
595 }
596
ToFileLocation()597 Result<FileLocation, nsresult> URLPreloader::CacheKey::ToFileLocation() {
598 if (mType == TypeFile) {
599 nsCOMPtr<nsIFile> file;
600 MOZ_TRY(NS_NewLocalFile(NS_ConvertUTF8toUTF16(mPath), false,
601 getter_AddRefs(file)));
602 return FileLocation(file);
603 }
604
605 RefPtr<nsZipArchive> zip = Archive();
606 return FileLocation(zip, mPath.get());
607 }
608
Read()609 Result<nsCString, nsresult> URLPreloader::URLEntry::Read() {
610 FileLocation location;
611 MOZ_TRY_VAR(location, ToFileLocation());
612
613 MOZ_TRY_VAR(mData, ReadLocation(location));
614 return mData;
615 }
616
ReadLocation(FileLocation & location)617 /* static */ Result<nsCString, nsresult> URLPreloader::URLEntry::ReadLocation(
618 FileLocation& location) {
619 FileLocation::Data data;
620 MOZ_TRY(location.GetData(data));
621
622 uint32_t size;
623 MOZ_TRY(data.GetSize(&size));
624
625 nsCString result;
626 result.SetLength(size);
627 MOZ_TRY(data.Copy(result.BeginWriting(), size));
628
629 return std::move(result);
630 }
631
ReadOrWait(ReadType readType)632 Result<nsCString, nsresult> URLPreloader::URLEntry::ReadOrWait(
633 ReadType readType) {
634 auto now = TimeStamp::Now();
635 LOG(Info, "Reading %s\n", mPath.get());
636 auto cleanup = MakeScopeExit([&]() {
637 LOG(Info, "Read in %fms\n", (TimeStamp::Now() - now).ToMilliseconds());
638 });
639
640 if (mResultCode == NS_ERROR_NOT_INITIALIZED) {
641 MonitorAutoLock mal(GetSingleton().mMonitor);
642
643 while (mResultCode == NS_ERROR_NOT_INITIALIZED) {
644 mal.Wait();
645 }
646 }
647
648 if (mResultCode == NS_OK && mData.IsVoid()) {
649 LOG(Info, "Reading synchronously...\n");
650 return Read();
651 }
652
653 if (NS_FAILED(mResultCode)) {
654 return Err(mResultCode);
655 }
656
657 nsCString res = mData;
658
659 if (readType == Forget) {
660 mData.SetIsVoid(true);
661 }
662 return res;
663 }
664
CacheKey(InputBuffer & buffer)665 inline URLPreloader::CacheKey::CacheKey(InputBuffer& buffer) { Code(buffer); }
666
667 NS_IMPL_ISUPPORTS(URLPreloader, nsIMemoryReporter)
668
669 #undef LOG
670
671 } // namespace mozilla
672