Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/layout/style/nsLayoutStylesheetCache.cpp
Line
Count
Source (jump to first uncovered line)
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 "nsLayoutStylesheetCache.h"
8
9
#include "nsAppDirectoryServiceDefs.h"
10
#include "mozilla/StyleSheetInlines.h"
11
#include "mozilla/MemoryReporting.h"
12
#include "mozilla/Omnijar.h"
13
#include "mozilla/Preferences.h"
14
#include "mozilla/StyleSheet.h"
15
#include "mozilla/StyleSheetInlines.h"
16
#include "mozilla/Telemetry.h"
17
#include "mozilla/css/Loader.h"
18
#include "mozilla/dom/SRIMetadata.h"
19
#include "MainThreadUtils.h"
20
#include "nsColor.h"
21
#include "nsDirectoryServiceDefs.h"
22
#include "nsDirectoryService.h"
23
#include "nsExceptionHandler.h"
24
#include "nsIChromeRegistry.h"
25
#include "nsIConsoleService.h"
26
#include "nsIFile.h"
27
#include "nsIObserverService.h"
28
#include "nsISimpleEnumerator.h"
29
#include "nsISubstitutingProtocolHandler.h"
30
#include "nsIXULRuntime.h"
31
#include "nsNetUtil.h"
32
#include "nsPresContext.h"
33
#include "nsPrintfCString.h"
34
#include "nsServiceManagerUtils.h"
35
#include "nsXULAppAPI.h"
36
#include "nsZipArchive.h"
37
38
#include "zlib.h"
39
40
using namespace mozilla;
41
using namespace mozilla::css;
42
43
NS_IMPL_ISUPPORTS(
44
  nsLayoutStylesheetCache, nsIObserver, nsIMemoryReporter)
45
46
nsresult
47
nsLayoutStylesheetCache::Observe(nsISupports* aSubject,
48
                            const char* aTopic,
49
                            const char16_t* aData)
50
0
{
51
0
  if (!strcmp(aTopic, "profile-before-change")) {
52
0
    mUserContentSheet = nullptr;
53
0
    mUserChromeSheet  = nullptr;
54
0
  }
55
0
  else if (!strcmp(aTopic, "profile-do-change")) {
56
0
    InitFromProfile();
57
0
  }
58
0
  else if (strcmp(aTopic, "chrome-flush-skin-caches") == 0 ||
59
0
           strcmp(aTopic, "chrome-flush-caches") == 0) {
60
0
    mScrollbarsSheet = nullptr;
61
0
    mFormsSheet = nullptr;
62
0
  }
63
0
  else {
64
0
    MOZ_ASSERT_UNREACHABLE("Unexpected observer topic.");
65
0
  }
66
0
  return NS_OK;
67
0
}
68
69
StyleSheet*
70
nsLayoutStylesheetCache::ScrollbarsSheet()
71
0
{
72
0
  if (!mScrollbarsSheet) {
73
0
    // Scrollbars don't need access to unsafe rules
74
0
    LoadSheetURL("chrome://global/skin/scrollbars.css",
75
0
                 &mScrollbarsSheet, eSafeAgentSheetFeatures, eCrash);
76
0
  }
77
0
78
0
  return mScrollbarsSheet;
79
0
}
80
81
StyleSheet*
82
nsLayoutStylesheetCache::FormsSheet()
83
0
{
84
0
  if (!mFormsSheet) {
85
0
    // forms.css needs access to unsafe rules
86
0
    LoadSheetURL("resource://gre-resources/forms.css",
87
0
                 &mFormsSheet, eAgentSheetFeatures, eCrash);
88
0
  }
89
0
90
0
  return mFormsSheet;
91
0
}
92
93
StyleSheet*
94
nsLayoutStylesheetCache::UserContentSheet()
95
0
{
96
0
  return mUserContentSheet;
97
0
}
98
99
StyleSheet*
100
nsLayoutStylesheetCache::UserChromeSheet()
101
0
{
102
0
  return mUserChromeSheet;
103
0
}
104
105
StyleSheet*
106
nsLayoutStylesheetCache::UASheet()
107
0
{
108
0
  if (!mUASheet) {
109
0
    LoadSheetURL("resource://gre-resources/ua.css",
110
0
                 &mUASheet, eAgentSheetFeatures, eCrash);
111
0
  }
112
0
113
0
  return mUASheet;
114
0
}
115
116
StyleSheet*
117
nsLayoutStylesheetCache::HTMLSheet()
118
0
{
119
0
  return mHTMLSheet;
120
0
}
121
122
StyleSheet*
123
nsLayoutStylesheetCache::MinimalXULSheet()
124
0
{
125
0
  return mMinimalXULSheet;
126
0
}
127
128
StyleSheet*
129
nsLayoutStylesheetCache::XULSheet()
130
0
{
131
0
  if (!mXULSheet) {
132
0
    LoadSheetURL("chrome://global/content/xul.css",
133
0
                 &mXULSheet, eAgentSheetFeatures, eCrash);
134
0
  }
135
0
136
0
  return mXULSheet;
137
0
}
138
139
StyleSheet*
140
nsLayoutStylesheetCache::XULComponentsSheet()
141
0
{
142
0
  if (!mXULComponentsSheet) {
143
0
    LoadSheetURL("chrome://global/content/components.css",
144
0
                 &mXULComponentsSheet, eAgentSheetFeatures, eCrash);
145
0
  }
146
0
147
0
  return mXULComponentsSheet;
148
0
}
149
150
StyleSheet*
151
nsLayoutStylesheetCache::QuirkSheet()
152
0
{
153
0
  return mQuirkSheet;
154
0
}
155
156
StyleSheet*
157
nsLayoutStylesheetCache::SVGSheet()
158
0
{
159
0
  return mSVGSheet;
160
0
}
161
162
StyleSheet*
163
nsLayoutStylesheetCache::MathMLSheet()
164
0
{
165
0
  if (!mMathMLSheet) {
166
0
    LoadSheetURL("resource://gre-resources/mathml.css",
167
0
                 &mMathMLSheet, eAgentSheetFeatures, eCrash);
168
0
  }
169
0
170
0
  return mMathMLSheet;
171
0
}
172
173
StyleSheet*
174
nsLayoutStylesheetCache::CounterStylesSheet()
175
0
{
176
0
  return mCounterStylesSheet;
177
0
}
178
179
StyleSheet*
180
nsLayoutStylesheetCache::NoScriptSheet()
181
0
{
182
0
  if (!mNoScriptSheet) {
183
0
    LoadSheetURL("resource://gre-resources/noscript.css",
184
0
                 &mNoScriptSheet, eAgentSheetFeatures, eCrash);
185
0
  }
186
0
187
0
  return mNoScriptSheet;
188
0
}
189
190
StyleSheet*
191
nsLayoutStylesheetCache::NoFramesSheet()
192
0
{
193
0
  if (!mNoFramesSheet) {
194
0
    LoadSheetURL("resource://gre-resources/noframes.css",
195
0
                 &mNoFramesSheet, eAgentSheetFeatures, eCrash);
196
0
  }
197
0
198
0
  return mNoFramesSheet;
199
0
}
200
201
StyleSheet*
202
nsLayoutStylesheetCache::ChromePreferenceSheet(nsPresContext* aPresContext)
203
0
{
204
0
  if (!mChromePreferenceSheet) {
205
0
    BuildPreferenceSheet(&mChromePreferenceSheet, aPresContext);
206
0
  }
207
0
208
0
  return mChromePreferenceSheet;
209
0
}
210
211
StyleSheet*
212
nsLayoutStylesheetCache::ContentPreferenceSheet(nsPresContext* aPresContext)
213
0
{
214
0
  if (!mContentPreferenceSheet) {
215
0
    BuildPreferenceSheet(&mContentPreferenceSheet, aPresContext);
216
0
  }
217
0
218
0
  return mContentPreferenceSheet;
219
0
}
220
221
StyleSheet*
222
nsLayoutStylesheetCache::ContentEditableSheet()
223
0
{
224
0
  if (!mContentEditableSheet) {
225
0
    LoadSheetURL("resource://gre/res/contenteditable.css",
226
0
                 &mContentEditableSheet, eAgentSheetFeatures, eCrash);
227
0
  }
228
0
229
0
  return mContentEditableSheet;
230
0
}
231
232
StyleSheet*
233
nsLayoutStylesheetCache::DesignModeSheet()
234
0
{
235
0
  if (!mDesignModeSheet) {
236
0
    LoadSheetURL("resource://gre/res/designmode.css",
237
0
                 &mDesignModeSheet, eAgentSheetFeatures, eCrash);
238
0
  }
239
0
240
0
  return mDesignModeSheet;
241
0
}
242
243
void
244
nsLayoutStylesheetCache::Shutdown()
245
0
{
246
0
  gCSSLoader = nullptr;
247
0
  NS_WARNING_ASSERTION(!gStyleCache || !gUserContentSheetURL,
248
0
                       "Got the URL but never used?");
249
0
  gStyleCache = nullptr;
250
0
  gUserContentSheetURL = nullptr;
251
0
}
252
253
void
254
nsLayoutStylesheetCache::SetUserContentCSSURL(nsIURI* aURI)
255
0
{
256
0
  MOZ_ASSERT(XRE_IsContentProcess(), "Only used in content processes.");
257
0
  gUserContentSheetURL = aURI;
258
0
}
259
260
MOZ_DEFINE_MALLOC_SIZE_OF(LayoutStylesheetCacheMallocSizeOf)
261
262
NS_IMETHODIMP
263
nsLayoutStylesheetCache::CollectReports(nsIHandleReportCallback* aHandleReport,
264
                                        nsISupports* aData, bool aAnonymize)
265
0
{
266
0
  MOZ_COLLECT_REPORT(
267
0
    "explicit/layout/style-sheet-cache", KIND_HEAP, UNITS_BYTES,
268
0
    SizeOfIncludingThis(LayoutStylesheetCacheMallocSizeOf),
269
0
    "Memory used for some built-in style sheets.");
270
0
271
0
  return NS_OK;
272
0
}
273
274
275
size_t
276
nsLayoutStylesheetCache::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const
277
0
{
278
0
  size_t n = aMallocSizeOf(this);
279
0
280
0
  #define MEASURE(s) n += s ? s->SizeOfIncludingThis(aMallocSizeOf) : 0;
281
0
282
0
  MEASURE(mChromePreferenceSheet);
283
0
  MEASURE(mContentEditableSheet);
284
0
  MEASURE(mContentPreferenceSheet);
285
0
  MEASURE(mCounterStylesSheet);
286
0
  MEASURE(mDesignModeSheet);
287
0
  MEASURE(mFormsSheet);
288
0
  MEASURE(mHTMLSheet);
289
0
  MEASURE(mMathMLSheet);
290
0
  MEASURE(mMinimalXULSheet);
291
0
  MEASURE(mNoFramesSheet);
292
0
  MEASURE(mNoScriptSheet);
293
0
  MEASURE(mQuirkSheet);
294
0
  MEASURE(mSVGSheet);
295
0
  MEASURE(mScrollbarsSheet);
296
0
  MEASURE(mUASheet);
297
0
  MEASURE(mUserChromeSheet);
298
0
  MEASURE(mUserContentSheet);
299
0
  MEASURE(mXULSheet);
300
0
  MEASURE(mXULComponentsSheet);
301
0
302
0
  // Measurement of the following members may be added later if DMD finds it is
303
0
  // worthwhile:
304
0
  // - gCSSLoader
305
0
306
0
  return n;
307
0
}
308
309
nsLayoutStylesheetCache::nsLayoutStylesheetCache()
310
0
{
311
0
  nsCOMPtr<nsIObserverService> obsSvc =
312
0
    mozilla::services::GetObserverService();
313
0
  NS_ASSERTION(obsSvc, "No global observer service?");
314
0
315
0
  if (obsSvc) {
316
0
    obsSvc->AddObserver(this, "profile-before-change", false);
317
0
    obsSvc->AddObserver(this, "profile-do-change", false);
318
0
    obsSvc->AddObserver(this, "chrome-flush-skin-caches", false);
319
0
    obsSvc->AddObserver(this, "chrome-flush-caches", false);
320
0
  }
321
0
322
0
  InitFromProfile();
323
0
324
0
  // And make sure that we load our UA sheets.  No need to do this
325
0
  // per-profile, since they're profile-invariant.
326
0
  LoadSheetURL("resource://gre-resources/counterstyles.css",
327
0
               &mCounterStylesSheet, eAgentSheetFeatures, eCrash);
328
0
  LoadSheetURL("resource://gre-resources/html.css",
329
0
               &mHTMLSheet, eAgentSheetFeatures, eCrash);
330
0
  LoadSheetURL("chrome://global/content/minimal-xul.css",
331
0
               &mMinimalXULSheet, eAgentSheetFeatures, eCrash);
332
0
  LoadSheetURL("resource://gre-resources/quirk.css",
333
0
               &mQuirkSheet, eAgentSheetFeatures, eCrash);
334
0
  LoadSheetURL("resource://gre/res/svg.css",
335
0
               &mSVGSheet, eAgentSheetFeatures, eCrash);
336
0
  if (XRE_IsParentProcess()) {
337
0
    // We know we need xul.css for the UI, so load that now too:
338
0
    XULSheet();
339
0
    XULComponentsSheet();
340
0
  }
341
0
342
0
  if (gUserContentSheetURL) {
343
0
    MOZ_ASSERT(XRE_IsContentProcess(), "Only used in content processes.");
344
0
    LoadSheet(gUserContentSheetURL, &mUserContentSheet,
345
0
              eUserSheetFeatures, eLogToConsole);
346
0
    gUserContentSheetURL = nullptr;
347
0
  }
348
0
349
0
  // The remaining sheets are created on-demand do to their use being rarer
350
0
  // (which helps save memory for Firefox OS apps) or because they need to
351
0
  // be re-loadable in DependentPrefChanged.
352
0
}
353
354
nsLayoutStylesheetCache::~nsLayoutStylesheetCache()
355
0
{
356
0
  mozilla::UnregisterWeakMemoryReporter(this);
357
0
}
358
359
void
360
nsLayoutStylesheetCache::InitMemoryReporter()
361
0
{
362
0
  mozilla::RegisterWeakMemoryReporter(this);
363
0
}
364
365
/* static */ nsLayoutStylesheetCache*
366
nsLayoutStylesheetCache::Singleton()
367
0
{
368
0
  MOZ_ASSERT(NS_IsMainThread());
369
0
370
0
  if (!gStyleCache) {
371
0
    gStyleCache = new nsLayoutStylesheetCache;
372
0
    gStyleCache->InitMemoryReporter();
373
0
374
0
    // For each pref that controls a CSS feature that a UA style sheet depends
375
0
    // on (such as a pref that enables a property that a UA style sheet uses),
376
0
    // register DependentPrefChanged as a callback to ensure that the relevant
377
0
    // style sheets will be re-parsed.
378
0
    // Preferences::RegisterCallback(&DependentPrefChanged,
379
0
    //                               "layout.css.example-pref.enabled");
380
0
  }
381
0
382
0
  return gStyleCache;
383
0
}
384
385
void
386
nsLayoutStylesheetCache::InitFromProfile()
387
0
{
388
0
  nsCOMPtr<nsIXULRuntime> appInfo = do_GetService("@mozilla.org/xre/app-info;1");
389
0
  if (appInfo) {
390
0
    bool inSafeMode = false;
391
0
    appInfo->GetInSafeMode(&inSafeMode);
392
0
    if (inSafeMode)
393
0
      return;
394
0
  }
395
0
  nsCOMPtr<nsIFile> contentFile;
396
0
  nsCOMPtr<nsIFile> chromeFile;
397
0
398
0
  NS_GetSpecialDirectory(NS_APP_USER_CHROME_DIR,
399
0
                         getter_AddRefs(contentFile));
400
0
  if (!contentFile) {
401
0
    // if we don't have a profile yet, that's OK!
402
0
    return;
403
0
  }
404
0
405
0
  contentFile->Clone(getter_AddRefs(chromeFile));
406
0
  if (!chromeFile) return;
407
0
408
0
  contentFile->Append(NS_LITERAL_STRING("userContent.css"));
409
0
  chromeFile->Append(NS_LITERAL_STRING("userChrome.css"));
410
0
411
0
  LoadSheetFile(contentFile, &mUserContentSheet, eUserSheetFeatures, eLogToConsole);
412
0
  LoadSheetFile(chromeFile, &mUserChromeSheet, eUserSheetFeatures, eLogToConsole);
413
0
414
0
  if (XRE_IsParentProcess()) {
415
0
    // We're interested specifically in potential chrome customizations,
416
0
    // so we only need data points from the parent process
417
0
    Telemetry::Accumulate(Telemetry::USER_CHROME_CSS_LOADED, mUserChromeSheet != nullptr);
418
0
  }
419
0
}
420
421
void
422
nsLayoutStylesheetCache::LoadSheetURL(const char* aURL,
423
                                      RefPtr<StyleSheet>* aSheet,
424
                                      SheetParsingMode aParsingMode,
425
                                      FailureAction aFailureAction)
426
0
{
427
0
  nsCOMPtr<nsIURI> uri;
428
0
  NS_NewURI(getter_AddRefs(uri), aURL);
429
0
  LoadSheet(uri, aSheet, aParsingMode, aFailureAction);
430
0
  if (!aSheet) {
431
0
    NS_ERROR(nsPrintfCString("Could not load %s", aURL).get());
432
0
  }
433
0
}
434
435
void
436
nsLayoutStylesheetCache::LoadSheetFile(nsIFile* aFile,
437
                                       RefPtr<StyleSheet>* aSheet,
438
                                       SheetParsingMode aParsingMode,
439
                                       FailureAction aFailureAction)
440
0
{
441
0
  bool exists = false;
442
0
  aFile->Exists(&exists);
443
0
444
0
  if (!exists) return;
445
0
446
0
  nsCOMPtr<nsIURI> uri;
447
0
  NS_NewFileURI(getter_AddRefs(uri), aFile);
448
0
449
0
  LoadSheet(uri, aSheet, aParsingMode, aFailureAction);
450
0
}
451
452
static inline nsresult
453
ComputeCRC32(nsIFile* aFile, uint32_t* aResult)
454
0
{
455
0
  PRFileDesc* fd;
456
0
  nsresult rv = aFile->OpenNSPRFileDesc(PR_RDONLY, 0, &fd);
457
0
  NS_ENSURE_SUCCESS(rv, rv);
458
0
459
0
  uint32_t crc = crc32(0, nullptr, 0);
460
0
461
0
  unsigned char buf[512];
462
0
  int32_t n;
463
0
  while ((n = PR_Read(fd, buf, sizeof(buf))) > 0) {
464
0
    crc = crc32(crc, buf, n);
465
0
  }
466
0
  PR_Close(fd);
467
0
468
0
  if (n < 0) {
469
0
    return NS_ERROR_FAILURE;
470
0
  }
471
0
472
0
  *aResult = crc;
473
0
  return NS_OK;
474
0
}
475
476
static void
477
ListInterestingFiles(nsString& aAnnotation, nsIFile* aFile,
478
                     const nsTArray<nsString>& aInterestingFilenames)
479
0
{
480
0
  nsString filename;
481
0
  aFile->GetLeafName(filename);
482
0
  for (const nsString& interestingFilename : aInterestingFilenames) {
483
0
    if (interestingFilename == filename) {
484
0
      nsString path;
485
0
      aFile->GetPath(path);
486
0
      aAnnotation.AppendLiteral("  ");
487
0
      aAnnotation.Append(path);
488
0
      aAnnotation.AppendLiteral(" (");
489
0
      int64_t size;
490
0
      if (NS_SUCCEEDED(aFile->GetFileSize(&size))) {
491
0
        aAnnotation.AppendPrintf("%" PRId64, size);
492
0
      } else {
493
0
        aAnnotation.AppendLiteral("???");
494
0
      }
495
0
      aAnnotation.AppendLiteral(" bytes, crc32 = ");
496
0
      uint32_t crc;
497
0
      nsresult rv = ComputeCRC32(aFile, &crc);
498
0
      if (NS_SUCCEEDED(rv)) {
499
0
        aAnnotation.AppendPrintf("0x%08x)\n", crc);
500
0
      } else {
501
0
        aAnnotation.AppendPrintf("error 0x%08x)\n", uint32_t(rv));
502
0
      }
503
0
      return;
504
0
    }
505
0
  }
506
0
507
0
  bool isDir = false;
508
0
  aFile->IsDirectory(&isDir);
509
0
510
0
  if (!isDir) {
511
0
    return;
512
0
  }
513
0
514
0
  nsCOMPtr<nsIDirectoryEnumerator> entries;
515
0
  if (NS_FAILED(aFile->GetDirectoryEntries(getter_AddRefs(entries)))) {
516
0
    aAnnotation.AppendLiteral("  (failed to enumerated directory)\n");
517
0
    return;
518
0
  }
519
0
520
0
  for (;;) {
521
0
    nsCOMPtr<nsIFile> file;
522
0
    if (NS_FAILED(entries->GetNextFile(getter_AddRefs(file)))) {
523
0
      aAnnotation.AppendLiteral("  (failed during directory enumeration)\n");
524
0
      return;
525
0
    }
526
0
    if (!file) {
527
0
      break;
528
0
    }
529
0
    ListInterestingFiles(aAnnotation, file, aInterestingFilenames);
530
0
  }
531
0
}
532
533
// Generate a crash report annotation to help debug issues with style
534
// sheets failing to load (bug 1194856).
535
static void
536
AnnotateCrashReport(nsIURI* aURI)
537
0
{
538
0
  nsAutoCString spec;
539
0
  nsAutoCString scheme;
540
0
  nsDependentCSubstring filename;
541
0
  if (aURI) {
542
0
    spec = aURI->GetSpecOrDefault();
543
0
    aURI->GetScheme(scheme);
544
0
    int32_t i = spec.RFindChar('/');
545
0
    if (i != -1) {
546
0
      filename.Rebind(spec, i + 1);
547
0
    }
548
0
  }
549
0
550
0
  nsString annotation;
551
0
552
0
  // The URL of the sheet that failed to load.
553
0
  annotation.AppendLiteral("Error loading sheet: ");
554
0
  annotation.Append(NS_ConvertUTF8toUTF16(spec).get());
555
0
  annotation.Append('\n');
556
0
557
0
  annotation.AppendLiteral("NS_ERROR_FILE_CORRUPTION reason: ");
558
0
  if (nsZipArchive::sFileCorruptedReason) {
559
0
    annotation.Append(NS_ConvertUTF8toUTF16(nsZipArchive::sFileCorruptedReason).get());
560
0
    annotation.Append('\n');
561
0
  } else {
562
0
    annotation.AppendLiteral("(none)\n");
563
0
  }
564
0
565
0
  // The jar: or file: URL that the sheet's resource: or chrome: URL
566
0
  // resolves to.
567
0
  if (scheme.EqualsLiteral("resource")) {
568
0
    annotation.AppendLiteral("Real location: ");
569
0
    nsCOMPtr<nsISubstitutingProtocolHandler> handler;
570
0
    nsCOMPtr<nsIIOService> io(do_GetIOService());
571
0
    if (io) {
572
0
      nsCOMPtr<nsIProtocolHandler> ph;
573
0
      io->GetProtocolHandler(scheme.get(), getter_AddRefs(ph));
574
0
      if (ph) {
575
0
        handler = do_QueryInterface(ph);
576
0
      }
577
0
    }
578
0
    if (!handler) {
579
0
      annotation.AppendLiteral("(ResolveURI failed)\n");
580
0
    } else {
581
0
      nsAutoCString resolvedSpec;
582
0
      nsresult rv = handler->ResolveURI(aURI, resolvedSpec);
583
0
      if (NS_FAILED(rv)) {
584
0
        annotation.AppendPrintf("(ResolveURI failed with 0x%08" PRIx32 ")\n",
585
0
                                static_cast<uint32_t>(rv));
586
0
      }
587
0
      annotation.Append(NS_ConvertUTF8toUTF16(resolvedSpec));
588
0
      annotation.Append('\n');
589
0
    }
590
0
  } else if (scheme.EqualsLiteral("chrome")) {
591
0
    annotation.AppendLiteral("Real location: ");
592
0
    nsCOMPtr<nsIChromeRegistry> reg =
593
0
      mozilla::services::GetChromeRegistryService();
594
0
    if (!reg) {
595
0
      annotation.AppendLiteral("(no chrome registry)\n");
596
0
    } else {
597
0
      nsCOMPtr<nsIURI> resolvedURI;
598
0
      reg->ConvertChromeURL(aURI, getter_AddRefs(resolvedURI));
599
0
      if (!resolvedURI) {
600
0
        annotation.AppendLiteral("(ConvertChromeURL failed)\n");
601
0
      } else {
602
0
        annotation.Append(
603
0
          NS_ConvertUTF8toUTF16(resolvedURI->GetSpecOrDefault()));
604
0
        annotation.Append('\n');
605
0
      }
606
0
    }
607
0
  }
608
0
609
0
  nsTArray<nsString> interestingFiles;
610
0
  interestingFiles.AppendElement(NS_LITERAL_STRING("chrome.manifest"));
611
0
  interestingFiles.AppendElement(NS_LITERAL_STRING("omni.ja"));
612
0
  interestingFiles.AppendElement(NS_ConvertUTF8toUTF16(filename));
613
0
614
0
  annotation.AppendLiteral("GRE directory: ");
615
0
  nsCOMPtr<nsIFile> file;
616
0
  nsDirectoryService::gService->Get(NS_GRE_DIR, NS_GET_IID(nsIFile),
617
0
                                    getter_AddRefs(file));
618
0
  if (file) {
619
0
    // The Firefox installation directory.
620
0
    nsString path;
621
0
    file->GetPath(path);
622
0
    annotation.Append(path);
623
0
    annotation.Append('\n');
624
0
625
0
    // List interesting files -- any chrome.manifest or omni.ja file or any file
626
0
    // whose name is the sheet's filename -- under the Firefox installation
627
0
    // directory.
628
0
    annotation.AppendLiteral("Interesting files in the GRE directory:\n");
629
0
    ListInterestingFiles(annotation, file, interestingFiles);
630
0
631
0
    // If the Firefox installation directory has a chrome.manifest file, let's
632
0
    // see what's in it.
633
0
    file->Append(NS_LITERAL_STRING("chrome.manifest"));
634
0
    bool exists = false;
635
0
    file->Exists(&exists);
636
0
    if (exists) {
637
0
      annotation.AppendLiteral("Contents of chrome.manifest:\n[[[\n");
638
0
      PRFileDesc* fd;
639
0
      if (NS_SUCCEEDED(file->OpenNSPRFileDesc(PR_RDONLY, 0, &fd))) {
640
0
        nsCString contents;
641
0
        char buf[512];
642
0
        int32_t n;
643
0
        while ((n = PR_Read(fd, buf, sizeof(buf))) > 0) {
644
0
          contents.Append(buf, n);
645
0
        }
646
0
        if (n < 0) {
647
0
          annotation.AppendLiteral("  (error while reading)\n");
648
0
        } else {
649
0
          annotation.Append(NS_ConvertUTF8toUTF16(contents));
650
0
        }
651
0
        PR_Close(fd);
652
0
      }
653
0
      annotation.AppendLiteral("]]]\n");
654
0
    }
655
0
  } else {
656
0
    annotation.AppendLiteral("(none)\n");
657
0
  }
658
0
659
0
  // The jar: or file: URL prefix that chrome: and resource: URLs get translated
660
0
  // to.
661
0
  annotation.AppendLiteral("GRE omnijar URI string: ");
662
0
  nsCString uri;
663
0
  nsresult rv = Omnijar::GetURIString(Omnijar::GRE, uri);
664
0
  if (NS_FAILED(rv)) {
665
0
    annotation.AppendLiteral("(failed)\n");
666
0
  } else {
667
0
    annotation.Append(NS_ConvertUTF8toUTF16(uri));
668
0
    annotation.Append('\n');
669
0
  }
670
0
671
0
  RefPtr<nsZipArchive> zip = Omnijar::GetReader(Omnijar::GRE);
672
0
  if (zip) {
673
0
    // List interesting files in the GRE omnijar.
674
0
    annotation.AppendLiteral("Interesting files in the GRE omnijar:\n");
675
0
    nsZipFind* find;
676
0
    rv = zip->FindInit(nullptr, &find);
677
0
    if (NS_FAILED(rv)) {
678
0
      annotation.AppendPrintf("  (FindInit failed with 0x%08" PRIx32 ")\n",
679
0
                              static_cast<uint32_t>(rv));
680
0
    } else if (!find) {
681
0
      annotation.AppendLiteral("  (FindInit returned null)\n");
682
0
    } else {
683
0
      const char* result;
684
0
      uint16_t len;
685
0
      while (NS_SUCCEEDED(find->FindNext(&result, &len))) {
686
0
        nsCString itemPathname;
687
0
        nsString itemFilename;
688
0
        itemPathname.Append(result, len);
689
0
        int32_t i = itemPathname.RFindChar('/');
690
0
        if (i != -1) {
691
0
          itemFilename = NS_ConvertUTF8toUTF16(Substring(itemPathname, i + 1));
692
0
        }
693
0
        for (const nsString& interestingFile : interestingFiles) {
694
0
          if (interestingFile == itemFilename) {
695
0
            annotation.AppendLiteral("  ");
696
0
            annotation.Append(NS_ConvertUTF8toUTF16(itemPathname));
697
0
            nsZipItem* item = zip->GetItem(itemPathname.get());
698
0
            if (!item) {
699
0
              annotation.AppendLiteral(" (GetItem failed)\n");
700
0
            } else {
701
0
              annotation.AppendPrintf(" (%d bytes, crc32 = 0x%08x)\n",
702
0
                                      item->RealSize(),
703
0
                                      item->CRC32());
704
0
            }
705
0
            break;
706
0
          }
707
0
        }
708
0
      }
709
0
      delete find;
710
0
    }
711
0
  } else {
712
0
    annotation.AppendLiteral("No GRE omnijar\n");
713
0
  }
714
0
715
0
  CrashReporter::AnnotateCrashReport(
716
0
    CrashReporter::Annotation::SheetLoadFailure,
717
0
    NS_ConvertUTF16toUTF8(annotation));
718
0
}
719
720
static void
721
ErrorLoadingSheet(nsIURI* aURI, const char* aMsg, FailureAction aFailureAction)
722
0
{
723
0
  nsPrintfCString errorMessage("%s loading built-in stylesheet '%s'",
724
0
                               aMsg,
725
0
                               aURI ? aURI->GetSpecOrDefault().get() : "");
726
0
  if (aFailureAction == eLogToConsole) {
727
0
    nsCOMPtr<nsIConsoleService> cs = do_GetService(NS_CONSOLESERVICE_CONTRACTID);
728
0
    if (cs) {
729
0
      cs->LogStringMessage(NS_ConvertUTF8toUTF16(errorMessage).get());
730
0
      return;
731
0
    }
732
0
  }
733
0
734
0
  AnnotateCrashReport(aURI);
735
0
  MOZ_CRASH_UNSAFE_OOL(errorMessage.get());
736
0
}
737
738
void
739
nsLayoutStylesheetCache::LoadSheet(nsIURI* aURI,
740
                                   RefPtr<StyleSheet>* aSheet,
741
                                   SheetParsingMode aParsingMode,
742
                                   FailureAction aFailureAction)
743
0
{
744
0
  if (!aURI) {
745
0
    ErrorLoadingSheet(aURI, "null URI", eCrash);
746
0
    return;
747
0
  }
748
0
749
0
  if (!gCSSLoader) {
750
0
    gCSSLoader = new Loader;
751
0
    if (!gCSSLoader) {
752
0
      ErrorLoadingSheet(aURI, "no Loader", eCrash);
753
0
      return;
754
0
    }
755
0
  }
756
0
757
0
  nsZipArchive::sFileCorruptedReason = nullptr;
758
0
759
0
  // Note: The parallel parsing code assume that UA sheets are always loaded
760
0
  // synchronously like they are here, and thus that we'll never attempt
761
0
  // parallel parsing on them. If that ever changes, we'll either need to find a
762
0
  // different way to prohibit parallel parsing for UA sheets, or handle
763
0
  // -moz-bool-pref and various other things in the parallel parsing code.
764
0
  nsresult rv = gCSSLoader->LoadSheetSync(aURI, aParsingMode, true, aSheet);
765
0
  if (NS_FAILED(rv)) {
766
0
    ErrorLoadingSheet(aURI,
767
0
      nsPrintfCString("LoadSheetSync failed with error %" PRIx32, static_cast<uint32_t>(rv)).get(),
768
0
      aFailureAction);
769
0
  }
770
0
}
771
772
/* static */ void
773
nsLayoutStylesheetCache::InvalidatePreferenceSheets()
774
0
{
775
0
  if (gStyleCache) {
776
0
    gStyleCache->mContentPreferenceSheet = nullptr;
777
0
    gStyleCache->mChromePreferenceSheet = nullptr;
778
0
  }
779
0
}
780
781
void
782
nsLayoutStylesheetCache::BuildPreferenceSheet(RefPtr<StyleSheet>* aSheet,
783
                                              nsPresContext* aPresContext)
784
0
{
785
0
  *aSheet = new StyleSheet(eAgentSheetFeatures,
786
0
                           CORS_NONE,
787
0
                           mozilla::net::RP_Unset,
788
0
                           dom::SRIMetadata());
789
0
790
0
  StyleSheet* sheet = *aSheet;
791
0
792
0
  nsCOMPtr<nsIURI> uri;
793
0
  NS_NewURI(getter_AddRefs(uri), "about:PreferenceStyleSheet", nullptr);
794
0
  MOZ_ASSERT(uri, "URI creation shouldn't fail");
795
0
796
0
  sheet->SetURIs(uri, uri, uri);
797
0
  sheet->SetComplete();
798
0
799
0
  static const uint32_t kPreallocSize = 1024;
800
0
801
0
  nsCString sheetText;
802
0
  sheetText.SetCapacity(kPreallocSize);
803
0
804
0
#define NS_GET_R_G_B(color_) \
805
0
  NS_GET_R(color_), NS_GET_G(color_), NS_GET_B(color_)
806
0
807
0
  sheetText.AppendLiteral(
808
0
      "@namespace url(http://www.w3.org/1999/xhtml);\n"
809
0
      "@namespace svg url(http://www.w3.org/2000/svg);\n");
810
0
811
0
  // Rules for link styling.
812
0
  nscolor linkColor = aPresContext->DefaultLinkColor();
813
0
  nscolor activeColor = aPresContext->DefaultActiveLinkColor();
814
0
  nscolor visitedColor = aPresContext->DefaultVisitedLinkColor();
815
0
816
0
  sheetText.AppendPrintf(
817
0
      "*|*:link { color: #%02x%02x%02x; }\n"
818
0
      "*|*:any-link:active { color: #%02x%02x%02x; }\n"
819
0
      "*|*:visited { color: #%02x%02x%02x; }\n",
820
0
      NS_GET_R_G_B(linkColor),
821
0
      NS_GET_R_G_B(activeColor),
822
0
      NS_GET_R_G_B(visitedColor));
823
0
824
0
  bool underlineLinks =
825
0
    aPresContext->GetCachedBoolPref(kPresContext_UnderlineLinks);
826
0
  sheetText.AppendPrintf(
827
0
      "*|*:any-link%s { text-decoration: %s; }\n",
828
0
      underlineLinks ? ":not(svg|a)" : "",
829
0
      underlineLinks ? "underline" : "none");
830
0
831
0
  // Rules for focus styling.
832
0
833
0
  bool focusRingOnAnything = aPresContext->GetFocusRingOnAnything();
834
0
  uint8_t focusRingWidth = aPresContext->FocusRingWidth();
835
0
  uint8_t focusRingStyle = aPresContext->GetFocusRingStyle();
836
0
837
0
  if ((focusRingWidth != 1 && focusRingWidth <= 4) || focusRingOnAnything) {
838
0
    if (focusRingWidth != 1) {
839
0
      // If the focus ring width is different from the default, fix buttons
840
0
      // with rings.
841
0
      sheetText.AppendPrintf(
842
0
          "button::-moz-focus-inner, input[type=\"reset\"]::-moz-focus-inner, "
843
0
          "input[type=\"button\"]::-moz-focus-inner, "
844
0
          "input[type=\"submit\"]::-moz-focus-inner { "
845
0
          "border: %dpx %s transparent !important; }\n",
846
0
          focusRingWidth,
847
0
          focusRingStyle == 0 ? "solid" : "dotted");
848
0
849
0
      sheetText.AppendLiteral(
850
0
          "button:focus::-moz-focus-inner, "
851
0
          "input[type=\"reset\"]:focus::-moz-focus-inner, "
852
0
          "input[type=\"button\"]:focus::-moz-focus-inner, "
853
0
          "input[type=\"submit\"]:focus::-moz-focus-inner { "
854
0
          "border-color: ButtonText !important; }\n");
855
0
    }
856
0
857
0
    sheetText.AppendPrintf(
858
0
        "%s { outline: %dpx %s !important; %s}\n",
859
0
        focusRingOnAnything ?
860
0
          ":focus" :
861
0
          "*|*:link:focus, *|*:visited:focus",
862
0
        focusRingWidth,
863
0
        focusRingStyle == 0 ? // solid
864
0
          "solid -moz-mac-focusring" : "dotted WindowText",
865
0
        focusRingStyle == 0 ? // solid
866
0
          "-moz-outline-radius: 3px; outline-offset: 1px; " : "");
867
0
  }
868
0
869
0
  if (aPresContext->GetUseFocusColors()) {
870
0
    nscolor focusText = aPresContext->FocusTextColor();
871
0
    nscolor focusBG = aPresContext->FocusBackgroundColor();
872
0
    sheetText.AppendPrintf(
873
0
        "*:focus, *:focus > font { color: #%02x%02x%02x !important; "
874
0
        "background-color: #%02x%02x%02x !important; }\n",
875
0
        NS_GET_R_G_B(focusText),
876
0
        NS_GET_R_G_B(focusBG));
877
0
  }
878
0
879
0
  NS_ASSERTION(sheetText.Length() <= kPreallocSize,
880
0
               "kPreallocSize should be big enough to build preference style "
881
0
               "sheet without reallocation");
882
0
883
0
  // NB: The pref sheet never has @import rules, thus no loader.
884
0
  sheet->ParseSheetSync(nullptr,
885
0
                        sheetText,
886
0
                        /* aLoadData = */ nullptr,
887
0
                        /* aLineNumber = */ 0);
888
0
889
0
#undef NS_GET_R_G_B
890
0
}
891
892
mozilla::StaticRefPtr<nsLayoutStylesheetCache>
893
nsLayoutStylesheetCache::gStyleCache;
894
895
mozilla::StaticRefPtr<mozilla::css::Loader>
896
nsLayoutStylesheetCache::gCSSLoader;
897
898
mozilla::StaticRefPtr<nsIURI>
899
nsLayoutStylesheetCache::gUserContentSheetURL;