File: application_lifetime_desktop.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (324 lines) | stat: -rw-r--r-- 11,351 bytes parent folder | download | duplicates (6)
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
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/lifetime/application_lifetime_desktop.h"

#include <optional>

#include "base/callback_list.h"
#include "base/functional/bind.h"
#include "base/no_destructor.h"
#include "base/process/process.h"
#include "base/threading/hang_watcher.h"
#include "base/time/time.h"
#include "base/types/strong_alias.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/download/download_core_service.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/browser/lifetime/browser_close_manager.h"
#include "chrome/browser/lifetime/browser_shutdown.h"
#include "chrome/browser/lifetime/termination_notification.h"
#include "chrome/browser/metrics/shutdown_watcher_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/sessions/exit_type_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/pref_names.h"
#include "components/keep_alive_registry/keep_alive_registry.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ash/boot_times_recorder/boot_times_recorder.h"
#include "chrome/browser/lifetime/application_lifetime_chromeos.h"
#else  // !BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ui/profiles/profile_picker.h"
#endif  // BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(IS_WIN)
#include "base/win/win_util.h"
#endif  // BUILDFLAG(IS_WIN)

#if BUILDFLAG(ENABLE_SESSION_SERVICE)
#include "chrome/browser/sessions/session_data_service.h"
#include "chrome/browser/sessions/session_data_service_factory.h"
#endif  // BUILDFLAG(ENABLE_SESSION_SERVICE)

#if BUILDFLAG(ENABLE_GLIC)
#include "chrome/browser/background/glic/glic_background_mode_manager.h"
#endif

namespace chrome {

namespace {

base::RepeatingCallbackList<void(bool)>& GetClosingAllBrowsersCallbackList() {
  static base::NoDestructor<base::RepeatingCallbackList<void(bool)>>
      callback_list;
  return *callback_list;
}

using IgnoreUnloadHandlers =
    base::StrongAlias<class IgnoreUnloadHandlersTag, bool>;

void AttemptRestartInternal(IgnoreUnloadHandlers ignore_unload_handlers) {
  // TODO(beng): Can this use ProfileManager::GetLoadedProfiles instead?
  // TODO(crbug.com/40180622): Unset SaveSessionState if the restart fails.
  for (Browser* browser : *BrowserList::GetInstance()) {
    browser->profile()->SaveSessionState();
#if BUILDFLAG(ENABLE_SESSION_SERVICE)
    auto* session_data_service =
        SessionDataServiceFactory::GetForProfile(browser->profile());
    if (session_data_service) {
      session_data_service->SetForceKeepSessionState();
    }
#endif  // BUILDFLAG(ENABLE_SESSION_SERVICE)
  }

  PrefService* pref_service = g_browser_process->local_state();
  pref_service->SetBoolean(prefs::kWasRestarted, true);
  KeepAliveRegistry::GetInstance()->SetRestarting();

#if BUILDFLAG(IS_CHROMEOS)
  DCHECK(!chrome::IsSendingStopRequestToSessionManager());

  ash::BootTimesRecorder::Get()->set_restart_requested();
  chrome::SetSendStopRequestToSessionManager(false);

  // If an update is pending StopSession() will trigger a system reboot,
  // which in turn will send SIGTERM to Chrome, and that ends up processing
  // unload handlers.
  if (UpdatePending()) {
    browser_shutdown::NotifyAppTerminating();
    StopSession();
    return;
  }

  // Run exit process in clean stack.
  content::GetUIThreadTaskRunner({})->PostTask(
      FROM_HERE, base::BindOnce(&ExitIgnoreUnloadHandlers));
#else   // !BUILDFLAG(IS_CHROMEOS).
  // Set the flag to restore state after the restart.
  pref_service->SetBoolean(prefs::kRestartLastSessionOnShutdown, true);
  if (ignore_unload_handlers) {
    ExitIgnoreUnloadHandlers();
  } else {
    AttemptExit();
  }
#endif  // BUILDFLAG(IS_CHROMEOS)
}

void ShutdownIfNoBrowsers() {
  if (GetTotalBrowserCount() > 0) {
    return;
  }

  // Tell everyone that we are shutting down.
  browser_shutdown::SetTryingToQuit(true);

#if BUILDFLAG(ENABLE_GLIC)
  auto* glic_background_mode_manager =
      glic::GlicBackgroundModeManager::GetInstance();
  if (glic_background_mode_manager) {
    glic_background_mode_manager->ExitBackgroundMode();
  }
#endif

#if BUILDFLAG(ENABLE_SESSION_SERVICE)
  // If ShuttingDownWithoutClosingBrowsers() returns true, the session
  // services may not get a chance to shut down normally, so explicitly shut
  // them down here to ensure they have a chance to persist their data.
  ProfileManager::ShutdownSessionServices();
#endif  // BUILDFLAG(ENABLE_SESSION_SERVICE)
  browser_shutdown::NotifyAppTerminating();
#if BUILDFLAG(IS_CHROMEOS)
  StopSession();
#endif  // BUILDFLAG(IS_CHROMEOS)
  OnAppExiting();
}

}  // namespace

void CloseAllBrowsersAndQuit() {
  browser_shutdown::SetTryingToQuit(true);
  CloseAllBrowsers();
}

void CloseAllBrowsers() {
  // If there are no browsers and closing the last browser would quit the
  // application, send the APP_TERMINATING action here. Otherwise, it will be
  // sent by RemoveBrowser() when the last browser has closed.
  if (GetTotalBrowserCount() == 0 &&
      (browser_shutdown::IsTryingToQuit() ||
       !KeepAliveRegistry::GetInstance()->IsKeepingAlive())) {
    ShutdownIfNoBrowsers();
    return;
  }

#if BUILDFLAG(IS_CHROMEOS)
  ash::BootTimesRecorder::Get()->AddLogoutTimeMarker("StartedClosingWindows",
                                                     false);
#endif  // BUILDFLAG(IS_CHROMEOS)
  scoped_refptr<BrowserCloseManager> browser_close_manager =
      new BrowserCloseManager;
  browser_close_manager->StartClosingBrowsers();
}

void AttemptRestart() {
  AttemptRestartInternal(IgnoreUnloadHandlers(false));
}
#if !BUILDFLAG(IS_CHROMEOS)
void RelaunchIgnoreUnloadHandlers() {
  AttemptRestartInternal(IgnoreUnloadHandlers(true));
}
#endif  // !BUILDFLAG(IS_CHROMEOS)

void SessionEnding() {
  // This is a time-limited shutdown where we need to write as much to
  // disk as we can as soon as we can, and where we must kill the
  // process within a hang timeout to avoid user prompts.

  // EndSession is invoked once per frame. Only do something the first time.
  static bool already_ended = false;
  // We may get called in the middle of shutdown, e.g. https://crbug.com/70852
  // and https://crbug.com/1187418.  In this case, do nothing.
  if (already_ended || !g_browser_process) {
    return;
  }
  already_ended = true;

  // ~ShutdownWatcherHelper uses IO (it joins a thread). We'll only trigger that
  // if Terminate() fails, which leaves us in a weird state, or the OS is going
  // to kill us soon. Either way we don't care about that here.
  base::ScopedAllowBlocking allow_blocking;

  // Two different types of hang detection cannot attempt to upload crashes at
  // the same time or they would interfere with each other.
  std::optional<ShutdownWatcherHelper> shutdown_watcher;
  std::optional<base::WatchHangsInScope> watch_hangs_scope;
  if (base::HangWatcher::IsCrashReportingEnabled()) {
    // TODO(crbug.com/40840897): Migrate away from ShutdownWatcher and its old
    // timing.
    base::HangWatcher::SetShuttingDown();
    constexpr base::TimeDelta kShutdownHangDelay{base::Seconds(30)};
    watch_hangs_scope.emplace(kShutdownHangDelay);
  } else {
    // Start watching for hang during shutdown, and crash it if takes too long.
    // We disarm when |shutdown_watcher| object is destroyed, which is when we
    // exit this function.
    constexpr base::TimeDelta kShutdownHangDelay{base::Seconds(90)};
    shutdown_watcher.emplace();
    shutdown_watcher->Arm(kShutdownHangDelay);
  }

  browser_shutdown::OnShutdownStarting(
      browser_shutdown::ShutdownType::kEndSession);

  // In a clean shutdown, browser_shutdown::OnShutdownStarting sets
  // g_shutdown_type, and browser_shutdown::ShutdownPreThreadsStop calls
  // RecordShutdownInfoPrefs to update the pref with the value. However, here
  // the process is going to exit without calling ShutdownPreThreadsStop.
  // Instead, here we call RecordShutdownInfoPrefs to record the shutdown info.
  browser_shutdown::RecordShutdownInfoPrefs();

  OnClosingAllBrowsers(true);

  // Write important data first.
  g_browser_process->EndSession();

  // Emit the shutdown metric for the end-session case. The process will exit
  // after this point.
  browser_shutdown::RecordShutdownMetrics();

#if BUILDFLAG(IS_WIN)
  base::win::SetShouldCrashOnProcessDetach(false);
#endif  // BUILDFLAG(IS_WIN)

  // On Windows 7 and later, the system will consider the process ripe for
  // termination as soon as it hides or destroys its windows. Since any
  // execution past that point will be non-deterministically cut short, we
  // might as well put ourselves out of that misery deterministically.
  base::Process::TerminateCurrentProcessImmediately(0);
}

void ShutdownIfNeeded() {
  if (browser_shutdown::IsTryingToQuit()) {
    return;
  }

  ShutdownIfNoBrowsers();
}

void OnAppExiting() {
  static bool notified = false;
  if (notified) {
    return;
  }
  notified = true;
  HandleAppExitingForPlatform();
}

void OnClosingAllBrowsers(bool closing) {
  GetClosingAllBrowsersCallbackList().Notify(closing);
}

base::CallbackListSubscription AddClosingAllBrowsersCallback(
    base::RepeatingCallback<void(bool)> closing_all_browsers_callback) {
  return GetClosingAllBrowsersCallbackList().Add(
      std::move(closing_all_browsers_callback));
}

void MarkAsCleanShutdown() {
#if BUILDFLAG(IS_CHROMEOS)
  LogMarkAsCleanShutdown();
  // Tracks profiles that have pending write of the exit type.
  std::set<Profile*> pending_profiles;
#endif  // BUILDFLAG(IS_CHROMEOS)

  for (Browser* browser : *BrowserList::GetInstance()) {
    if (ExitTypeService* exit_type_service =
            ExitTypeService::GetInstanceForProfile(browser->profile())) {
      exit_type_service->SetCurrentSessionExitType(ExitType::kClean);

#if BUILDFLAG(IS_CHROMEOS)
      // Explicitly schedule pending writes on ChromeOS so that even if the
      // UI thread is hosed (e.g. taking a long time to close all tabs because
      // of page faults/swap-in), the clean shutdown flag still gets a chance
      // to be persisted. See https://crbug.com/1294764
      Profile* profile = browser->profile();
      if (pending_profiles.insert(profile).second) {
        profile->GetPrefs()->CommitPendingWrite();
      }
#endif  // BUILDFLAG(IS_CHROMEOS)
    }
  }
}

bool AreAllBrowsersCloseable() {
  if (BrowserList::GetInstance()->empty()) {
    return true;
  }

  // If there are any downloads active, all browsers are not closeable.
  // However, this does not block for malicious downloads.
  if (DownloadCoreService::BlockingShutdownCountAllProfiles() > 0) {
    return false;
  }

  // Check TabsNeedBeforeUnloadFired().
  for (Browser* browser : *BrowserList::GetInstance()) {
    if (browser->TabsNeedBeforeUnloadFired()) {
      return false;
    }
  }
  return true;
}

}  // namespace chrome