Coverage Report

Created: 2018-09-25 14:53

/src/mozilla-central/toolkit/components/startup/nsAppStartup.cpp
Line
Count
Source (jump to first uncovered line)
1
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2
/* This Source Code Form is subject to the terms of the Mozilla Public
3
 * License, v. 2.0. If a copy of the MPL was not distributed with this
4
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6
#include "nsAppStartup.h"
7
8
#include "nsIAppShellService.h"
9
#include "nsPIDOMWindow.h"
10
#include "nsIInterfaceRequestor.h"
11
#include "nsIFile.h"
12
#include "nsIObserverService.h"
13
#include "nsIPrefBranch.h"
14
#include "nsIPrefService.h"
15
#include "nsIProcess.h"
16
#include "nsIPromptService.h"
17
#include "nsIStringBundle.h"
18
#include "nsISupportsPrimitives.h"
19
#include "nsIToolkitProfile.h"
20
#include "nsIWebBrowserChrome.h"
21
#include "nsIWindowMediator.h"
22
#include "nsIWindowWatcher.h"
23
#include "nsIXULRuntime.h"
24
#include "nsIXULWindow.h"
25
#include "nsNativeCharsetUtils.h"
26
#include "nsThreadUtils.h"
27
#include "nsAutoPtr.h"
28
#include "nsString.h"
29
#include "mozilla/Preferences.h"
30
#include "mozilla/ResultExtensions.h"
31
#include "mozilla/Unused.h"
32
#include "GeckoProfiler.h"
33
34
#include "prprf.h"
35
#include "nsIInterfaceRequestorUtils.h"
36
#include "nsWidgetsCID.h"
37
#include "nsAppRunner.h"
38
#include "nsAppShellCID.h"
39
#include "nsXPCOMCIDInternal.h"
40
#include "mozilla/Services.h"
41
#include "nsIXPConnect.h"
42
#include "jsapi.h"
43
#include "js/Date.h"
44
#include "prenv.h"
45
#include "nsAppDirectoryServiceDefs.h"
46
47
#if defined(XP_WIN)
48
// Prevent collisions with nsAppStartup::GetStartupInfo()
49
#undef GetStartupInfo
50
#endif
51
52
#include "mozilla/IOInterposer.h"
53
#include "mozilla/Telemetry.h"
54
#include "mozilla/StartupTimeline.h"
55
56
static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
57
58
0
#define kPrefLastSuccess "toolkit.startup.last_success"
59
0
#define kPrefMaxResumedCrashes "toolkit.startup.max_resumed_crashes"
60
0
#define kPrefRecentCrashes "toolkit.startup.recent_crashes"
61
0
#define kPrefAlwaysUseSafeMode "toolkit.startup.always_use_safe_mode"
62
63
#if defined(XP_WIN)
64
#include "mozilla/perfprobe.h"
65
/**
66
 * Events sent to the system for profiling purposes
67
 */
68
//Keep them syncronized with the .mof file
69
70
//Process-wide GUID, used by the OS to differentiate sources
71
// {509962E0-406B-46F4-99BA-5A009F8D2225}
72
//Keep it synchronized with the .mof file
73
#define NS_APPLICATION_TRACING_CID \
74
  { 0x509962E0, 0x406B, 0x46F4, \
75
  { 0x99, 0xBA, 0x5A, 0x00, 0x9F, 0x8D, 0x22, 0x25} }
76
77
//Event-specific GUIDs, used by the OS to differentiate events
78
// {A3DA04E0-57D7-482A-A1C1-61DA5F95BACB}
79
#define NS_PLACES_INIT_COMPLETE_EVENT_CID \
80
  { 0xA3DA04E0, 0x57D7, 0x482A, \
81
  { 0xA1, 0xC1, 0x61, 0xDA, 0x5F, 0x95, 0xBA, 0xCB} }
82
// {917B96B1-ECAD-4DAB-A760-8D49027748AE}
83
#define NS_SESSION_STORE_WINDOW_RESTORED_EVENT_CID \
84
  { 0x917B96B1, 0xECAD, 0x4DAB, \
85
  { 0xA7, 0x60, 0x8D, 0x49, 0x02, 0x77, 0x48, 0xAE} }
86
// {26D1E091-0AE7-4F49-A554-4214445C505C}
87
#define NS_XPCOM_SHUTDOWN_EVENT_CID \
88
  { 0x26D1E091, 0x0AE7, 0x4F49, \
89
  { 0xA5, 0x54, 0x42, 0x14, 0x44, 0x5C, 0x50, 0x5C} }
90
91
static NS_DEFINE_CID(kApplicationTracingCID,
92
  NS_APPLICATION_TRACING_CID);
93
static NS_DEFINE_CID(kPlacesInitCompleteCID,
94
  NS_PLACES_INIT_COMPLETE_EVENT_CID);
95
static NS_DEFINE_CID(kSessionStoreWindowRestoredCID,
96
  NS_SESSION_STORE_WINDOW_RESTORED_EVENT_CID);
97
static NS_DEFINE_CID(kXPCOMShutdownCID,
98
  NS_XPCOM_SHUTDOWN_EVENT_CID);
99
#endif //defined(XP_WIN)
100
101
using namespace mozilla;
102
103
class nsAppExitEvent : public mozilla::Runnable {
104
private:
105
  RefPtr<nsAppStartup> mService;
106
107
public:
108
  explicit nsAppExitEvent(nsAppStartup* service)
109
    : mozilla::Runnable("nsAppExitEvent")
110
    , mService(service)
111
0
  {
112
0
  }
113
114
0
  NS_IMETHOD Run() override {
115
0
    // Tell the appshell to exit
116
0
    mService->mAppShell->Exit();
117
0
118
0
    mService->mRunning = false;
119
0
    return NS_OK;
120
0
  }
121
};
122
123
/**
124
 * Computes an approximation of the absolute time represented by @a stamp
125
 * which is comparable to those obtained via PR_Now(). If the current absolute
126
 * time varies a lot (e.g. DST adjustments) since the first call then the
127
 * resulting times may be inconsistent.
128
 *
129
 * @param stamp The timestamp to be converted
130
 * @returns The converted timestamp
131
 */
132
static uint64_t
133
ComputeAbsoluteTimestamp(TimeStamp stamp)
134
0
{
135
0
  static PRTime sAbsoluteNow = PR_Now();
136
0
  static TimeStamp sMonotonicNow = TimeStamp::Now();
137
0
138
0
  return sAbsoluteNow - (sMonotonicNow - stamp).ToMicroseconds();
139
0
}
140
141
//
142
// nsAppStartup
143
//
144
145
nsAppStartup::nsAppStartup() :
146
  mConsiderQuitStopper(0),
147
  mRunning(false),
148
  mShuttingDown(false),
149
  mStartingUp(true),
150
  mAttemptingQuit(false),
151
  mRestart(false),
152
  mInterrupted(false),
153
  mIsSafeModeNecessary(false),
154
  mStartupCrashTrackingEnded(false),
155
  mRestartNotSameProfile(false)
156
0
{ }
157
158
159
nsresult
160
nsAppStartup::Init()
161
0
{
162
0
  nsresult rv;
163
0
164
0
  // Create widget application shell
165
0
  mAppShell = do_GetService(kAppShellCID, &rv);
166
0
  NS_ENSURE_SUCCESS(rv, rv);
167
0
168
0
  nsCOMPtr<nsIObserverService> os =
169
0
    mozilla::services::GetObserverService();
170
0
  if (!os)
171
0
    return NS_ERROR_FAILURE;
172
0
173
0
  os->AddObserver(this, "quit-application", true);
174
0
  os->AddObserver(this, "quit-application-forced", true);
175
0
  os->AddObserver(this, "sessionstore-init-started", true);
176
0
  os->AddObserver(this, "sessionstore-windows-restored", true);
177
0
  os->AddObserver(this, "profile-change-teardown", true);
178
0
  os->AddObserver(this, "xul-window-registered", true);
179
0
  os->AddObserver(this, "xul-window-destroyed", true);
180
0
  os->AddObserver(this, "profile-before-change", true);
181
0
  os->AddObserver(this, "xpcom-shutdown", true);
182
0
183
#if defined(XP_WIN)
184
  os->AddObserver(this, "places-init-complete", true);
185
  // This last event is only interesting to us for xperf-based measures
186
187
  // Initialize interaction with profiler
188
  mProbesManager =
189
    new ProbeManager(
190
                     kApplicationTracingCID,
191
                     NS_LITERAL_CSTRING("Application startup probe"));
192
  // Note: The operation is meant mostly for in-house profiling.
193
  // Therefore, we do not warn if probes manager cannot be initialized
194
195
  if (mProbesManager) {
196
    mPlacesInitCompleteProbe =
197
      mProbesManager->
198
      GetProbe(kPlacesInitCompleteCID,
199
               NS_LITERAL_CSTRING("places-init-complete"));
200
    NS_WARNING_ASSERTION(mPlacesInitCompleteProbe,
201
                         "Cannot initialize probe 'places-init-complete'");
202
203
    mSessionWindowRestoredProbe =
204
      mProbesManager->
205
      GetProbe(kSessionStoreWindowRestoredCID,
206
               NS_LITERAL_CSTRING("sessionstore-windows-restored"));
207
    NS_WARNING_ASSERTION(
208
      mSessionWindowRestoredProbe,
209
      "Cannot initialize probe 'sessionstore-windows-restored'");
210
211
    mXPCOMShutdownProbe =
212
      mProbesManager->
213
      GetProbe(kXPCOMShutdownCID,
214
               NS_LITERAL_CSTRING("xpcom-shutdown"));
215
    NS_WARNING_ASSERTION(mXPCOMShutdownProbe,
216
                         "Cannot initialize probe 'xpcom-shutdown'");
217
218
    rv = mProbesManager->StartSession();
219
    NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
220
                         "Cannot initialize system probe manager");
221
  }
222
#endif //defined(XP_WIN)
223
224
0
  return NS_OK;
225
0
}
226
227
228
//
229
// nsAppStartup->nsISupports
230
//
231
232
NS_IMPL_ISUPPORTS(nsAppStartup,
233
                  nsIAppStartup,
234
                  nsIWindowCreator,
235
                  nsIWindowCreator2,
236
                  nsIObserver,
237
                  nsISupportsWeakReference)
238
239
240
//
241
// nsAppStartup->nsIAppStartup
242
//
243
244
NS_IMETHODIMP
245
nsAppStartup::CreateHiddenWindow()
246
0
{
247
#if defined(MOZ_WIDGET_UIKIT)
248
  return NS_OK;
249
#else
250
  nsCOMPtr<nsIAppShellService> appShellService
251
0
    (do_GetService(NS_APPSHELLSERVICE_CONTRACTID));
252
0
  NS_ENSURE_TRUE(appShellService, NS_ERROR_FAILURE);
253
0
254
0
  return appShellService->CreateHiddenWindow();
255
0
#endif
256
0
}
257
258
259
NS_IMETHODIMP
260
nsAppStartup::DestroyHiddenWindow()
261
0
{
262
#if defined(MOZ_WIDGET_UIKIT)
263
  return NS_OK;
264
#else
265
  nsCOMPtr<nsIAppShellService> appShellService
266
0
    (do_GetService(NS_APPSHELLSERVICE_CONTRACTID));
267
0
  NS_ENSURE_TRUE(appShellService, NS_ERROR_FAILURE);
268
0
269
0
  return appShellService->DestroyHiddenWindow();
270
0
#endif
271
0
}
272
273
NS_IMETHODIMP
274
nsAppStartup::Run(void)
275
0
{
276
0
  NS_ASSERTION(!mRunning, "Reentrant appstartup->Run()");
277
0
278
0
  // If we have no windows open and no explicit calls to
279
0
  // enterLastWindowClosingSurvivalArea, or somebody has explicitly called
280
0
  // quit, don't bother running the event loop which would probably leave us
281
0
  // with a zombie process.
282
0
283
0
  if (!mShuttingDown && mConsiderQuitStopper != 0) {
284
#ifdef XP_MACOSX
285
    EnterLastWindowClosingSurvivalArea();
286
#endif
287
288
0
    mRunning = true;
289
0
290
0
    nsresult rv = mAppShell->Run();
291
0
    if (NS_FAILED(rv))
292
0
      return rv;
293
0
  }
294
0
295
0
  nsresult retval = NS_OK;
296
0
  if (mRestart) {
297
0
    retval = NS_SUCCESS_RESTART_APP;
298
0
  } else if (mRestartNotSameProfile) {
299
0
    retval = NS_SUCCESS_RESTART_APP_NOT_SAME_PROFILE;
300
0
  }
301
0
302
0
  return retval;
303
0
}
304
305
306
307
NS_IMETHODIMP
308
nsAppStartup::Quit(uint32_t aMode)
309
0
{
310
0
  uint32_t ferocity = (aMode & 0xF);
311
0
312
0
  // Quit the application. We will asynchronously call the appshell's
313
0
  // Exit() method via nsAppExitEvent to allow one last pass
314
0
  // through any events in the queue. This guarantees a tidy cleanup.
315
0
  nsresult rv = NS_OK;
316
0
  bool postedExitEvent = false;
317
0
318
0
  if (mShuttingDown)
319
0
    return NS_OK;
320
0
321
0
  // If we're considering quitting, we will only do so if:
322
0
  if (ferocity == eConsiderQuit) {
323
#ifdef XP_MACOSX
324
    nsCOMPtr<nsIAppShellService> appShell
325
      (do_GetService(NS_APPSHELLSERVICE_CONTRACTID));
326
    bool hasHiddenPrivateWindow = false;
327
    if (appShell) {
328
      appShell->GetHasHiddenPrivateWindow(&hasHiddenPrivateWindow);
329
    }
330
    int32_t suspiciousCount = hasHiddenPrivateWindow ? 2 : 1;
331
#endif
332
333
0
    if (mConsiderQuitStopper == 0) {
334
0
      // there are no windows...
335
0
      ferocity = eAttemptQuit;
336
0
    }
337
#ifdef XP_MACOSX
338
    else if (mConsiderQuitStopper == suspiciousCount) {
339
      // ... or there is only a hiddenWindow left, and it's useless:
340
341
      // Failure shouldn't be fatal, but will abort quit attempt:
342
      if (!appShell)
343
        return NS_OK;
344
345
      bool usefulHiddenWindow;
346
      appShell->GetApplicationProvidedHiddenWindow(&usefulHiddenWindow);
347
      nsCOMPtr<nsIXULWindow> hiddenWindow;
348
      appShell->GetHiddenWindow(getter_AddRefs(hiddenWindow));
349
      // If the remaining windows are useful, we won't quit:
350
      nsCOMPtr<nsIXULWindow> hiddenPrivateWindow;
351
      if (hasHiddenPrivateWindow) {
352
        appShell->GetHiddenPrivateWindow(getter_AddRefs(hiddenPrivateWindow));
353
        if ((!hiddenWindow && !hiddenPrivateWindow) || usefulHiddenWindow)
354
          return NS_OK;
355
      } else if (!hiddenWindow || usefulHiddenWindow) {
356
        return NS_OK;
357
      }
358
359
      ferocity = eAttemptQuit;
360
    }
361
#endif
362
  }
363
0
364
0
  nsCOMPtr<nsIObserverService> obsService;
365
0
  if (ferocity == eAttemptQuit || ferocity == eForceQuit) {
366
0
367
0
    nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
368
0
    nsCOMPtr<nsIWindowMediator> mediator (do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));
369
0
    if (mediator) {
370
0
      mediator->GetEnumerator(nullptr, getter_AddRefs(windowEnumerator));
371
0
      if (windowEnumerator) {
372
0
        bool more;
373
0
        windowEnumerator->HasMoreElements(&more);
374
0
        // If we reported no windows, we definitely shouldn't be
375
0
        // iterating any here.
376
0
        MOZ_ASSERT_IF(!mConsiderQuitStopper, !more);
377
0
378
0
        while (more) {
379
0
          nsCOMPtr<nsISupports> window;
380
0
          windowEnumerator->GetNext(getter_AddRefs(window));
381
0
          nsCOMPtr<nsPIDOMWindowOuter> domWindow(do_QueryInterface(window));
382
0
          if (domWindow) {
383
0
            if (!domWindow->CanClose())
384
0
              return NS_OK;
385
0
          }
386
0
          windowEnumerator->HasMoreElements(&more);
387
0
        }
388
0
      }
389
0
    }
390
0
391
0
    PROFILER_ADD_MARKER("Shutdown start");
392
0
    mozilla::RecordShutdownStartTimeStamp();
393
0
    mShuttingDown = true;
394
0
    if (!mRestart) {
395
0
      mRestart = (aMode & eRestart) != 0;
396
0
    }
397
0
398
0
    if (!mRestartNotSameProfile) {
399
0
      mRestartNotSameProfile = (aMode & eRestartNotSameProfile) != 0;
400
0
    }
401
0
402
0
    if (mRestart || mRestartNotSameProfile) {
403
0
      // Mark the next startup as a restart.
404
0
      PR_SetEnv("MOZ_APP_RESTART=1");
405
0
406
0
      /* Firefox-restarts reuse the process so regular process start-time isn't
407
0
         a useful indicator of startup time anymore. */
408
0
      TimeStamp::RecordProcessRestart();
409
0
    }
410
0
411
0
    obsService = mozilla::services::GetObserverService();
412
0
413
0
    if (!mAttemptingQuit) {
414
0
      mAttemptingQuit = true;
415
#ifdef XP_MACOSX
416
      // now even the Mac wants to quit when the last window is closed
417
      ExitLastWindowClosingSurvivalArea();
418
#endif
419
0
      if (obsService)
420
0
        obsService->NotifyObservers(nullptr, "quit-application-granted", nullptr);
421
0
    }
422
0
423
0
    /* Enumerate through each open window and close it. It's important to do
424
0
       this before we forcequit because this can control whether we really quit
425
0
       at all. e.g. if one of these windows has an unload handler that
426
0
       opens a new window. Ugh. I know. */
427
0
    CloseAllWindows();
428
0
429
0
    if (mediator) {
430
0
      if (ferocity == eAttemptQuit) {
431
0
        ferocity = eForceQuit; // assume success
432
0
433
0
        /* Were we able to immediately close all windows? if not, eAttemptQuit
434
0
           failed. This could happen for a variety of reasons; in fact it's
435
0
           very likely. Perhaps we're being called from JS and the window->Close
436
0
           method hasn't had a chance to wrap itself up yet. So give up.
437
0
           We'll return (with eConsiderQuit) as the remaining windows are
438
0
           closed. */
439
0
        mediator->GetEnumerator(nullptr, getter_AddRefs(windowEnumerator));
440
0
        if (windowEnumerator) {
441
0
          bool more;
442
0
          while (NS_SUCCEEDED(windowEnumerator->HasMoreElements(&more)) &&
443
0
                 more) {
444
0
            /* we can't quit immediately. we'll try again as the last window
445
0
               finally closes. */
446
0
            ferocity = eAttemptQuit;
447
0
            nsCOMPtr<nsISupports> window;
448
0
            windowEnumerator->GetNext(getter_AddRefs(window));
449
0
            nsCOMPtr<nsPIDOMWindowOuter> domWindow = do_QueryInterface(window);
450
0
            if (domWindow) {
451
0
              if (!domWindow->Closed()) {
452
0
                rv = NS_ERROR_FAILURE;
453
0
                break;
454
0
              }
455
0
            }
456
0
          }
457
0
        }
458
0
      }
459
0
    }
460
0
  }
461
0
462
0
  if (ferocity == eForceQuit) {
463
0
    // do it!
464
0
465
0
    // No chance of the shutdown being cancelled from here on; tell people
466
0
    // we're shutting down for sure while all services are still available.
467
0
    if (obsService) {
468
0
      obsService->NotifyObservers(nullptr, "quit-application",
469
0
        (mRestart || mRestartNotSameProfile) ? u"restart" : u"shutdown");
470
0
    }
471
0
472
0
    if (!mRunning) {
473
0
      postedExitEvent = true;
474
0
    }
475
0
    else {
476
0
      // no matter what, make sure we send the exit event.  If
477
0
      // worst comes to worst, we'll do a leaky shutdown but we WILL
478
0
      // shut down. Well, assuming that all *this* stuff works ;-).
479
0
      nsCOMPtr<nsIRunnable> event = new nsAppExitEvent(this);
480
0
      rv = NS_DispatchToCurrentThread(event);
481
0
      if (NS_SUCCEEDED(rv)) {
482
0
        postedExitEvent = true;
483
0
      }
484
0
      else {
485
0
        NS_WARNING("failed to dispatch nsAppExitEvent");
486
0
      }
487
0
    }
488
0
  }
489
0
490
0
  // turn off the reentrancy check flag, but not if we have
491
0
  // more asynchronous work to do still.
492
0
  if (!postedExitEvent)
493
0
    mShuttingDown = false;
494
0
  return rv;
495
0
}
496
497
498
void
499
nsAppStartup::CloseAllWindows()
500
0
{
501
0
  nsCOMPtr<nsIWindowMediator> mediator
502
0
    (do_GetService(NS_WINDOWMEDIATOR_CONTRACTID));
503
0
504
0
  nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
505
0
506
0
  mediator->GetEnumerator(nullptr, getter_AddRefs(windowEnumerator));
507
0
508
0
  if (!windowEnumerator)
509
0
    return;
510
0
511
0
  bool more;
512
0
  while (NS_SUCCEEDED(windowEnumerator->HasMoreElements(&more)) && more) {
513
0
    nsCOMPtr<nsISupports> isupports;
514
0
    if (NS_FAILED(windowEnumerator->GetNext(getter_AddRefs(isupports))))
515
0
      break;
516
0
517
0
    nsCOMPtr<nsPIDOMWindowOuter> window = do_QueryInterface(isupports);
518
0
    NS_ASSERTION(window, "not an nsPIDOMWindow");
519
0
    if (window) {
520
0
      window->ForceClose();
521
0
    }
522
0
  }
523
0
}
524
525
NS_IMETHODIMP
526
nsAppStartup::EnterLastWindowClosingSurvivalArea(void)
527
0
{
528
0
  ++mConsiderQuitStopper;
529
0
  return NS_OK;
530
0
}
531
532
533
NS_IMETHODIMP
534
nsAppStartup::ExitLastWindowClosingSurvivalArea(void)
535
0
{
536
0
  NS_ASSERTION(mConsiderQuitStopper > 0, "consider quit stopper out of bounds");
537
0
  --mConsiderQuitStopper;
538
0
539
0
  if (mRunning)
540
0
    Quit(eConsiderQuit);
541
0
542
0
  return NS_OK;
543
0
}
544
545
//
546
// nsAppStartup->nsIAppStartup2
547
//
548
549
NS_IMETHODIMP
550
nsAppStartup::GetShuttingDown(bool *aResult)
551
0
{
552
0
  *aResult = mShuttingDown;
553
0
  return NS_OK;
554
0
}
555
556
NS_IMETHODIMP
557
nsAppStartup::GetStartingUp(bool *aResult)
558
0
{
559
0
  *aResult = mStartingUp;
560
0
  return NS_OK;
561
0
}
562
563
NS_IMETHODIMP
564
nsAppStartup::DoneStartingUp()
565
0
{
566
0
  // This must be called once at most
567
0
  MOZ_ASSERT(mStartingUp);
568
0
569
0
  mStartingUp = false;
570
0
  return NS_OK;
571
0
}
572
573
NS_IMETHODIMP
574
nsAppStartup::GetRestarting(bool *aResult)
575
0
{
576
0
  *aResult = mRestart;
577
0
  return NS_OK;
578
0
}
579
580
NS_IMETHODIMP
581
nsAppStartup::GetWasRestarted(bool *aResult)
582
0
{
583
0
  char *mozAppRestart = PR_GetEnv("MOZ_APP_RESTART");
584
0
585
0
  /* When calling PR_SetEnv() with an empty value the existing variable may
586
0
   * be unset or set to the empty string depending on the underlying platform
587
0
   * thus we have to check if the variable is present and not empty. */
588
0
  *aResult = mozAppRestart && (strcmp(mozAppRestart, "") != 0);
589
0
590
0
  return NS_OK;
591
0
}
592
593
NS_IMETHODIMP
594
nsAppStartup::SetInterrupted(bool aInterrupted)
595
0
{
596
0
  mInterrupted = aInterrupted;
597
0
  return NS_OK;
598
0
}
599
600
NS_IMETHODIMP
601
nsAppStartup::GetInterrupted(bool *aInterrupted)
602
0
{
603
0
  *aInterrupted = mInterrupted;
604
0
  return NS_OK;
605
0
}
606
607
//
608
// nsAppStartup->nsIWindowCreator
609
//
610
611
NS_IMETHODIMP
612
nsAppStartup::CreateChromeWindow(nsIWebBrowserChrome *aParent,
613
                                 uint32_t aChromeFlags,
614
                                 nsIWebBrowserChrome **_retval)
615
0
{
616
0
  bool cancel;
617
0
  return CreateChromeWindow2(aParent, aChromeFlags, nullptr, nullptr, 0, &cancel, _retval);
618
0
}
619
620
621
//
622
// nsAppStartup->nsIWindowCreator2
623
//
624
625
NS_IMETHODIMP
626
nsAppStartup::SetScreenId(uint32_t aScreenId)
627
0
{
628
0
  nsCOMPtr<nsIAppShellService> appShell(do_GetService(NS_APPSHELLSERVICE_CONTRACTID));
629
0
  if (!appShell) {
630
0
    return NS_ERROR_FAILURE;
631
0
  }
632
0
633
0
  return appShell->SetScreenId(aScreenId);
634
0
}
635
636
NS_IMETHODIMP
637
nsAppStartup::CreateChromeWindow2(nsIWebBrowserChrome *aParent,
638
                                  uint32_t aChromeFlags,
639
                                  nsITabParent *aOpeningTab,
640
                                  mozIDOMWindowProxy* aOpener,
641
                                  uint64_t aNextTabParentId,
642
                                  bool *aCancel,
643
                                  nsIWebBrowserChrome **_retval)
644
0
{
645
0
  NS_ENSURE_ARG_POINTER(aCancel);
646
0
  NS_ENSURE_ARG_POINTER(_retval);
647
0
  *aCancel = false;
648
0
  *_retval = 0;
649
0
650
0
  // Non-modal windows cannot be opened if we are attempting to quit
651
0
  if (mAttemptingQuit && (aChromeFlags & nsIWebBrowserChrome::CHROME_MODAL) == 0)
652
0
    return NS_ERROR_ILLEGAL_DURING_SHUTDOWN;
653
0
654
0
  nsCOMPtr<nsIXULWindow> newWindow;
655
0
656
0
  if (aParent) {
657
0
    nsCOMPtr<nsIXULWindow> xulParent(do_GetInterface(aParent));
658
0
    NS_ASSERTION(xulParent, "window created using non-XUL parent. that's unexpected, but may work.");
659
0
660
0
    if (xulParent)
661
0
      xulParent->CreateNewWindow(aChromeFlags, aOpeningTab, aOpener,
662
0
                                 aNextTabParentId,
663
0
                                 getter_AddRefs(newWindow));
664
0
    // And if it fails, don't try again without a parent. It could fail
665
0
    // intentionally (bug 115969).
666
0
  } else { // try using basic methods:
667
0
    MOZ_RELEASE_ASSERT(aNextTabParentId == 0,
668
0
                       "Unexpected aNextTabParentId, we shouldn't ever have a next actor ID without a parent");
669
0
670
0
    /* You really shouldn't be making dependent windows without a parent.
671
0
      But unparented modal (and therefore dependent) windows happen
672
0
      in our codebase, so we allow it after some bellyaching: */
673
0
    if (aChromeFlags & nsIWebBrowserChrome::CHROME_DEPENDENT)
674
0
      NS_WARNING("dependent window created without a parent");
675
0
676
0
    nsCOMPtr<nsIAppShellService> appShell(do_GetService(NS_APPSHELLSERVICE_CONTRACTID));
677
0
    if (!appShell)
678
0
      return NS_ERROR_FAILURE;
679
0
680
0
    appShell->CreateTopLevelWindow(0, 0, aChromeFlags,
681
0
                                   nsIAppShellService::SIZE_TO_CONTENT,
682
0
                                   nsIAppShellService::SIZE_TO_CONTENT,
683
0
                                   aOpeningTab, aOpener,
684
0
                                   getter_AddRefs(newWindow));
685
0
  }
686
0
687
0
  // if anybody gave us anything to work with, use it
688
0
  if (newWindow) {
689
0
    nsCOMPtr<nsIInterfaceRequestor> thing(do_QueryInterface(newWindow));
690
0
    if (thing)
691
0
      CallGetInterface(thing.get(), _retval);
692
0
  }
693
0
694
0
  return *_retval ? NS_OK : NS_ERROR_FAILURE;
695
0
}
696
697
698
//
699
// nsAppStartup->nsIObserver
700
//
701
702
NS_IMETHODIMP
703
nsAppStartup::Observe(nsISupports *aSubject,
704
                      const char *aTopic, const char16_t *aData)
705
0
{
706
0
  NS_ASSERTION(mAppShell, "appshell service notified before appshell built");
707
0
  if (!strcmp(aTopic, "quit-application-forced")) {
708
0
    mShuttingDown = true;
709
0
  }
710
0
  else if (!strcmp(aTopic, "profile-change-teardown")) {
711
0
    if (!mShuttingDown) {
712
0
      EnterLastWindowClosingSurvivalArea();
713
0
      CloseAllWindows();
714
0
      ExitLastWindowClosingSurvivalArea();
715
0
    }
716
0
  } else if (!strcmp(aTopic, "xul-window-registered")) {
717
0
    EnterLastWindowClosingSurvivalArea();
718
0
  } else if (!strcmp(aTopic, "xul-window-destroyed")) {
719
0
    ExitLastWindowClosingSurvivalArea();
720
0
  } else if (!strcmp(aTopic, "sessionstore-windows-restored")) {
721
0
    StartupTimeline::Record(StartupTimeline::SESSION_RESTORED);
722
0
    IOInterposer::EnteringNextStage();
723
#if defined(XP_WIN)
724
    if (mSessionWindowRestoredProbe) {
725
      mSessionWindowRestoredProbe->Trigger();
726
    }
727
  } else if (!strcmp(aTopic, "places-init-complete")) {
728
    if (mPlacesInitCompleteProbe) {
729
      mPlacesInitCompleteProbe->Trigger();
730
    }
731
#endif //defined(XP_WIN)
732
0
  } else if (!strcmp(aTopic, "sessionstore-init-started")) {
733
0
    StartupTimeline::Record(StartupTimeline::SESSION_RESTORE_INIT);
734
0
  } else if (!strcmp(aTopic, "xpcom-shutdown")) {
735
0
    IOInterposer::EnteringNextStage();
736
#if defined(XP_WIN)
737
    if (mXPCOMShutdownProbe) {
738
      mXPCOMShutdownProbe->Trigger();
739
    }
740
#endif // defined(XP_WIN)
741
0
  } else if (!strcmp(aTopic, "quit-application")) {
742
0
    StartupTimeline::Record(StartupTimeline::QUIT_APPLICATION);
743
0
  } else if (!strcmp(aTopic, "profile-before-change")) {
744
0
    StartupTimeline::Record(StartupTimeline::PROFILE_BEFORE_CHANGE);
745
0
  } else {
746
0
    NS_ERROR("Unexpected observer topic.");
747
0
  }
748
0
749
0
  return NS_OK;
750
0
}
751
752
NS_IMETHODIMP
753
nsAppStartup::GetStartupInfo(JSContext* aCx, JS::MutableHandle<JS::Value> aRetval)
754
0
{
755
0
  JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
756
0
757
0
  aRetval.setObject(*obj);
758
0
759
0
  TimeStamp procTime = StartupTimeline::Get(StartupTimeline::PROCESS_CREATION);
760
0
761
0
  if (procTime.IsNull()) {
762
0
    bool error = false;
763
0
764
0
    procTime = TimeStamp::ProcessCreation(&error);
765
0
766
0
    if (error) {
767
0
      Telemetry::Accumulate(Telemetry::STARTUP_MEASUREMENT_ERRORS,
768
0
        StartupTimeline::PROCESS_CREATION);
769
0
    }
770
0
771
0
    StartupTimeline::Record(StartupTimeline::PROCESS_CREATION, procTime);
772
0
  }
773
0
774
0
  for (int i = StartupTimeline::PROCESS_CREATION;
775
0
       i < StartupTimeline::MAX_EVENT_ID;
776
0
       ++i)
777
0
  {
778
0
    StartupTimeline::Event ev = static_cast<StartupTimeline::Event>(i);
779
0
    TimeStamp stamp = StartupTimeline::Get(ev);
780
0
781
0
    if (stamp.IsNull() && (ev == StartupTimeline::MAIN)) {
782
0
      // Always define main to aid with bug 689256.
783
0
      stamp = procTime;
784
0
      MOZ_ASSERT(!stamp.IsNull());
785
0
      Telemetry::Accumulate(Telemetry::STARTUP_MEASUREMENT_ERRORS,
786
0
        StartupTimeline::MAIN);
787
0
    }
788
0
789
0
    if (!stamp.IsNull()) {
790
0
      if (stamp >= procTime) {
791
0
        PRTime prStamp = ComputeAbsoluteTimestamp(stamp)
792
0
          / PR_USEC_PER_MSEC;
793
0
        JS::Rooted<JSObject*> date(aCx, JS::NewDateObject(aCx, JS::TimeClip(prStamp)));
794
0
        JS_DefineProperty(aCx, obj, StartupTimeline::Describe(ev), date, JSPROP_ENUMERATE);
795
0
      } else {
796
0
        Telemetry::Accumulate(Telemetry::STARTUP_MEASUREMENT_ERRORS, ev);
797
0
      }
798
0
    }
799
0
  }
800
0
801
0
  return NS_OK;
802
0
}
803
804
NS_IMETHODIMP
805
nsAppStartup::GetAutomaticSafeModeNecessary(bool *_retval)
806
0
{
807
0
  NS_ENSURE_ARG_POINTER(_retval);
808
0
809
0
  bool alwaysSafe = false;
810
0
  Preferences::GetBool(kPrefAlwaysUseSafeMode, &alwaysSafe);
811
0
812
0
  if (!alwaysSafe) {
813
#if DEBUG
814
    mIsSafeModeNecessary = false;
815
#else
816
    mIsSafeModeNecessary &= !PR_GetEnv("MOZ_DISABLE_AUTO_SAFE_MODE");
817
0
#endif
818
0
  }
819
0
820
0
  *_retval = mIsSafeModeNecessary;
821
0
  return NS_OK;
822
0
}
823
824
NS_IMETHODIMP
825
nsAppStartup::TrackStartupCrashBegin(bool *aIsSafeModeNecessary)
826
0
{
827
0
  const int32_t MAX_TIME_SINCE_STARTUP = 6 * 60 * 60 * 1000;
828
0
  const int32_t MAX_STARTUP_BUFFER = 10;
829
0
  nsresult rv;
830
0
831
0
  mStartupCrashTrackingEnded = false;
832
0
833
0
  StartupTimeline::Record(StartupTimeline::STARTUP_CRASH_DETECTION_BEGIN);
834
0
835
0
  bool hasLastSuccess = Preferences::HasUserValue(kPrefLastSuccess);
836
0
  if (!hasLastSuccess) {
837
0
    // Clear so we don't get stuck with SafeModeNecessary returning true if we
838
0
    // have had too many recent crashes and the last success pref is missing.
839
0
    Preferences::ClearUser(kPrefRecentCrashes);
840
0
    return NS_ERROR_NOT_AVAILABLE;
841
0
  }
842
0
843
0
  bool inSafeMode = false;
844
0
  nsCOMPtr<nsIXULRuntime> xr = do_GetService(XULRUNTIME_SERVICE_CONTRACTID);
845
0
  NS_ENSURE_TRUE(xr, NS_ERROR_FAILURE);
846
0
847
0
  xr->GetInSafeMode(&inSafeMode);
848
0
849
0
  PRTime replacedLockTime;
850
0
  rv = xr->GetReplacedLockTime(&replacedLockTime);
851
0
852
0
  if (NS_FAILED(rv) || !replacedLockTime) {
853
0
    if (!inSafeMode)
854
0
      Preferences::ClearUser(kPrefRecentCrashes);
855
0
    GetAutomaticSafeModeNecessary(aIsSafeModeNecessary);
856
0
    return NS_OK;
857
0
  }
858
0
859
0
  // check whether safe mode is necessary
860
0
  int32_t maxResumedCrashes = -1;
861
0
  rv = Preferences::GetInt(kPrefMaxResumedCrashes, &maxResumedCrashes);
862
0
  NS_ENSURE_SUCCESS(rv, NS_OK);
863
0
864
0
  int32_t recentCrashes = 0;
865
0
  Preferences::GetInt(kPrefRecentCrashes, &recentCrashes);
866
0
  mIsSafeModeNecessary = (recentCrashes > maxResumedCrashes && maxResumedCrashes != -1);
867
0
868
0
  // Bug 731613 - Don't check if the last startup was a crash if XRE_PROFILE_PATH is set.  After
869
0
  // profile manager, the profile lock's mod. time has been changed so can't be used on this startup.
870
0
  // After a restart, it's safe to assume the last startup was successful.
871
0
  char *xreProfilePath = PR_GetEnv("XRE_PROFILE_PATH");
872
0
  if (xreProfilePath) {
873
0
    GetAutomaticSafeModeNecessary(aIsSafeModeNecessary);
874
0
    return NS_ERROR_NOT_AVAILABLE;
875
0
  }
876
0
877
0
  // time of last successful startup
878
0
  int32_t lastSuccessfulStartup;
879
0
  rv = Preferences::GetInt(kPrefLastSuccess, &lastSuccessfulStartup);
880
0
  NS_ENSURE_SUCCESS(rv, rv);
881
0
882
0
  int32_t lockSeconds = (int32_t)(replacedLockTime / PR_MSEC_PER_SEC);
883
0
884
0
  // started close enough to good startup so call it good
885
0
  if (lockSeconds <= lastSuccessfulStartup + MAX_STARTUP_BUFFER
886
0
      && lockSeconds >= lastSuccessfulStartup - MAX_STARTUP_BUFFER) {
887
0
    GetAutomaticSafeModeNecessary(aIsSafeModeNecessary);
888
0
    return NS_OK;
889
0
  }
890
0
891
0
  // sanity check that the pref set at last success is not greater than the current time
892
0
  if (PR_Now() / PR_USEC_PER_SEC <= lastSuccessfulStartup)
893
0
    return NS_ERROR_FAILURE;
894
0
895
0
  // The last startup was a crash so include it in the count regardless of when it happened.
896
0
  Telemetry::Accumulate(Telemetry::STARTUP_CRASH_DETECTED, true);
897
0
898
0
  if (inSafeMode) {
899
0
    GetAutomaticSafeModeNecessary(aIsSafeModeNecessary);
900
0
    return NS_OK;
901
0
  }
902
0
903
0
  PRTime now = (PR_Now() / PR_USEC_PER_MSEC);
904
0
  // if the last startup attempt which crashed was in the last 6 hours
905
0
  if (replacedLockTime >= now - MAX_TIME_SINCE_STARTUP) {
906
0
    NS_WARNING("Last startup was detected as a crash.");
907
0
    recentCrashes++;
908
0
    rv = Preferences::SetInt(kPrefRecentCrashes, recentCrashes);
909
0
  } else {
910
0
    // Otherwise ignore that crash and all previous since it may not be applicable anymore
911
0
    // and we don't want someone to get stuck in safe mode if their prefs are read-only.
912
0
    rv = Preferences::ClearUser(kPrefRecentCrashes);
913
0
  }
914
0
  NS_ENSURE_SUCCESS(rv, rv);
915
0
916
0
  // recalculate since recent crashes count may have changed above
917
0
  mIsSafeModeNecessary = (recentCrashes > maxResumedCrashes && maxResumedCrashes != -1);
918
0
919
0
  nsCOMPtr<nsIPrefService> prefs = Preferences::GetService();
920
0
  rv = static_cast<Preferences *>(prefs.get())->SavePrefFileBlocking(); // flush prefs to disk since we are tracking crashes
921
0
  NS_ENSURE_SUCCESS(rv, rv);
922
0
923
0
  GetAutomaticSafeModeNecessary(aIsSafeModeNecessary);
924
0
  return rv;
925
0
}
926
927
static nsresult
928
RemoveIncompleteStartupFile()
929
0
{
930
0
  nsCOMPtr<nsIFile> file;
931
0
  MOZ_TRY(NS_GetSpecialDirectory(NS_APP_USER_PROFILE_LOCAL_50_DIR, getter_AddRefs(file)));
932
0
933
0
  MOZ_TRY_VAR(file, mozilla::startup::GetIncompleteStartupFile(file));
934
0
  return file->Remove(false);
935
0
}
936
937
NS_IMETHODIMP
938
nsAppStartup::TrackStartupCrashEnd()
939
0
{
940
0
  bool inSafeMode = false;
941
0
  nsCOMPtr<nsIXULRuntime> xr = do_GetService(XULRUNTIME_SERVICE_CONTRACTID);
942
0
  if (xr)
943
0
    xr->GetInSafeMode(&inSafeMode);
944
0
945
0
  // return if we already ended or we're restarting into safe mode
946
0
  if (mStartupCrashTrackingEnded || (mIsSafeModeNecessary && !inSafeMode))
947
0
    return NS_OK;
948
0
  mStartupCrashTrackingEnded = true;
949
0
950
0
  StartupTimeline::Record(StartupTimeline::STARTUP_CRASH_DETECTION_END);
951
0
952
0
  // Remove the incomplete startup canary file, so the next startup doesn't
953
0
  // detect a recent startup crash.
954
0
  Unused << NS_WARN_IF(NS_FAILED(RemoveIncompleteStartupFile()));
955
0
956
0
  // Use the timestamp of XRE_main as an approximation for the lock file timestamp.
957
0
  // See MAX_STARTUP_BUFFER for the buffer time period.
958
0
  TimeStamp mainTime = StartupTimeline::Get(StartupTimeline::MAIN);
959
0
  nsresult rv;
960
0
961
0
  if (mainTime.IsNull()) {
962
0
    NS_WARNING("Could not get StartupTimeline::MAIN time.");
963
0
  } else {
964
0
    uint64_t lockFileTime = ComputeAbsoluteTimestamp(mainTime);
965
0
966
0
    rv = Preferences::SetInt(kPrefLastSuccess,
967
0
      (int32_t)(lockFileTime / PR_USEC_PER_SEC));
968
0
969
0
    if (NS_FAILED(rv))
970
0
      NS_WARNING("Could not set startup crash detection pref.");
971
0
  }
972
0
973
0
  if (inSafeMode && mIsSafeModeNecessary) {
974
0
    // On a successful startup in automatic safe mode, allow the user one more crash
975
0
    // in regular mode before returning to safe mode.
976
0
    int32_t maxResumedCrashes = 0;
977
0
    int32_t prefType;
978
0
    rv = Preferences::GetRootBranch(
979
0
      PrefValueKind::Default)->GetPrefType(kPrefMaxResumedCrashes, &prefType);
980
0
    NS_ENSURE_SUCCESS(rv, rv);
981
0
    if (prefType == nsIPrefBranch::PREF_INT) {
982
0
      rv = Preferences::GetInt(kPrefMaxResumedCrashes, &maxResumedCrashes);
983
0
      NS_ENSURE_SUCCESS(rv, rv);
984
0
    }
985
0
    rv = Preferences::SetInt(kPrefRecentCrashes, maxResumedCrashes);
986
0
    NS_ENSURE_SUCCESS(rv, rv);
987
0
  } else if (!inSafeMode) {
988
0
    // clear the count of recent crashes after a succesful startup when not in safe mode
989
0
    rv = Preferences::ClearUser(kPrefRecentCrashes);
990
0
    if (NS_FAILED(rv)) NS_WARNING("Could not clear startup crash count.");
991
0
  }
992
0
  nsCOMPtr<nsIPrefService> prefs = Preferences::GetService();
993
0
  // save prefs to disk since we are tracking crashes.  This may be
994
0
  // asynchronous, so a crash could sneak in that we would mistake for
995
0
  // a start up crash. See bug 789945 and bug 1361262.
996
0
  rv = prefs->SavePrefFile(nullptr);
997
0
998
0
  return rv;
999
0
}
1000
1001
NS_IMETHODIMP
1002
nsAppStartup::RestartInSafeMode(uint32_t aQuitMode)
1003
0
{
1004
0
  PR_SetEnv("MOZ_SAFE_MODE_RESTART=1");
1005
0
  this->Quit(aQuitMode | nsIAppStartup::eRestart);
1006
0
1007
0
  return NS_OK;
1008
0
}
1009
1010
NS_IMETHODIMP
1011
nsAppStartup::CreateInstanceWithProfile(nsIToolkitProfile* aProfile)
1012
0
{
1013
0
  if (NS_WARN_IF(!aProfile)) {
1014
0
    return NS_ERROR_FAILURE;
1015
0
  }
1016
0
1017
0
  if (NS_WARN_IF(gAbsoluteArgv0Path.IsEmpty())) {
1018
0
    return NS_ERROR_FAILURE;
1019
0
  }
1020
0
1021
0
  nsCOMPtr<nsIFile> execPath;
1022
0
  nsresult rv = NS_NewLocalFile(gAbsoluteArgv0Path,
1023
0
                                true, getter_AddRefs(execPath));
1024
0
  if (NS_WARN_IF(NS_FAILED(rv))) {
1025
0
    return rv;
1026
0
  }
1027
0
1028
0
  nsCOMPtr<nsIProcess> process = do_CreateInstance(NS_PROCESS_CONTRACTID, &rv);
1029
0
  if (NS_WARN_IF(NS_FAILED(rv))) {
1030
0
    return rv;
1031
0
  }
1032
0
1033
0
  rv = process->Init(execPath);
1034
0
  if (NS_WARN_IF(NS_FAILED(rv))) {
1035
0
    return rv;
1036
0
  }
1037
0
1038
0
  nsAutoCString profileName;
1039
0
  rv = aProfile->GetName(profileName);
1040
0
  if (NS_WARN_IF(NS_FAILED(rv))) {
1041
0
    return rv;
1042
0
  }
1043
0
1044
0
  const char *args[] = { "-no-remote", "-P", profileName.get() };
1045
0
  rv = process->Run(false, args, 3);
1046
0
  if (NS_WARN_IF(NS_FAILED(rv))) {
1047
0
    return rv;
1048
0
  }
1049
0
1050
0
  return NS_OK;
1051
0
}