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/files/file_path.h"
12 #include "base/mac/bundle_locations.h"
13 #include "base/mac/mac_util.h"
14 #include "base/mac/scoped_nsobject.h"
15 #include "base/metrics/histogram.h"
16 #include "base/path_service.h"
17 #import "chrome/browser/app_controller_mac.h"
18 #include "chrome/browser/browser_process.h"
19 #import "chrome/browser/chrome_browser_application_mac.h"
20 #include "chrome/browser/mac/install_from_dmg.h"
21 #include "chrome/browser/mac/keychain_reauthorize.h"
22 #import "chrome/browser/mac/keystone_glue.h"
23 #include "chrome/browser/metrics/metrics_service.h"
24 #include "chrome/common/chrome_paths.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "components/breakpad/app/breakpad_mac.h"
27 #include "content/public/common/main_function_params.h"
28 #include "content/public/common/result_codes.h"
29 #include "ui/base/l10n/l10n_util_mac.h"
30 #include "ui/base/resource/resource_bundle.h"
31 #include "ui/base/resource/resource_handle.h"
35 // Some users rarely restart Chrome, so they might never get a chance to run
36 // the at-launch KeychainReauthorize. To account for them, there's also an
37 // at-update KeychainReauthorize option, which runs from .keystone_install for
38 // users on a user Keystone ticket. This operation may make sense for a period
39 // of time after the application switches to being signed by the new
40 // certificate, as long as the at-update stub executable is still signed by
42 NSString* const kKeychainReauthorizeAtUpdatePref =
43 @"KeychainReauthorizeAtUpdateMay2012";
44 const int kKeychainReauthorizeAtUpdateMaxTries = 3;
46 // This is one enum instead of two so that the values can be correlated in a
49 // Older than any expected cat.
50 SABER_TOOTHED_CAT_32 = 0,
56 LION_32, // Unexpected, Lion requires a 64-bit CPU.
58 MOUNTAIN_LION_32, // Unexpected, Mountain Lion requires a 64-bit CPU.
60 MAVERICKS_32, // Unexpected, Mavericks requires a 64-bit CPU.
63 // DON'T add new constants here. It's important to keep the constant values,
64 // um, constant. Add new constants at the bottom.
66 // What if the bitsiness of the CPU can't be determined?
67 SABER_TOOTHED_CAT_DUNNO,
73 // Newer than any known cat.
74 FUTURE_CAT_32, // Unexpected, it's unlikely Apple will un-obsolete old CPUs.
78 // As new versions of Mac OS X are released with sillier and sillier names,
79 // rename the FUTURE_CAT enum values to match those names, and re-create
80 // FUTURE_CAT_[32|64|DUNNO] here.
85 CatSixtyFour CatSixtyFourValue() {
86 #if defined(ARCH_CPU_64_BITS)
87 // If 64-bit code is running, then it's established that this CPU can run
88 // 64-bit code, and no further inquiry is necessary.
90 bool cpu64_known = true;
92 // Check a sysctl conveniently provided by the kernel that identifies
93 // whether the CPU supports 64-bit operation. Note that this tests the
94 // actual hardware capabilities, not the bitsiness of the running process,
95 // and not the bitsiness of the running kernel. The value thus determines
96 // whether the CPU is capable of running 64-bit programs (in the presence of
97 // proper OS runtime support) without regard to whether the current program
98 // is 64-bit (it may not be) or whether the current kernel is (the kernel
99 // can launch cross-bitted user-space tasks).
102 size_t len = sizeof(cpu64);
103 const char kSysctlName[] = "hw.cpu64bit_capable";
104 bool cpu64_known = sysctlbyname(kSysctlName, &cpu64, &len, NULL, 0) == 0;
106 PLOG(WARNING) << "sysctlbyname(\"" << kSysctlName << "\")";
110 if (base::mac::IsOSSnowLeopard()) {
111 return cpu64_known ? (cpu64 ? SNOW_LEOPARD_64 : SNOW_LEOPARD_32) :
114 if (base::mac::IsOSLion()) {
115 return cpu64_known ? (cpu64 ? LION_64 : LION_32) :
118 if (base::mac::IsOSMountainLion()) {
119 return cpu64_known ? (cpu64 ? MOUNTAIN_LION_64 : MOUNTAIN_LION_32) :
122 if (base::mac::IsOSMavericks()) {
123 return cpu64_known ? (cpu64 ? MAVERICKS_64 : MAVERICKS_32) :
126 if (base::mac::IsOSLaterThanMavericks_DontCallThis()) {
127 return cpu64_known ? (cpu64 ? FUTURE_CAT_64 : FUTURE_CAT_32) :
131 // If it's not any of the expected OS versions or later than them, it must
133 return cpu64_known ? (cpu64 ? SABER_TOOTHED_CAT_64 : SABER_TOOTHED_CAT_32) :
134 SABER_TOOTHED_CAT_DUNNO;
137 void RecordCatSixtyFour() {
138 CatSixtyFour cat_sixty_four = CatSixtyFourValue();
140 // Set this higher than the highest value in the CatSixtyFour enum to
141 // provide some headroom and then leave it alone. See HISTOGRAM_ENUMERATION
142 // in base/metrics/histogram.h.
143 const int kMaxCatsAndSixtyFours = 32;
144 COMPILE_ASSERT(kMaxCatsAndSixtyFours >= CAT_SIXTY_FOUR_MAX,
145 CatSixtyFour_enum_grew_too_large);
147 UMA_HISTOGRAM_ENUMERATION("OSX.CatSixtyFour",
149 kMaxCatsAndSixtyFours);
154 // ChromeBrowserMainPartsMac ---------------------------------------------------
156 ChromeBrowserMainPartsMac::ChromeBrowserMainPartsMac(
157 const content::MainFunctionParams& parameters)
158 : ChromeBrowserMainPartsPosix(parameters) {
161 ChromeBrowserMainPartsMac::~ChromeBrowserMainPartsMac() {
164 void ChromeBrowserMainPartsMac::PreEarlyInitialization() {
165 if (parsed_command_line().HasSwitch(switches::kKeychainReauthorize)) {
166 if (base::mac::AmIBundled()) {
167 LOG(FATAL) << "Inappropriate process type for Keychain reauthorization";
170 // Do Keychain reauthorization at the time of update installation. This
171 // gets three chances to run. If the first or second try doesn't complete
172 // successfully (crashes or is interrupted for any reason), there will be
173 // another chance. Once this step completes successfully, it should never
174 // have to run again.
176 // This is kicked off by a special stub executable during an automatic
177 // update. See chrome/installer/mac/keychain_reauthorize_main.cc.
178 chrome::KeychainReauthorizeIfNeeded(kKeychainReauthorizeAtUpdatePref,
179 kKeychainReauthorizeAtUpdateMaxTries);
184 ChromeBrowserMainPartsPosix::PreEarlyInitialization();
186 if (base::mac::WasLaunchedAsHiddenLoginItem()) {
187 CommandLine* singleton_command_line = CommandLine::ForCurrentProcess();
188 singleton_command_line->AppendSwitch(switches::kNoStartupWindow);
191 RecordCatSixtyFour();
194 void ChromeBrowserMainPartsMac::PreMainMessageLoopStart() {
195 ChromeBrowserMainPartsPosix::PreMainMessageLoopStart();
197 // Tell Cocoa to finish its initialization, which we want to do manually
198 // instead of calling NSApplicationMain(). The primary reason is that NSAM()
199 // never returns, which would leave all the objects currently on the stack
200 // in scoped_ptrs hanging and never cleaned up. We then load the main nib
201 // directly. The main event loop is run from common code using the
202 // MessageLoop API, which works out ok for us because it's a wrapper around
205 // Initialize NSApplication using the custom subclass.
206 chrome_browser_application_mac::RegisterBrowserCrApp();
208 // If ui_task is not NULL, the app is actually a browser_test, so startup is
209 // handled outside of BrowserMain (which is what called this).
210 if (!parameters().ui_task) {
211 // The browser process only wants to support the language Cocoa will use,
212 // so force the app locale to be overriden with that value.
213 l10n_util::OverrideLocaleWithCocoaLocale();
215 // Before we load the nib, we need to start up the resource bundle so we
216 // have the strings avaiable for localization.
217 // TODO(markusheintz): Read preference pref::kApplicationLocale in order
218 // to enforce the application locale.
219 const std::string loaded_locale =
220 ResourceBundle::InitSharedInstanceWithLocale(std::string(), NULL);
221 CHECK(!loaded_locale.empty()) << "Default locale could not be found";
223 base::FilePath resources_pack_path;
224 PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
225 ResourceBundle::GetSharedInstance().AddDataPackFromPath(
226 resources_pack_path, ui::SCALE_FACTOR_NONE);
229 // This is a no-op if the KeystoneRegistration framework is not present.
230 // The framework is only distributed with branded Google Chrome builds.
231 [[KeystoneGlue defaultKeystoneGlue] registerWithKeystone];
233 // Disk image installation is sort of a first-run task, so it shares the
234 // no first run switches.
236 // This needs to be done after the resource bundle is initialized (for
237 // access to localizations in the UI) and after Keystone is initialized
238 // (because the installation may need to promote Keystone) but before the
239 // app controller is set up (and thus before MainMenu.nib is loaded, because
240 // the app controller assumes that a browser has been set up and will crash
241 // upon receipt of certain notifications if no browser exists), before
242 // anyone tries doing anything silly like firing off an import job, and
243 // before anything creating preferences like Local State in order for the
244 // relaunched installed application to still consider itself as first-run.
245 if (!first_run::IsFirstRunSuppressed(parsed_command_line())) {
246 if (MaybeInstallFromDiskImage()) {
247 // The application was installed and the installed copy has been
248 // launched. This process is now obsolete. Exit.
253 // Now load the nib (from the right bundle).
254 base::scoped_nsobject<NSNib> nib(
255 [[NSNib alloc] initWithNibNamed:@"MainMenu"
256 bundle:base::mac::FrameworkBundle()]);
257 // TODO(viettrungluu): crbug.com/20504 - This currently leaks, so if you
258 // change this, you'll probably need to change the Valgrind suppression.
259 [nib instantiateNibWithOwner:NSApp topLevelObjects:nil];
260 // Make sure the app controller has been created.
261 DCHECK([NSApp delegate]);
263 // Prevent Cocoa from turning command-line arguments into
264 // |-application:openFiles:|, since we already handle them directly.
265 [[NSUserDefaults standardUserDefaults]
266 setObject:@"NO" forKey:@"NSTreatUnknownArgumentsAsOpen"];
269 void ChromeBrowserMainPartsMac::PostProfileInit() {
270 ChromeBrowserMainPartsPosix::PostProfileInit();
271 g_browser_process->metrics_service()->RecordBreakpadRegistration(
272 breakpad::IsCrashReporterEnabled());
275 void ChromeBrowserMainPartsMac::DidEndMainMessageLoop() {
276 AppController* appController = [NSApp delegate];
277 [appController didEndMainMessageLoop];