blob: 02583716655476c537754f002bfe9c99dba8f512 [file] [log] [blame]
[email protected]a21d8082012-01-12 19:23:201// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
[email protected]c9349d082008-08-22 21:16:474
[email protected]4512f3ac2009-11-04 03:39:225#include <windows.h>
6#include <shlwapi.h>
[email protected]c9349d082008-08-22 21:16:477
[email protected]5d91c9e2010-07-28 17:25:288#include "base/command_line.h"
[email protected]58580352010-10-26 04:07:509#include "base/debug/trace_event.h"
[email protected]ae0f0772010-08-13 04:54:1010#include "base/environment.h"
[email protected]6a0464c82012-08-07 05:58:2811#include "base/file_version_info.h"
[email protected]ae0f0772010-08-13 04:54:1012#include "base/logging.h"
[email protected]3b63f8f42011-03-28 01:54:1513#include "base/memory/scoped_ptr.h"
[email protected]bffce7c2013-09-13 17:30:0714#include "base/rand_util.h" // For PreRead experiment.
15#include "base/sha1.h" // For PreRead experiment.
[email protected]ee2020662013-06-10 18:56:2116#include "base/strings/string16.h"
17#include "base/strings/string_util.h"
18#include "base/strings/stringprintf.h"
[email protected]12bfb612013-06-07 19:54:0219#include "base/strings/utf_string_conversions.h"
[email protected]85769352010-11-16 14:24:3020#include "base/version.h"
[email protected]797b7de42013-07-11 08:01:4221#include "base/win/windows_version.h"
[email protected]4512f3ac2009-11-04 03:39:2222#include "chrome/app/client_util.h"
[email protected]797b7de42013-07-11 08:01:4223#include "chrome/app/image_pre_reader_win.h"
[email protected]03d21b82010-12-07 19:37:2224#include "chrome/common/chrome_constants.h"
[email protected]1fcfb202011-07-19 19:53:1425#include "chrome/common/chrome_result_codes.h"
[email protected]103607e2010-02-01 18:57:0926#include "chrome/common/chrome_switches.h"
[email protected]e3824ec2013-02-08 01:02:4027#include "chrome/common/env_vars.h"
[email protected]74d1eec2009-11-04 22:18:5728#include "chrome/installer/util/browser_distribution.h"
[email protected]2544a7a2011-03-14 18:25:1929#include "chrome/installer/util/channel_info.h"
[email protected]2414e842008-11-07 01:27:5730#include "chrome/installer/util/google_update_constants.h"
[email protected]fd59f822011-05-12 18:07:1831#include "chrome/installer/util/google_update_settings.h"
[email protected]12bfb612013-06-07 19:54:0232#include "chrome/installer/util/install_util.h"
[email protected]28c19692008-11-07 23:40:3833#include "chrome/installer/util/util_constants.h"
[email protected]0b818f72013-10-22 00:11:0334#include "components/breakpad/app/breakpad_win.h"
[email protected]28c19692008-11-07 23:40:3835
36namespace {
[email protected]4512f3ac2009-11-04 03:39:2237// The entry point signature of chrome.dll.
[email protected]d85d6702011-09-01 15:51:5338typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*);
[email protected]28c19692008-11-07 23:40:3839
[email protected]3cdacd42010-04-30 18:55:5340typedef void (*RelaunchChromeBrowserWithNewCommandLineIfNeededFunc)();
41
[email protected]bffce7c2013-09-13 17:30:0742// Returns true if the build date for this module precedes the expiry date
43// for the pre-read experiment.
44bool PreReadExperimentIsActive() {
45 const int kPreReadExpiryYear = 2014;
46 const int kPreReadExpiryMonth = 7;
47 const int kPreReadExpiryDay = 1;
48 const char kBuildTimeStr[] = __DATE__ " " __TIME__;
49
50 // Get the timestamp of the build.
51 base::Time build_time;
52 bool result = base::Time::FromString(kBuildTimeStr, &build_time);
53 DCHECK(result);
54
55 // Get the timestamp at which the experiment expires.
56 base::Time::Exploded exploded = {0};
57 exploded.year = kPreReadExpiryYear;
58 exploded.month = kPreReadExpiryMonth;
59 exploded.day_of_month = kPreReadExpiryDay;
60 base::Time expiration_time = base::Time::FromLocalExploded(exploded);
61
62 // Return true if the build time predates the expiration time..
63 return build_time < expiration_time;
64}
65
66// Get random unit values, i.e., in the range (0, 1), denoting a die-toss for
67// being in an experiment population and experimental group thereof.
68void GetPreReadPopulationAndGroup(double* population, double* group) {
69 // By default we use the metrics id for the user as stable pseudo-random
70 // input to a hash.
[email protected]264c0acac2013-10-01 13:33:3071 std::string metrics_id;
[email protected]bffce7c2013-09-13 17:30:0772 GoogleUpdateSettings::GetMetricsId(&metrics_id);
73
74 // If this user has not metrics id, we fall back to a purely random value
75 // per browser session.
76 const size_t kLength = 16;
77 std::string random_value(metrics_id.empty() ? base::RandBytesAsString(kLength)
[email protected]264c0acac2013-10-01 13:33:3078 : metrics_id);
[email protected]bffce7c2013-09-13 17:30:0779
80 // To interpret the value as a random number we hash it and read the first 8
81 // bytes of the hash as a unit-interval representing a die-toss for being in
82 // the experiment population and the second 8 bytes as a die-toss for being
83 // in various experiment groups.
84 unsigned char sha1_hash[base::kSHA1Length];
85 base::SHA1HashBytes(
86 reinterpret_cast<const unsigned char*>(random_value.c_str()),
87 random_value.size() * sizeof(random_value[0]),
88 sha1_hash);
89 COMPILE_ASSERT(2 * sizeof(uint64) < sizeof(sha1_hash), need_more_data);
90 const uint64* random_bits = reinterpret_cast<uint64*>(&sha1_hash[0]);
91
92 // Convert the bits into unit-intervals and return.
93 *population = base::BitsToOpenEndedUnitInterval(random_bits[0]);
94 *group = base::BitsToOpenEndedUnitInterval(random_bits[1]);
95}
96
97// Gets the amount of pre-read to use as well as the experiment group in which
98// the user falls.
99size_t InitPreReadPercentage() {
100 // By default use the old behaviour: read 100%.
101 const int kDefaultPercentage = 100;
102 const char kDefaultFormatStr[] = "%d-pct-default";
103 const char kControlFormatStr[] = "%d-pct-control";
104 const char kGroupFormatStr[] = "%d-pct";
105
106 COMPILE_ASSERT(kDefaultPercentage <= 100, default_percentage_too_large);
107 COMPILE_ASSERT(kDefaultPercentage % 5 == 0, default_percentage_not_mult_5);
108
109 // Roll the dice to determine if this user is in the experiment and if so,
110 // in which experimental group.
111 double population = 0.0;
112 double group = 0.0;
113 GetPreReadPopulationAndGroup(&population, &group);
114
115 // We limit experiment populations to 1% of the Stable and 10% of each of
116 // the other channels.
117 const string16 channel(GoogleUpdateSettings::GetChromeChannel(
118 GoogleUpdateSettings::IsSystemInstall()));
119 double threshold = (channel == installer::kChromeChannelStable) ? 0.01 : 0.10;
120
121 // If the experiment has expired use the default pre-read level. Otherwise,
122 // those not in the experiment population also use the default pre-read level.
123 size_t value = kDefaultPercentage;
124 const char* format_str = kDefaultFormatStr;
125 if (PreReadExperimentIsActive() && (population <= threshold)) {
126 // We divide the experiment population into groups pre-reading at 5 percent
127 // increments in the range [0, 100].
128 value = static_cast<size_t>(group * 21.0) * 5;
129 DCHECK_LE(value, 100u);
130 DCHECK_EQ(0u, value % 5);
131 format_str =
132 (value == kDefaultPercentage) ? kControlFormatStr : kGroupFormatStr;
133 }
134
135 // Generate the group name corresponding to this percentage value.
136 std::string group_name;
137 base::SStringPrintf(&group_name, format_str, value);
138
139 // Persist the group name to the environment so that it can be used for
140 // reporting.
141 scoped_ptr<base::Environment> env(base::Environment::Create());
142 env->SetVar(chrome::kPreReadEnvironmentVariable, group_name);
143
144 // Return the percentage value to be used.
145 return value;
146}
147
[email protected]4512f3ac2009-11-04 03:39:22148// Expects that |dir| has a trailing backslash. |dir| is modified so it
149// contains the full path that was tried. Caller must check for the return
[email protected]85769352010-11-16 14:24:30150// value not being null to determine if this path contains a valid dll.
[email protected]6a0464c82012-08-07 05:58:28151HMODULE LoadChromeWithDirectory(string16* dir) {
[email protected]4512f3ac2009-11-04 03:39:22152 ::SetCurrentDirectoryW(dir->c_str());
[email protected]a4d16902013-07-20 20:41:37153 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
154#if !defined(CHROME_MULTIPLE_DLL)
155 const wchar_t* dll_name = installer::kChromeDll;
156#else
[email protected]dfb3b282013-10-08 01:25:36157 const wchar_t* dll_name =
158 cmd_line.HasSwitch(switches::kProcessType) &&
159 cmd_line.GetSwitchValueASCII(switches::kProcessType) != "service"
160 ? installer::kChromeChildDll
161 : installer::kChromeDll;
[email protected]a4d16902013-07-20 20:41:37162#endif
163 dir->append(dll_name);
[email protected]00b73412010-06-21 21:01:36164
[email protected]797b7de42013-07-11 08:01:42165#if !defined(WIN_DISABLE_PREREAD)
[email protected]bffce7c2013-09-13 17:30:07166 // We pre-read the binary to warm the memory caches (fewer hard faults to
167 // page parts of the binary in).
[email protected]a4d16902013-07-20 20:41:37168 if (!cmd_line.HasSwitch(switches::kProcessType)) {
169 const size_t kStepSize = 1024 * 1024;
[email protected]bffce7c2013-09-13 17:30:07170 size_t percentage = InitPreReadPercentage();
171 ImagePreReader::PartialPreReadImage(dir->c_str(), percentage, kStepSize);
[email protected]a4d16902013-07-20 20:41:37172 }
[email protected]797b7de42013-07-11 08:01:42173#endif
174
[email protected]4512f3ac2009-11-04 03:39:22175 return ::LoadLibraryExW(dir->c_str(), NULL,
176 LOAD_WITH_ALTERED_SEARCH_PATH);
177}
178
[email protected]6a0464c82012-08-07 05:58:28179void RecordDidRun(const string16& dll_path) {
[email protected]2544a7a2011-03-14 18:25:19180 bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());
[email protected]fd59f822011-05-12 18:07:18181 GoogleUpdateSettings::UpdateDidRunState(true, system_level);
[email protected]4512f3ac2009-11-04 03:39:22182}
183
[email protected]6a0464c82012-08-07 05:58:28184void ClearDidRun(const string16& dll_path) {
[email protected]2544a7a2011-03-14 18:25:19185 bool system_level = !InstallUtil::IsPerUserInstall(dll_path.c_str());
[email protected]fd59f822011-05-12 18:07:18186 GoogleUpdateSettings::UpdateDidRunState(false, system_level);
[email protected]2544a7a2011-03-14 18:25:19187}
[email protected]fd59f822011-05-12 18:07:18188
[email protected]28f576f2011-08-26 20:46:55189} // namespace
[email protected]f068b412012-04-02 20:24:48190
[email protected]6a0464c82012-08-07 05:58:28191string16 GetExecutablePath() {
[email protected]f068b412012-04-02 20:24:48192 wchar_t path[MAX_PATH];
193 ::GetModuleFileNameW(NULL, path, MAX_PATH);
194 if (!::PathRemoveFileSpecW(path))
[email protected]6a0464c82012-08-07 05:58:28195 return string16();
196 string16 exe_path(path);
[email protected]f068b412012-04-02 20:24:48197 return exe_path.append(1, L'\\');
198}
199
[email protected]18ee9f962013-07-01 22:38:48200string16 GetCurrentModuleVersion() {
201 scoped_ptr<FileVersionInfo> file_version_info(
202 FileVersionInfo::CreateFileVersionInfoForCurrentModule());
203 if (file_version_info.get()) {
204 string16 version_string(file_version_info->file_version());
205 if (Version(WideToASCII(version_string)).IsValid())
206 return version_string;
207 }
208 return string16();
209}
210
[email protected]4512f3ac2009-11-04 03:39:22211//=============================================================================
212
213MainDllLoader::MainDllLoader() : dll_(NULL) {
214}
215
216MainDllLoader::~MainDllLoader() {
[email protected]4512f3ac2009-11-04 03:39:22217}
218
[email protected]85769352010-11-16 14:24:30219// Loading chrome is an interesting affair. First we try loading from the
220// current directory to support run-what-you-compile and other development
221// scenarios.
[email protected]18ee9f962013-07-01 22:38:48222// If that fails then we look at the --chrome-version command line flag to
223// determine if we should stick with an older dll version even if a new one is
224// available to support upgrade-in-place scenarios.
225// If that fails then finally we look at the version resource in the current
226// module. This is the expected path for chrome.exe browser instances in an
227// installed build.
[email protected]6a0464c82012-08-07 05:58:28228HMODULE MainDllLoader::Load(string16* out_version, string16* out_file) {
[email protected]00d0c6d2013-05-16 23:52:03229 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
[email protected]6a0464c82012-08-07 05:58:28230 const string16 dir(GetExecutablePath());
[email protected]85769352010-11-16 14:24:30231 *out_file = dir;
[email protected]5bca9ee2011-09-03 00:18:42232 HMODULE dll = LoadChromeWithDirectory(out_file);
[email protected]00d0c6d2013-05-16 23:52:03233 if (!dll) {
234 // Loading from same directory (for developers) failed.
235 string16 version_string;
[email protected]00d0c6d2013-05-16 23:52:03236 if (cmd_line.HasSwitch(switches::kChromeVersion)) {
237 // This is used to support Chrome Frame, see http://crbug.com/88589.
238 version_string = cmd_line.GetSwitchValueNative(switches::kChromeVersion);
[email protected]4512f3ac2009-11-04 03:39:22239
[email protected]18ee9f962013-07-01 22:38:48240 if (!Version(WideToASCII(version_string)).IsValid()) {
[email protected]00d0c6d2013-05-16 23:52:03241 // If a bogus command line flag was given, then abort.
242 LOG(ERROR) << "Invalid command line version: " << version_string;
243 return NULL;
244 }
245 }
246
247 // If no version on the command line, then look at the version resource in
248 // the current module and try loading that.
[email protected]18ee9f962013-07-01 22:38:48249 if (version_string.empty())
250 version_string = GetCurrentModuleVersion();
[email protected]85769352010-11-16 14:24:30251
[email protected]18ee9f962013-07-01 22:38:48252 if (version_string.empty()) {
[email protected]00d0c6d2013-05-16 23:52:03253 LOG(ERROR) << "No valid Chrome version found";
254 return NULL;
255 }
256
257 *out_file = dir;
258 *out_version = version_string;
259 out_file->append(*out_version).append(1, L'\\');
260 dll = LoadChromeWithDirectory(out_file);
261 if (!dll) {
[email protected]18ee9f962013-07-01 22:38:48262 PLOG(ERROR) << "Failed to load Chrome DLL from " << *out_file;
[email protected]4512f3ac2009-11-04 03:39:22263 return NULL;
[email protected]85769352010-11-16 14:24:30264 }
[email protected]4512f3ac2009-11-04 03:39:22265 }
266
[email protected]18ee9f962013-07-01 22:38:48267 DCHECK(dll);
268
[email protected]f068b412012-04-02 20:24:48269 return dll;
[email protected]4512f3ac2009-11-04 03:39:22270}
271
272// Launching is a matter of loading the right dll, setting the CHROME_VERSION
273// environment variable and just calling the entry point. Derived classes can
274// add custom code in the OnBeforeLaunch callback.
275int MainDllLoader::Launch(HINSTANCE instance,
276 sandbox::SandboxInterfaceInfo* sbox_info) {
[email protected]6a0464c82012-08-07 05:58:28277 string16 version;
278 string16 file;
[email protected]4512f3ac2009-11-04 03:39:22279 dll_ = Load(&version, &file);
280 if (!dll_)
[email protected]1fcfb202011-07-19 19:53:14281 return chrome::RESULT_CODE_MISSING_DATA;
[email protected]4512f3ac2009-11-04 03:39:22282
[email protected]ae0f0772010-08-13 04:54:10283 scoped_ptr<base::Environment> env(base::Environment::Create());
[email protected]47e870b2013-02-24 21:14:53284 env->SetVar(chrome::kChromeVersionEnvVar, WideToUTF8(version));
[email protected]e3824ec2013-02-08 01:02:40285 // TODO(erikwright): Remove this when http://crbug.com/174953 is fixed and
286 // widely deployed.
287 env->UnSetVar(env_vars::kGoogleUpdateIsMachineEnvVar);
[email protected]4512f3ac2009-11-04 03:39:22288
[email protected]8dc338c2013-12-09 16:28:48289 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
290 std::string process_type =
291 cmd_line.GetSwitchValueASCII(switches::kProcessType);
292 breakpad::InitCrashReporter(process_type);
[email protected]2544a7a2011-03-14 18:25:19293 OnBeforeLaunch(file);
[email protected]4512f3ac2009-11-04 03:39:22294
295 DLL_MAIN entry_point =
296 reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll_, "ChromeMain"));
297 if (!entry_point)
[email protected]1fcfb202011-07-19 19:53:14298 return chrome::RESULT_CODE_BAD_PROCESS_TYPE;
[email protected]4512f3ac2009-11-04 03:39:22299
[email protected]d85d6702011-09-01 15:51:53300 int rc = entry_point(instance, sbox_info);
[email protected]2544a7a2011-03-14 18:25:19301 return OnBeforeExit(rc, file);
[email protected]4512f3ac2009-11-04 03:39:22302}
303
[email protected]3cdacd42010-04-30 18:55:53304void MainDllLoader::RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
305 RelaunchChromeBrowserWithNewCommandLineIfNeededFunc relaunch_function =
306 reinterpret_cast<RelaunchChromeBrowserWithNewCommandLineIfNeededFunc>(
307 ::GetProcAddress(dll_,
308 "RelaunchChromeBrowserWithNewCommandLineIfNeeded"));
309 if (!relaunch_function) {
310 LOG(ERROR) << "Could not find exported function "
311 << "RelaunchChromeBrowserWithNewCommandLineIfNeeded";
312 } else {
313 relaunch_function();
314 }
315}
316
[email protected]4512f3ac2009-11-04 03:39:22317//=============================================================================
318
319class ChromeDllLoader : public MainDllLoader {
320 public:
[email protected]6a0464c82012-08-07 05:58:28321 virtual string16 GetRegistryPath() {
322 string16 key(google_update::kRegPathClients);
[email protected]5f2cee82009-11-05 04:59:48323 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
324 key.append(L"\\").append(dist->GetAppGuid());
[email protected]4512f3ac2009-11-04 03:39:22325 return key;
326 }
327
[email protected]6a0464c82012-08-07 05:58:28328 virtual void OnBeforeLaunch(const string16& dll_path) {
[email protected]2544a7a2011-03-14 18:25:19329 RecordDidRun(dll_path);
[email protected]4512f3ac2009-11-04 03:39:22330 }
[email protected]42d7510c2009-12-19 01:48:30331
[email protected]6a0464c82012-08-07 05:58:28332 virtual int OnBeforeExit(int return_code, const string16& dll_path) {
[email protected]42d7510c2009-12-19 01:48:30333 // NORMAL_EXIT_CANCEL is used for experiments when the user cancels
334 // so we need to reset the did_run signal so omaha does not count
335 // this run as active usage.
[email protected]1fcfb202011-07-19 19:53:14336 if (chrome::RESULT_CODE_NORMAL_EXIT_CANCEL == return_code) {
[email protected]2544a7a2011-03-14 18:25:19337 ClearDidRun(dll_path);
[email protected]42d7510c2009-12-19 01:48:30338 }
339 return return_code;
340 }
[email protected]4512f3ac2009-11-04 03:39:22341};
342
343//=============================================================================
344
345class ChromiumDllLoader : public MainDllLoader {
346 public:
[email protected]6a0464c82012-08-07 05:58:28347 virtual string16 GetRegistryPath() {
[email protected]74d1eec2009-11-04 22:18:57348 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
349 return dist->GetVersionKey();
[email protected]4512f3ac2009-11-04 03:39:22350 }
351};
352
353MainDllLoader* MakeMainDllLoader() {
354#if defined(GOOGLE_CHROME_BUILD)
355 return new ChromeDllLoader();
356#else
357 return new ChromiumDllLoader();
358#endif
359}