summaryrefslogtreecommitdiffstats
path: root/gfx/src/DriverCrashGuard.cpp
blob: fd616575bd0e02231f53ee4ac3519e0a032580ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "DriverCrashGuard.h"
#include "gfxEnv.h"
#include "gfxPrefs.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsDirectoryServiceUtils.h"
#include "nsServiceManagerUtils.h"
#include "nsString.h"
#include "nsXULAppAPI.h"
#include "mozilla/Preferences.h"
#include "mozilla/Services.h"
#include "mozilla/gfx/Logging.h"
#include "mozilla/dom/ContentChild.h"

namespace mozilla {
namespace gfx {

static const size_t NUM_CRASH_GUARD_TYPES = size_t(CrashGuardType::NUM_TYPES);
static const char* sCrashGuardNames[] = {
  "d3d11layers",
  "d3d9video",
  "glcontext",
  "d3d11video",
};
static_assert(MOZ_ARRAY_LENGTH(sCrashGuardNames) == NUM_CRASH_GUARD_TYPES,
              "CrashGuardType updated without a name string");

static inline void
BuildCrashGuardPrefName(CrashGuardType aType, nsCString& aOutPrefName)
{
  MOZ_ASSERT(aType < CrashGuardType::NUM_TYPES);
  MOZ_ASSERT(sCrashGuardNames[size_t(aType)]);

  aOutPrefName.Assign("gfx.crash-guard.status.");
  aOutPrefName.Append(sCrashGuardNames[size_t(aType)]);
}

DriverCrashGuard::DriverCrashGuard(CrashGuardType aType, dom::ContentParent* aContentParent)
 : mType(aType)
 , mMode(aContentParent ? Mode::Proxy : Mode::Normal)
 , mInitialized(false)
 , mGuardActivated(false)
 , mCrashDetected(false)
{
  BuildCrashGuardPrefName(aType, mStatusPref);
}

void
DriverCrashGuard::InitializeIfNeeded()
{
  if (mInitialized) {
    return;
  }

  mInitialized = true;
  Initialize();
}

static inline bool
AreCrashGuardsEnabled()
{
  // Crash guard isn't supported in the GPU process since the entire
  // process is basically a crash guard.
  if (XRE_IsGPUProcess()) {
    return false;
  }
#ifdef NIGHTLY_BUILD
  // We only use the crash guard on non-nightly channels, since the nightly
  // channel is for development and having graphics features perma-disabled
  // is rather annoying.  Unless the user forces is with an environment
  // variable, which comes in handy for testing.
  return gfxEnv::ForceCrashGuardNightly();
#else
  // Check to see if all guards have been disabled through the environment.
  if (gfxEnv::DisableCrashGuard()) {
    return false;
  }
  return true;
#endif
}

void
DriverCrashGuard::Initialize()
{
  if (!AreCrashGuardsEnabled()) {
    return;
  }

  // Using DriverCrashGuard off the main thread currently does not work. Under
  // e10s it could conceivably work by dispatching the IPC calls via the main
  // thread. In the parent process this would be harder. For now, we simply
  // exit early instead.
  if (!NS_IsMainThread()) {
    return;
  }

  mGfxInfo = services::GetGfxInfo();

  if (XRE_IsContentProcess()) {
    // Ask the parent whether or not activating the guard is okay. The parent
    // won't bother if it detected a crash.
    dom::ContentChild* cc = dom::ContentChild::GetSingleton();
    cc->SendBeginDriverCrashGuard(uint32_t(mType), &mCrashDetected);
    if (mCrashDetected) {
      LogFeatureDisabled();
      return;
    }

    ActivateGuard();
    return;
  }

  // Always check whether or not the lock file exists. For example, we could
  // have crashed creating a D3D9 device in the parent process, and on restart
  // are now requesting one in the child process. We catch everything here.
  if (RecoverFromCrash()) {
    mCrashDetected = true;
    return;
  }

  // If the environment has changed, we always activate the guard. In the
  // parent process this performs main-thread disk I/O. Child process guards
  // only incur an IPC cost, so if we're proxying for a child process, we
  // play it safe and activate the guard as long as we don't expect it to
  // crash.
  if (CheckOrRefreshEnvironment() ||
      (mMode == Mode::Proxy && GetStatus() != DriverInitStatus::Crashed))
  {
    ActivateGuard();
    return;
  }

  // If we got here and our status is "crashed", then the environment has not
  // updated and we do not want to attempt to use the driver again.
  if (GetStatus() == DriverInitStatus::Crashed) {
    mCrashDetected = true;
    LogFeatureDisabled();
  }
}

DriverCrashGuard::~DriverCrashGuard()
{
  if (!mGuardActivated) {
    return;
  }

  if (XRE_IsParentProcess()) {
    if (mGuardFile) {
      mGuardFile->Remove(false);
    }

    // If during our initialization, no other process encountered a crash, we
    // proceed to mark the status as okay.
    if (GetStatus() != DriverInitStatus::Crashed) {
      SetStatus(DriverInitStatus::Okay);
    }
  } else {
    dom::ContentChild::GetSingleton()->SendEndDriverCrashGuard(uint32_t(mType));
  }
}

bool
DriverCrashGuard::Crashed()
{
  InitializeIfNeeded();

  // Note, we read mCrashDetected instead of GetStatus(), since in child
  // processes we're not guaranteed that the prefs have been synced in
  // time.
  return mCrashDetected;
}

nsCOMPtr<nsIFile>
DriverCrashGuard::GetGuardFile()
{
  MOZ_ASSERT(XRE_IsParentProcess());

  nsCString filename;
  filename.Assign(sCrashGuardNames[size_t(mType)]);
  filename.Append(".guard");

  nsCOMPtr<nsIFile> file;
  NS_GetSpecialDirectory(NS_APP_USER_PROFILE_LOCAL_50_DIR, getter_AddRefs(file));
  if (!file) {
    return nullptr;
  }
  if (!NS_SUCCEEDED(file->AppendNative(filename))) {
    return nullptr;
  }
  return file;
}

void
DriverCrashGuard::ActivateGuard()
{
  mGuardActivated = true;

  // If we're in the content process, the rest of the guarding is handled
  // in the parent.
  if (XRE_IsContentProcess()) {
    return;
  }

  SetStatus(DriverInitStatus::Attempting);

  if (mMode != Mode::Proxy) {
    // In parent process guards, we use two tombstones to detect crashes: a
    // preferences and a zero-byte file on the filesystem.
    FlushPreferences();

    // Create a temporary tombstone/lockfile.
    FILE* fp = nullptr;
    mGuardFile = GetGuardFile();
    if (!mGuardFile || !NS_SUCCEEDED(mGuardFile->OpenANSIFileDesc("w", &fp))) {
      return;
    }
    fclose(fp);
  }
}

void
DriverCrashGuard::NotifyCrashed()
{
  CheckOrRefreshEnvironment();
  SetStatus(DriverInitStatus::Crashed);
  FlushPreferences();
  LogCrashRecovery();
}

bool
DriverCrashGuard::RecoverFromCrash()
{
  MOZ_ASSERT(XRE_IsParentProcess());

  nsCOMPtr<nsIFile> file = GetGuardFile();
  bool exists;
  if ((file &&
       NS_SUCCEEDED(file->Exists(&exists)) &&
       exists) ||
      (GetStatus() == DriverInitStatus::Attempting))
  {
    // If we get here, we've just recovered from a crash. Disable acceleration
    // until the environment changes.
    if (file) {
      file->Remove(false);
    }
    NotifyCrashed();
    return true;
  }
  return false;
}

// Return true if the caller should proceed to guard for crashes. False if
// the environment has not changed. We persist the "changed" status across
// calls, so that after an environment changes, all guards for the new
// session are activated rather than just the first.
bool
DriverCrashGuard::CheckOrRefreshEnvironment()
{
  // Our result can be cached statically since we don't check live prefs.
  static bool sBaseInfoChanged = false;
  static bool sBaseInfoChecked = false;

  if (!sBaseInfoChecked) {
    // None of the prefs we care about, so we cache the result statically.
    sBaseInfoChecked = true;
    sBaseInfoChanged = UpdateBaseEnvironment();
  }

  // Always update the full environment, even if the base info didn't change.
  return UpdateEnvironment() ||
         sBaseInfoChanged ||
         GetStatus() == DriverInitStatus::Unknown;
}

bool
DriverCrashGuard::UpdateBaseEnvironment()
{
  bool changed = false;
  if (mGfxInfo) {
    nsString value;

    // Driver properties.
    mGfxInfo->GetAdapterDriverVersion(value);
    changed |= CheckAndUpdatePref("driverVersion", value);
    mGfxInfo->GetAdapterDeviceID(value);
    changed |= CheckAndUpdatePref("deviceID", value);
  }

  // Firefox properties.
  changed |= CheckAndUpdatePref("appVersion", NS_LITERAL_STRING(MOZ_APP_VERSION));

  return changed;
}

bool
DriverCrashGuard::FeatureEnabled(int aFeature, bool aDefault)
{
  if (!mGfxInfo) {
    return aDefault;
  }
  int32_t status;
  nsCString discardFailureId;
  if (!NS_SUCCEEDED(mGfxInfo->GetFeatureStatus(aFeature, discardFailureId, &status))) {
    return false;
  }
  return status == nsIGfxInfo::FEATURE_STATUS_OK;
}

bool
DriverCrashGuard::CheckAndUpdateBoolPref(const char* aPrefName, bool aCurrentValue)
{
  std::string pref = GetFullPrefName(aPrefName);

  bool oldValue;
  if (NS_SUCCEEDED(Preferences::GetBool(pref.c_str(), &oldValue)) &&
      oldValue == aCurrentValue)
  {
    return false;
  }
  Preferences::SetBool(pref.c_str(), aCurrentValue);
  return true;
}

bool
DriverCrashGuard::CheckAndUpdatePref(const char* aPrefName, const nsAString& aCurrentValue)
{
  std::string pref = GetFullPrefName(aPrefName);

  nsAdoptingString oldValue = Preferences::GetString(pref.c_str());
  if (oldValue == aCurrentValue) {
    return false;
  }
  Preferences::SetString(pref.c_str(), aCurrentValue);
  return true;
}

std::string
DriverCrashGuard::GetFullPrefName(const char* aPref)
{
  return std::string("gfx.crash-guard.") +
         std::string(sCrashGuardNames[uint32_t(mType)]) +
         std::string(".") +
         std::string(aPref);
}

DriverInitStatus
DriverCrashGuard::GetStatus() const
{
  return (DriverInitStatus)Preferences::GetInt(mStatusPref.get(), 0);
}

void
DriverCrashGuard::SetStatus(DriverInitStatus aStatus)
{
  MOZ_ASSERT(XRE_IsParentProcess());

  Preferences::SetInt(mStatusPref.get(), int32_t(aStatus));
}

void
DriverCrashGuard::FlushPreferences()
{
  MOZ_ASSERT(XRE_IsParentProcess());

  if (nsIPrefService* prefService = Preferences::GetService()) {
    prefService->SavePrefFile(nullptr);
  }
}

void
DriverCrashGuard::ForEachActiveCrashGuard(const CrashGuardCallback& aCallback)
{
  if (!AreCrashGuardsEnabled()) {
    // Even if guards look active (via prefs), they can be ignored if globally
    // disabled.
    return;
  }

  for (size_t i = 0; i < NUM_CRASH_GUARD_TYPES; i++) {
    CrashGuardType type = static_cast<CrashGuardType>(i);

    nsCString prefName;
    BuildCrashGuardPrefName(type, prefName);

    auto status =
      static_cast<DriverInitStatus>(Preferences::GetInt(prefName.get(), 0));
    if (status != DriverInitStatus::Crashed) {
      continue;
    }

    aCallback(sCrashGuardNames[i], prefName.get());
  }
}

D3D11LayersCrashGuard::D3D11LayersCrashGuard(dom::ContentParent* aContentParent)
 : DriverCrashGuard(CrashGuardType::D3D11Layers, aContentParent)
{
}

void
D3D11LayersCrashGuard::Initialize()
{
  if (!XRE_IsParentProcess()) {
    // We assume the parent process already performed crash detection for
    // graphics devices.
    return;
  }

  DriverCrashGuard::Initialize();

  // If no telemetry states have been recorded, this will set the state to okay.
  // Otherwise, it will have no effect.
  RecordTelemetry(TelemetryState::Okay);
}

bool
D3D11LayersCrashGuard::UpdateEnvironment()
{
  // Our result can be cached statically since we don't check live prefs.
  static bool checked = false;
  static bool changed = false;

  if (checked) {
    return changed;
  }

  checked = true;

  // Feature status.
#if defined(XP_WIN)
  bool d2dEnabled = gfxPrefs::Direct2DForceEnabled() ||
                    (!gfxPrefs::Direct2DDisabled() && FeatureEnabled(nsIGfxInfo::FEATURE_DIRECT2D));
  changed |= CheckAndUpdateBoolPref("feature-d2d", d2dEnabled);

  bool d3d11Enabled = !gfxPrefs::LayersPreferD3D9();
  if (!FeatureEnabled(nsIGfxInfo::FEATURE_DIRECT3D_11_LAYERS)) {
    d3d11Enabled = false;
  }
  changed |= CheckAndUpdateBoolPref("feature-d3d11", d3d11Enabled);
#endif

  if (!changed) {
    return false;
  }

  RecordTelemetry(TelemetryState::EnvironmentChanged);
  return true;
}

void
D3D11LayersCrashGuard::LogCrashRecovery()
{
  RecordTelemetry(TelemetryState::RecoveredFromCrash);
  gfxCriticalNote << "D3D11 layers just crashed; D3D11 will be disabled.";
}

void
D3D11LayersCrashGuard::LogFeatureDisabled()
{
  RecordTelemetry(TelemetryState::FeatureDisabled);
  gfxCriticalNote << "D3D11 layers disabled due to a prior crash.";
}

void
D3D11LayersCrashGuard::RecordTelemetry(TelemetryState aState)
{
  /* STUB */
}

D3D9VideoCrashGuard::D3D9VideoCrashGuard(dom::ContentParent* aContentParent)
 : DriverCrashGuard(CrashGuardType::D3D9Video, aContentParent)
{
}

bool
D3D9VideoCrashGuard::UpdateEnvironment()
{
  // We don't care about any extra preferences here.
  return false;
}

void
D3D9VideoCrashGuard::LogCrashRecovery()
{
  gfxCriticalNote << "DXVA2D3D9 just crashed; hardware video will be disabled.";
}

void
D3D9VideoCrashGuard::LogFeatureDisabled()
{
  gfxCriticalNote << "DXVA2D3D9 video decoding is disabled due to a previous crash.";
}

D3D11VideoCrashGuard::D3D11VideoCrashGuard(dom::ContentParent* aContentParent)
 : DriverCrashGuard(CrashGuardType::D3D11Video, aContentParent)
{
}

bool
D3D11VideoCrashGuard::UpdateEnvironment()
{
  // We don't care about any extra preferences here.
  return false;
}

void
D3D11VideoCrashGuard::LogCrashRecovery()
{
  gfxCriticalNote << "DXVA2D3D11 just crashed; hardware video will be disabled.";
}

void
D3D11VideoCrashGuard::LogFeatureDisabled()
{
  gfxCriticalNote << "DXVA2D3D11 video decoding is disabled due to a previous crash.";
}

GLContextCrashGuard::GLContextCrashGuard(dom::ContentParent* aContentParent)
 : DriverCrashGuard(CrashGuardType::GLContext, aContentParent)
{
}

void
GLContextCrashGuard::Initialize()
{
  if (XRE_IsContentProcess()) {
    // Disable the GL crash guard in content processes, since we're not going
    // to lose the entire browser and we don't want to hinder WebGL availability.
    return;
  }

#if defined(MOZ_WIDGET_ANDROID)
  // Disable the WebGL crash guard on Android - it doesn't use E10S, and
  // its drivers will essentially never change, so the crash guard could
  // permanently disable WebGL.
  return;
#endif

  DriverCrashGuard::Initialize();
}

bool
GLContextCrashGuard::UpdateEnvironment()
{
  static bool checked = false;
  static bool changed = false;

  if (checked) {
    return changed;
  }

  checked = true;

#if defined(XP_WIN)
  changed |= CheckAndUpdateBoolPref("gfx.driver-init.webgl-angle-force-d3d11",
                                    gfxPrefs::WebGLANGLEForceD3D11());
  changed |= CheckAndUpdateBoolPref("gfx.driver-init.webgl-angle-try-d3d11",
                                    gfxPrefs::WebGLANGLETryD3D11());
  changed |= CheckAndUpdateBoolPref("gfx.driver-init.webgl-angle-force-warp",
                                    gfxPrefs::WebGLANGLEForceWARP());
  changed |= CheckAndUpdateBoolPref("gfx.driver-init.webgl-angle",
                                    FeatureEnabled(nsIGfxInfo::FEATURE_WEBGL_ANGLE, false));
  changed |= CheckAndUpdateBoolPref("gfx.driver-init.direct3d11-angle",
                                    FeatureEnabled(nsIGfxInfo::FEATURE_DIRECT3D_11_ANGLE, false));
#endif

  return changed;
}

void
GLContextCrashGuard::LogCrashRecovery()
{
  gfxCriticalNote << "GLContext just crashed.";
}

void
GLContextCrashGuard::LogFeatureDisabled()
{
  gfxCriticalNote << "GLContext remains enabled despite a previous crash.";
}

} // namespace gfx
} // namespace mozilla