Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(57)

Side by Side Diff: chrome/installer/test/alternate_version_generator.cc

Issue 5236002: Add infrastructure enabling tests of installer upgrade scenarios.... (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: '' Created 10 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2010 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.
4
5 // The file contains the implementation of the mini_installer re-versioner.
6 // The main function (GenerateNextVersion) does the following in a temp dir:
7 // - Extracts and unpacks setup.exe and the Chrome-bin folder from
8 // mini_installer.exe.
9 // - Inspects setup.exe to determine the current version.
10 // - Runs through all .dll and .exe files:
11 // - Replacing all occurrences of the Unicode version string in the files'
12 // resources with the updated string.
13 // - For all resources in which the string substitution is made, the binary
14 // form of the version is also replaced.
15 // - Re-packs setup.exe and Chrome-bin.
16 // - Inserts them into the target mini_installer.exe.
17 //
18 // This code assumes that the host program 1) initializes the process-wide
19 // CommandLine instance, and 2) resides in the output directory of a build
20 // tree. When #2 is not the case, the --7za_path command-line switch may be
21 // used to provide the (relative or absolute) path to the directory containing
22 // 7za.exe.
23
24 #include "chrome/installer/test/alternate_version_generator.h"
25
26 #include <windows.h>
27
28 #include <algorithm>
29 #include <sstream>
30 #include <limits>
31 #include <utility>
32 #include <vector>
33
34 #include "base/basictypes.h"
35 #include "base/command_line.h"
36 #include "base/file_path.h"
37 #include "base/file_util.h"
38 #include "base/logging.h"
39 #include "base/path_service.h"
40 #include "base/platform_file.h"
41 #include "base/process_util.h"
42 #include "base/win/pe_image.h"
43 #include "base/win/scoped_handle.h"
44 #include "chrome/installer/test/pe_image_resources.h"
45 #include "chrome/installer/test/resource_loader.h"
46 #include "chrome/installer/test/resource_updater.h"
47 #include "chrome/installer/util/lzma_util.h"
48 #include "testing/gtest/include/gtest/gtest.h"
49
50 namespace {
51
52 const wchar_t k7zaExe[] = L"7za.exe";
53 const wchar_t k7zaPathRelative[] = L"..\\..\\third_party\\lzma_sdk\\Executable";
54 const wchar_t kB7[] = L"B7";
55 const wchar_t kBl[] = L"BL";
56 const wchar_t kChrome7z[] = L"chrome.7z";
57 const wchar_t kChromeBin[] = L"Chrome-bin";
58 const wchar_t kChromePacked7z[] = L"chrome.packed.7z";
59 const wchar_t kExe[] = L"exe";
60 const wchar_t kExpandExe[] = L"expand.exe";
61 const wchar_t kExtDll[] = L".dll";
62 const wchar_t kExtExe[] = L".exe";
63 const wchar_t kMakeCab[] = L"makecab.exe";
64 const wchar_t kSetupEx_[] = L"setup.ex_";
65 const wchar_t kSetupExe[] = L"setup.exe";
66 const char kSwitch7zaPath[] = "7za_path";
67 const wchar_t kTempDirPrefix[] = L"mini_installer_test_temp";
68
69 // A helper class for creating and cleaning a temporary directory. A temporary
70 // directory is created in Initialize and destroyed (along with all of its
71 // contents) when the guard instance is destroyed.
72 class ScopedTempDirectory {
73 public:
74 ScopedTempDirectory() { }
75 ~ScopedTempDirectory() {
76 if (!directory_.empty() && !file_util::Delete(directory_, true)) {
77 LOG(DFATAL) << "Failed deleting temporary directory \""
78 << directory_.value() << "\"";
79 }
80 }
81 // Creates a temporary directory.
82 bool Initialize() {
83 DCHECK(directory_.empty());
84 if (!file_util::CreateNewTempDirectory(&kTempDirPrefix[0], &directory_)) {
85 LOG(DFATAL) << "Failed creating temporary directory.";
86 return false;
87 }
88 return true;
89 }
90 const FilePath& directory() const {
91 DCHECK(!directory_.empty());
92 return directory_;
93 }
94 private:
95 FilePath directory_;
96 DISALLOW_COPY_AND_ASSIGN(ScopedTempDirectory);
97 }; // class ScopedTempDirectory
98
99 // A helper class for manipulating a Chrome product version.
100 class ChromeVersion {
101 public:
102 static ChromeVersion FromHighLow(DWORD high, DWORD low) {
103 return ChromeVersion(static_cast<ULONGLONG>(high) << 32 |
104 static_cast<ULONGLONG>(low));
105 }
106 ChromeVersion() { }
107 explicit ChromeVersion(ULONGLONG value) : version_(value) { }
108 WORD major() const { return static_cast<WORD>(version_ >> 48); }
109 WORD minor() const { return static_cast<WORD>(version_ >> 32); }
110 WORD build() const { return static_cast<WORD>(version_ >> 16); }
111 WORD patch() const { return static_cast<WORD>(version_); }
112 DWORD high() const { return static_cast<DWORD>(version_ >> 32); }
113 DWORD low() const { return static_cast<DWORD>(version_); }
114 ULONGLONG value() const { return version_; }
115 void set_value(ULONGLONG value) { version_ = value; }
116 std::wstring ToString() const;
117 private:
118 ULONGLONG version_;
119 }; // class ChromeVersion
120
121 std::wstring ChromeVersion::ToString() const {
122 wchar_t buffer[24];
123 int string_len =
124 swprintf_s(&buffer[0], arraysize(buffer), L"%hu.%hu.%hu.%hu",
125 major(), minor(), build(), patch());
126 DCHECK_NE(-1, string_len);
127 DCHECK_GT(static_cast<int>(arraysize(buffer)), string_len);
128 return std::wstring(&buffer[0], string_len);
129 }
130
131 // A read/write mapping of a file.
132 // Note: base::MemoryMappedFile is not used because it doesn't support
133 // read/write mappings. Adding such support across all platforms for this
134 // Windows-only test code seems like overkill.
135 class MappedFile {
136 public:
137 MappedFile() : size_(), mapping_(), view_() { }
138 ~MappedFile();
139 bool Initialize(base::PlatformFile file);
140 void* data() const { return view_; }
141 size_t size() const { return size_; }
142 private:
143 size_t size_;
144 HANDLE mapping_;
145 void* view_;
146 DISALLOW_COPY_AND_ASSIGN(MappedFile);
147 }; // class MappedFile
148
149 MappedFile::~MappedFile() {
150 if (view_ != NULL) {
151 EXPECT_NE(0, UnmapViewOfFile(view_));
152 }
153 if (mapping_ != NULL) {
154 EXPECT_NE(0, CloseHandle(mapping_));
155 }
156 }
157
158 bool MappedFile::Initialize(base::PlatformFile file) {
159 DCHECK(mapping_ == NULL);
160 bool result = false;
161 base::PlatformFileInfo file_info;
162
163 if (base::GetPlatformFileInfo(file, &file_info)) {
164 if (file_info.size <=
165 static_cast<int64>(std::numeric_limits<size_t>::max())) {
166 mapping_ = CreateFileMapping(file, NULL, PAGE_READWRITE, 0,
167 static_cast<DWORD>(file_info.size), NULL);
168 if (mapping_ != NULL) {
169 view_ = MapViewOfFile(mapping_, FILE_MAP_WRITE, 0, 0,
170 static_cast<size_t>(file_info.size));
171 if (view_ != NULL) {
172 result = true;
173 } else {
174 PLOG(DFATAL) << "MapViewOfFile failed";
175 }
176 } else {
177 PLOG(DFATAL) << "CreateFileMapping failed";
178 }
179 } else {
180 LOG(DFATAL) << "Files larger than " << std::numeric_limits<size_t>::max()
181 << " are not supported.";
182 }
183 } else {
184 PLOG(DFATAL) << "GetPlatformFileInfo failed";
185 }
186 return result;
187 }
188
189 // Calls CreateProcess with good default parameters and waits for the process
190 // to terminate returning the process exit code.
191 bool RunProcessAndWait(const wchar_t* exe_path, const std::wstring& cmdline,
192 int* exit_code) {
193 bool result = true;
194 base::ProcessHandle process;
195 if (base::LaunchApp(cmdline, true, true, &process)) {
196 if (exit_code) {
197 if (!GetExitCodeProcess(process,
198 reinterpret_cast<DWORD*>(exit_code))) {
199 PLOG(DFATAL) << "Failed getting the exit code for \""
200 << cmdline << "\".";
201 result = false;
202 } else {
203 DCHECK_NE(*exit_code, STILL_ACTIVE);
204 }
205 }
206 } else {
207 result = false;
208 }
209
210 CloseHandle(process);
211 return result;
212 }
213
214 // Retrieves the version number of setup.exe in |work_dir| from its version
215 // resource, placing the value in |version|. Returns true on success.
216 bool GetSetupExeVersion(const FilePath& work_dir, ChromeVersion* version) {
217 DCHECK(version);
218 bool result = false;
219 upgrade_test::ResourceLoader setup;
220 std::pair<const uint8*, DWORD> version_info_data;
221
222 if (setup.Initialize(work_dir.Append(&kSetupExe[0])) &&
223 setup.Load(VS_VERSION_INFO, reinterpret_cast<WORD>(RT_VERSION),
224 &version_info_data)) {
225 const VS_FIXEDFILEINFO* fixed_file_info;
226 UINT ver_info_len;
227 if (VerQueryValue(version_info_data.first, L"\\",
228 reinterpret_cast<void**>(
229 const_cast<VS_FIXEDFILEINFO**>(&fixed_file_info)),
230 &ver_info_len) != 0) {
231 DCHECK_EQ(sizeof(VS_FIXEDFILEINFO), static_cast<size_t>(ver_info_len));
232 *version = ChromeVersion::FromHighLow(fixed_file_info->dwFileVersionMS,
233 fixed_file_info->dwFileVersionLS);
234 result = true;
235 } else {
236 LOG(DFATAL) << "VerQueryValue failed to retrieve VS_FIXEDFILEINFO";
237 }
238 }
239
240 return result;
241 }
242
243 // Replace all occurrences in the sequence [|dest_first|, |dest_last) that
244 // equals [|src_first|, |src_last) with the sequence at |replacement_first| of
245 // the same length. Returns true on success. If non-NULL, |replacements_made|
246 // is set to true/false accordingly.
247 bool ReplaceAll(uint8* dest_first, uint8* dest_last,
248 const uint8* src_first, const uint8* src_last,
249 const uint8* replacement_first, bool* replacements_made) {
250 bool result = true;
251 bool changed = false;
252 do {
253 dest_first = std::search(dest_first, dest_last, src_first, src_last);
254 if (dest_first == dest_last) {
255 break;
256 }
257 changed = true;
258 if (memcpy_s(dest_first, dest_last - dest_first,
259 replacement_first, src_last - src_first) != 0) {
260 result = false;
261 break;
262 }
263 dest_first += (src_last - src_first);
264 } while (true);
265
266 if (replacements_made != NULL) {
267 *replacements_made = changed;
268 }
269
270 return result;
271 }
272
273 // A context structure in support of our EnumResource_Fn callback.
274 struct VisitResourceContext {
275 ChromeVersion current_version;
276 std::wstring current_version_str;
277 ChromeVersion new_version;
278 std::wstring new_version_str;
279 }; // struct VisitResourceContext
280
281 // Replaces the old version with the new in a resource. A first pass is made to
282 // replace the string form (e.g., "9.0.584.0"). If any replacements are made, a
283 // second pass is made to replace the binary form (e.g., 0x0000024800000009).
284 void VisitResource(const upgrade_test::EntryPath& path,
285 uint8* data, DWORD size, DWORD code_page,
286 uintptr_t context) {
287 VisitResourceContext& ctx = *reinterpret_cast<VisitResourceContext*>(context);
288
289 // Replace all occurrences of current_version_str with new_version_str
290 bool changing_version = false;
291 if (ReplaceAll(
292 data,
293 data + size,
294 reinterpret_cast<const uint8*>(ctx.current_version_str.c_str()),
295 reinterpret_cast<const uint8*>(ctx.current_version_str.c_str() +
296 ctx.current_version_str.size() + 1),
297 reinterpret_cast<const uint8*>(ctx.new_version_str.c_str()),
298 &changing_version) &&
299 changing_version) {
300 // Replace all occurrences of current_version with new_version
301 struct VersionPair {
302 DWORD high;
303 DWORD low;
304 };
305 VersionPair cur_ver = {
306 ctx.current_version.high(), ctx.current_version.low()
307 };
308 VersionPair new_ver = {
309 ctx.new_version.high(), ctx.new_version.low()
310 };
311 ReplaceAll(data, data + size, reinterpret_cast<const uint8*>(&cur_ver),
312 reinterpret_cast<const uint8*>(&cur_ver) + sizeof(cur_ver),
313 reinterpret_cast<const uint8*>(&new_ver), NULL);
314 }
315 }
316
317 // Updates the version strings and numbers in all of |image_file|'s resources.
318 bool UpdateVersionIfMatch(const FilePath& image_file,
319 VisitResourceContext* context) {
320 bool result = false;
321 base::win::ScopedHandle image_handle(base::CreatePlatformFile(
322 image_file,
323 (base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ |
324 base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_EXCLUSIVE_READ |
325 base::PLATFORM_FILE_EXCLUSIVE_WRITE), NULL, NULL));
326 if (image_handle.Get() != INVALID_HANDLE_VALUE) {
327 MappedFile image_mapping;
328 if (image_mapping.Initialize(image_handle)) {
329 base::win::PEImageAsData image(
330 reinterpret_cast<HMODULE>(image_mapping.data()));
331 // PEImage class does not support other-architecture images.
332 if (image.GetNTHeaders()->OptionalHeader.Magic ==
333 IMAGE_NT_OPTIONAL_HDR_MAGIC) {
334 result = upgrade_test::EnumResources(
335 image, &VisitResource, reinterpret_cast<uintptr_t>(context));
336 } else {
337 result = true;
338 }
339 }
340 } else {
341 PLOG(DFATAL) << "Failed to open \"" << image_file.value() << "\"";
342 }
343 return result;
344 }
345
346 // Bumps the version of all .exe and .dll files in |work_dir| as well as the
347 // |work-dir|\Chrome-bin\w.x.y.z directory.
348 bool ApplyNextVersion(const FilePath& work_dir) {
349 VisitResourceContext ctx;
350 if (!GetSetupExeVersion(work_dir, &ctx.current_version)) {
351 return false;
352 }
353 ctx.current_version_str = ctx.current_version.ToString();
354
355 // Figure out a future version with the same string length as this one by
356 // incrementing each component.
357 ULONGLONG incrementer = 1;
358
359 do {
360 if (incrementer == 0) {
361 LOG(DFATAL) << "Improbable version composed of only 9s and/or USHRT_MAX";
362 return false;
363 }
364 ctx.new_version.set_value(ctx.current_version.value() + incrementer);
365 ctx.new_version_str = ctx.new_version.ToString();
366 incrementer <<= 16;
367 } while (ctx.new_version_str.size() != ctx.current_version_str.size());
368
369 // Modify all .dll and .exe files with the current version.
370 bool doing_great = true;
371 file_util::FileEnumerator all_files(work_dir, true,
372 file_util::FileEnumerator::FILES);
373 do {
374 FilePath file = all_files.Next();
375 if (file.empty()) {
376 break;
377 }
378 std::wstring extension = file.Extension();
379 if (extension == &kExtExe[0] || extension == &kExtDll[0]) {
380 doing_great = UpdateVersionIfMatch(file, &ctx);
381 }
382 } while (doing_great);
383
384 // Change the versioned directory.
385 FilePath chrome_bin = work_dir.Append(&kChromeBin[0]);
386 doing_great = file_util::Move(chrome_bin.Append(ctx.current_version_str),
387 chrome_bin.Append(ctx.new_version_str));
388
389 return doing_great;
390 }
391
392 // Returns the path to the directory holding the 7za executable. By default, it
393 // is assumed that the test resides in the tree's output directory, so the
394 // relative path "..\..\third_party\lzma_sdk\Executable" is applied to the host
395 // executable's directory. This can be overridden with the --7za_path
396 // command-line switch.
397 FilePath Get7zaPath() {
398 FilePath l7za_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
399 &kSwitch7zaPath[0]);
400 if (l7za_path.empty()) {
401 FilePath dir_exe;
402 if (!PathService::Get(base::DIR_EXE, &dir_exe))
403 LOG(DFATAL) << "Failed getting directory of host executable";
404 l7za_path = dir_exe.Append(&k7zaPathRelative[0]);
405 }
406 return l7za_path;
407 }
408
409 bool CreateArchive(const FilePath& output_file, const FilePath& input_path,
410 int compression_level) {
411 DCHECK(compression_level == 0 ||
412 compression_level >= 1 && compression_level <= 9 &&
413 (compression_level & 0x01) != 0);
414
415 std::wstring command_line(1, L'"');
416 command_line
417 .append(Get7zaPath().Append(&k7zaExe[0]).value())
418 .append(L"\" a -bd -t7z \"")
419 .append(output_file.value())
420 .append(L"\" \"")
421 .append(input_path.value())
422 .append(L"\" -mx")
423 .append(1, L'0' + compression_level);
424 int exit_code;
425 if (!RunProcessAndWait(NULL, command_line, &exit_code))
426 return false;
427 if (exit_code != 0) {
428 LOG(DFATAL) << Get7zaPath().Append(&k7zaExe[0]).value()
429 << " exited with code " << exit_code
430 << " while creating " << output_file.value();
431 return false;
432 }
433 return true;
434 }
435
436 } // namespace
437
438 namespace upgrade_test {
439
440 bool GenerateNextVersion(const FilePath& original_installer_path,
441 const FilePath& target_path) {
442 // Create a temporary directory in which we'll do our work.
443 ScopedTempDirectory work_dir;
444 if (!work_dir.Initialize())
445 return false;
446
447 // Copy the original mini_installer.
448 FilePath mini_installer =
449 work_dir.directory().Append(original_installer_path.BaseName());
450 if (!file_util::CopyFile(original_installer_path, mini_installer)) {
451 LOG(DFATAL) << "Failed copying \"" << original_installer_path.value()
452 << "\" to \"" << mini_installer.value() << "\"";
453 return false;
454 }
455
456 FilePath setup_ex_ = work_dir.directory().Append(&kSetupEx_[0]);
457 FilePath chrome_packed_7z = work_dir.directory().Append(&kChromePacked7z[0]);
458 // Load the original file and extract setup.ex_ and chrome.packed.7z
459 {
460 ResourceLoader resource_loader;
461 std::pair<const uint8*, DWORD> resource_data;
462
463 if (!resource_loader.Initialize(mini_installer))
464 return false;
465
466 // Write out setup.ex_
467 if (!resource_loader.Load(&kSetupEx_[0], &kBl[0], &resource_data))
468 return false;
469 int written =
470 file_util::WriteFile(setup_ex_,
471 reinterpret_cast<const char*>(resource_data.first),
472 static_cast<int>(resource_data.second));
473 if (written != resource_data.second) {
474 LOG(DFATAL) << "Failed writing \"" << setup_ex_.value() << "\"";
475 return false;
476 }
477
478 // Write out chrome.packed.7z
479 if (!resource_loader.Load(&kChromePacked7z[0], &kB7[0], &resource_data))
480 return false;
481 written =
482 file_util::WriteFile(chrome_packed_7z,
483 reinterpret_cast<const char*>(resource_data.first),
484 static_cast<int>(resource_data.second));
485 if (written != resource_data.second) {
486 LOG(DFATAL) << "Failed writing \"" << chrome_packed_7z.value() << "\"";
487 return false;
488 }
489 }
490
491 // Expand setup.ex_
492 FilePath setup_exe = setup_ex_.ReplaceExtension(&kExe[0]);
493 std::wstring command_line;
494 command_line.append(1, L'"')
495 .append(&kExpandExe[0])
496 .append(L"\" \"")
497 .append(setup_ex_.value())
498 .append(L"\" \"")
499 .append(setup_exe.value())
500 .append(1, L'\"');
501 int exit_code;
502 if (!RunProcessAndWait(NULL, command_line, &exit_code))
503 return false;
504 if (exit_code != 0) {
505 LOG(DFATAL) << &kExpandExe[0] << " exited with code " << exit_code;
506 return false;
507 }
508
509 // Unpack chrome.packed.7z
510 std::wstring chrome_7z_name;
511 if (LzmaUtil::UnPackArchive(chrome_packed_7z.value(),
512 work_dir.directory().value(),
513 &chrome_7z_name) != NO_ERROR) {
514 LOG(DFATAL) << "Failed unpacking \"" << chrome_packed_7z.value() << "\"";
515 return false;
516 }
517
518 // Unpack chrome.7z
519 if (LzmaUtil::UnPackArchive(chrome_7z_name, work_dir.directory().value(),
520 NULL) != NO_ERROR) {
521 LOG(DFATAL) << "Failed unpacking \"" << chrome_7z_name << "\"";
522 return false;
523 }
524
525 // Get rid of intermediate files
526 FilePath chrome_7z(chrome_7z_name);
527 if (!file_util::Delete(chrome_7z, false) ||
528 !file_util::Delete(chrome_packed_7z, false) ||
529 !file_util::Delete(setup_ex_, false)) {
530 LOG(DFATAL) << "Failed deleting intermediate files";
531 return false;
532 }
533
534 // Increment the version in all files.
535 ApplyNextVersion(work_dir.directory());
536
537 // Pack up files into chrome.7z
538 if (!CreateArchive(chrome_7z, work_dir.directory().Append(&kChromeBin[0]), 0))
539 return false;
540
541 // Compress chrome.7z into chrome.packed.7z
542 if (!CreateArchive(chrome_packed_7z, chrome_7z, 9))
543 return false;
544
545 // Compress setup.exe into setup.ex_
546 command_line.assign(1, L'"')
547 .append(&kMakeCab[0])
548 .append(L"\" /D CompressionType=LZX /L \"")
549 .append(work_dir.directory().value())
550 .append(L"\" \"")
551 .append(setup_exe.value());
552 if (!RunProcessAndWait(NULL, command_line, &exit_code))
553 return false;
554 if (exit_code != 0) {
555 LOG(DFATAL) << &kMakeCab[0] << " exited with code " << exit_code;
556 return false;
557 }
558
559 // Replace the mini_installer's setup.ex_ and chrome.packed.7z resources.
560 ResourceUpdater updater;
561 if (!updater.Initialize(mini_installer) ||
562 !updater.Update(&kSetupEx_[0], &kBl[0],
563 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
564 setup_ex_) ||
565 !updater.Update(&kChromePacked7z[0], &kB7[0],
566 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
567 chrome_packed_7z) ||
568 !updater.Commit()) {
569 return false;
570 }
571
572 // Finally, move the updated mini_installer into place.
573 return file_util::Move(mini_installer, target_path);
574 }
575
576 } // namespace upgrade_test
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698