1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chrome_browser_main_mac.h"
7 #import <Cocoa/Cocoa.h>
8 #include <sys/sysctl.h>
10 #include "base/command_line.h"
11 #include "base/debug/debugger.h"
12 #include "base/files/file_path.h"
13 #include "base/mac/bundle_locations.h"
14 #include "base/mac/mac_util.h"
15 #include "base/memory/scoped_nsobject.h"
16 #include "base/metrics/histogram.h"
17 #include "base/path_service.h"
18 #include "chrome/app/breakpad_mac.h"
19 #import "chrome/browser/app_controller_mac.h"
20 #import "chrome/browser/chrome_browser_application_mac.h"
21 #include "chrome/browser/mac/install_from_dmg.h"
22 #include "chrome/browser/mac/keychain_reauthorize.h"
23 #import "chrome/browser/mac/keystone_glue.h"
24 #include "chrome/browser/metrics/metrics_service.h"
25 #include "chrome/browser/storage_monitor/storage_monitor_mac.h"
26 #include "chrome/common/chrome_paths.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "content/public/common/main_function_params.h"
29 #include "content/public/common/result_codes.h"
30 #include "ui/base/l10n/l10n_util_mac.h"
31 #include "ui/base/resource/resource_bundle.h"
32 #include "ui/base/resource/resource_handle.h"
36 // This preference is used to track whether the KeychainReauthorize operation
37 // has occurred at launch. This operation only makes sense while the
38 // application continues to be signed by the old certificate.
39 NSString* const kKeychainReauthorizeAtLaunchPref =
40 @"KeychainReauthorizeInAppMay2012";
41 const int kKeychainReauthorizeAtLaunchMaxTries = 2;
43 // Some users rarely restart Chrome, so they might never get a chance to run
44 // the at-launch KeychainReauthorize. To account for them, there's also an
45 // at-update KeychainReauthorize option, which runs from .keystone_install for
46 // users on a user Keystone ticket. This operation may make sense for a period
47 // of time after the application switches to being signed by the new
48 // certificate, as long as the at-update stub executable is still signed by
50 NSString* const kKeychainReauthorizeAtUpdatePref =
51 @"KeychainReauthorizeAtUpdateMay2012";
52 const int kKeychainReauthorizeAtUpdateMaxTries = 3;
54 // This is one enum instead of two so that the values can be correlated in a
57 // Older than any expected cat.
58 SABER_TOOTHED_CAT_32 = 0,
64 LION_32, // Unexpected, Lion requires a 64-bit CPU.
66 MOUNTAIN_LION_32, // Unexpected, Mountain Lion requires a 64-bit CPU.
69 // DON'T add new constants here. It's important to keep the constant values,
70 // um, constant. Add new constants at the bottom.
72 // Newer than any known cat.
73 FUTURE_CAT_32, // Unexpected, it's unlikely Apple will un-obsolete old CPUs.
76 // What if the bitsiness of the CPU can't be determined?
77 SABER_TOOTHED_CAT_DUNNO,
83 // Add new constants here.
88 CatSixtyFour CatSixtyFourValue() {
89 #if defined(ARCH_CPU_64_BITS)
90 // If 64-bit code is running, then it's established that this CPU can run
91 // 64-bit code, and no further inquiry is necessary.
93 bool cpu64_known = true;
95 // Check a sysctl conveniently provided by the kernel that identifies
96 // whether the CPU supports 64-bit operation. Note that this tests the
97 // actual hardware capabilities, not the bitsiness of the running process,
98 // and not the bitsiness of the running kernel. The value thus determines
99 // whether the CPU is capable of running 64-bit programs (in the presence of
100 // proper OS runtime support) without regard to whether the current program
101 // is 64-bit (it may not be) or whether the current kernel is (the kernel
102 // can launch cross-bitted user-space tasks).
105 size_t len = sizeof(cpu64);
106 const char kSysctlName[] = "hw.cpu64bit_capable";
107 bool cpu64_known = sysctlbyname(kSysctlName, &cpu64, &len, NULL, 0) == 0;
109 PLOG(WARNING) << "sysctlbyname(\"" << kSysctlName << "\")";
113 if (base::mac::IsOSSnowLeopard()) {
114 return cpu64_known ? (cpu64 ? SNOW_LEOPARD_64 : SNOW_LEOPARD_32) :
117 if (base::mac::IsOSLion()) {
118 return cpu64_known ? (cpu64 ? LION_64 : LION_32) :
121 if (base::mac::IsOSMountainLion()) {
122 return cpu64_known ? (cpu64 ? MOUNTAIN_LION_64 : MOUNTAIN_LION_32) :
125 if (base::mac::IsOSLaterThanMountainLion_DontCallThis()) {
126 return cpu64_known ? (cpu64 ? FUTURE_CAT_64 : FUTURE_CAT_32) :
130 // If it's not any of the expected OS versions or later than them, it must
132 return cpu64_known ? (cpu64 ? SABER_TOOTHED_CAT_64 : SABER_TOOTHED_CAT_32) :
133 SABER_TOOTHED_CAT_DUNNO;
136 void RecordCatSixtyFour() {
137 CatSixtyFour cat_sixty_four = CatSixtyFourValue();
139 // Set this higher than the highest value in the CatSixtyFour enum to
140 // provide some headroom and then leave it alone. See HISTOGRAM_ENUMERATION
141 // in base/metrics/histogram.h.
142 const int kMaxCatsAndSixtyFours = 32;
143 COMPILE_ASSERT(kMaxCatsAndSixtyFours >= CAT_SIXTY_FOUR_MAX,
144 CatSixtyFour_enum_grew_too_large);
146 UMA_HISTOGRAM_ENUMERATION("OSX.CatSixtyFour",
148 kMaxCatsAndSixtyFours);
153 void RecordBreakpadStatusUMA(MetricsService* metrics) {
154 metrics->RecordBreakpadRegistration(IsCrashReporterEnabled());
155 metrics->RecordBreakpadHasDebugger(base::debug::BeingDebugged());
158 void WarnAboutMinimumSystemRequirements() {
159 // Nothing to check for on Mac right now.
162 // From browser_main_win.h, stubs until we figure out the right thing...
164 int DoUninstallTasks(bool chrome_still_running) {
165 return content::RESULT_CODE_NORMAL_EXIT;
168 // ChromeBrowserMainPartsMac ---------------------------------------------------
170 ChromeBrowserMainPartsMac::ChromeBrowserMainPartsMac(
171 const content::MainFunctionParams& parameters)
172 : ChromeBrowserMainPartsPosix(parameters) {
175 ChromeBrowserMainPartsMac::~ChromeBrowserMainPartsMac() {
178 void ChromeBrowserMainPartsMac::PreEarlyInitialization() {
179 if (parsed_command_line().HasSwitch(switches::kKeychainReauthorize)) {
180 if (base::mac::AmIBundled()) {
181 LOG(FATAL) << "Inappropriate process type for Keychain reauthorization";
184 // Do Keychain reauthorization at the time of update installation. This
185 // gets three chances to run. If the first or second try doesn't complete
186 // successfully (crashes or is interrupted for any reason), there will be
187 // another chance. Once this step completes successfully, it should never
188 // have to run again.
190 // This is kicked off by a special stub executable during an automatic
191 // update. See chrome/installer/mac/keychain_reauthorize_main.cc.
192 chrome::KeychainReauthorizeIfNeeded(kKeychainReauthorizeAtUpdatePref,
193 kKeychainReauthorizeAtUpdateMaxTries);
198 ChromeBrowserMainPartsPosix::PreEarlyInitialization();
200 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
201 CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
202 singleton_command_line->AppendSwitch(switches::kNoStartupWindow);
205 RecordCatSixtyFour();
208 void ChromeBrowserMainPartsMac::PreMainMessageLoopStart() {
209 ChromeBrowserMainPartsPosix::PreMainMessageLoopStart();
211 // Tell Cocoa to finish its initialization, which we want to do manually
212 // instead of calling NSApplicationMain(). The primary reason is that NSAM()
213 // never returns, which would leave all the objects currently on the stack
214 // in scoped_ptrs hanging and never cleaned up. We then load the main nib
215 // directly. The main event loop is run from common code using the
216 // MessageLoop API, which works out ok for us because it's a wrapper around
219 // Initialize NSApplication using the custom subclass.
220 chrome_browser_application_mac::RegisterBrowserCrApp();
222 // If ui_task is not NULL, the app is actually a browser_test, so startup is
223 // handled outside of BrowserMain (which is what called this).
224 if (!parameters().ui_task) {
225 // The browser process only wants to support the language Cocoa will use,
226 // so force the app locale to be overriden with that value.
227 l10n_util::OverrideLocaleWithCocoaLocale();
229 // Before we load the nib, we need to start up the resource bundle so we
230 // have the strings avaiable for localization.
231 // TODO(markusheintz): Read preference pref::kApplicationLocale in order
232 // to enforce the application locale.
233 const std::string loaded_locale =
234 ResourceBundle::InitSharedInstanceWithLocale(std::string(), NULL);
235 CHECK(!loaded_locale.empty()) << "Default locale could not be found";
237 base::FilePath resources_pack_path;
238 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
239 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
240 resources_pack_path, ui::SCALE_FACTOR_NONE);
243 // This is a no-op if the KeystoneRegistration framework is not present.
244 // The framework is only distributed with branded Google Chrome builds.
245 [[KeystoneGlue defaultKeystoneGlue] registerWithKeystone];
247 // Disk image installation is sort of a first-run task, so it shares the
248 // kNoFirstRun switch.
250 // This needs to be done after the resource bundle is initialized (for
251 // access to localizations in the UI) and after Keystone is initialized
252 // (because the installation may need to promote Keystone) but before the
253 // app controller is set up (and thus before MainMenu.nib is loaded, because
254 // the app controller assumes that a browser has been set up and will crash
255 // upon receipt of certain notifications if no browser exists), before
256 // anyone tries doing anything silly like firing off an import job, and
257 // before anything creating preferences like Local State in order for the
258 // relaunched installed application to still consider itself as first-run.
259 if (!parsed_command_line().HasSwitch(switches::kNoFirstRun)) {
260 if (MaybeInstallFromDiskImage()) {
261 // The application was installed and the installed copy has been
262 // launched. This process is now obsolete. Exit.
267 // Now load the nib (from the right bundle).
268 scoped_nsobject<NSNib>
269 nib([[NSNib alloc] initWithNibNamed:@"MainMenu"
270 bundle:base::mac::FrameworkBundle()]);
271 // TODO(viettrungluu): crbug.com/20504 - This currently leaks, so if you
272 // change this, you'll probably need to change the Valgrind suppression.
273 [nib instantiateNibWithOwner:NSApp topLevelObjects:nil];
274 // Make sure the app controller has been created.
275 DCHECK([NSApp delegate]);
277 // Prevent Cocoa from turning command-line arguments into
278 // |-application:openFiles:|, since we already handle them directly.
279 [[NSUserDefaults standardUserDefaults]
280 setObject:@"NO" forKey:@"NSTreatUnknownArgumentsAsOpen"];
283 void ChromeBrowserMainPartsMac::PreProfileInit() {
284 storage_monitor_.reset(new chrome::StorageMonitorMac());
286 ChromeBrowserMainPartsPosix::PreProfileInit();
289 void ChromeBrowserMainPartsMac::PostProfileInit() {
290 storage_monitor_->Init();
292 ChromeBrowserMainPartsPosix::PostProfileInit();
295 void ChromeBrowserMainPartsMac::DidEndMainMessageLoop() {
296 AppController* appController = [NSApp delegate];
297 [appController didEndMainMessageLoop];