alternate_version_generator.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
1// Copyright (c) 2011 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/string_util.h"
43#include "base/version.h"
44#include "base/win/pe_image.h"
45#include "base/win/scoped_handle.h"
46#include "chrome/installer/test/pe_image_resources.h"
47#include "chrome/installer/test/resource_loader.h"
48#include "chrome/installer/test/resource_updater.h"
49#include "chrome/installer/util/lzma_util.h"
50
51namespace {
52
53const wchar_t k7zaExe[] = L"7za.exe";
54const wchar_t k7zaPathRelative[] = L"..\\..\\third_party\\lzma_sdk\\Executable";
55const wchar_t kB7[] = L"B7";
56const wchar_t kBl[] = L"BL";
57const wchar_t kChrome7z[] = L"chrome.7z";
58const wchar_t kChromeBin[] = L"Chrome-bin";
59const wchar_t kChromePacked7z[] = L"chrome.packed.7z";
60const wchar_t kExe[] = L"exe";
61const wchar_t kExpandExe[] = L"expand.exe";
62const wchar_t kExtDll[] = L".dll";
63const wchar_t kExtExe[] = L".exe";
64const wchar_t kMakeCab[] = L"makecab.exe";
65const wchar_t kSetupEx_[] = L"setup.ex_";
66const wchar_t kSetupExe[] = L"setup.exe";
67const char kSwitch7zaPath[] = "7za_path";
68const wchar_t kTempDirPrefix[] = L"mini_installer_test_temp";
69
70// A helper class for creating and cleaning a temporary directory.  A temporary
71// directory is created in Initialize and destroyed (along with all of its
72// contents) when the guard instance is destroyed.
73class ScopedTempDirectory {
74 public:
75  ScopedTempDirectory() { }
76  ~ScopedTempDirectory() {
77    if (!directory_.empty() && !file_util::Delete(directory_, true)) {
78      LOG(DFATAL) << "Failed deleting temporary directory \""
79                  << directory_.value() << "\"";
80    }
81  }
82  // Creates a temporary directory.
83  bool Initialize() {
84    DCHECK(directory_.empty());
85    if (!file_util::CreateNewTempDirectory(&kTempDirPrefix[0], &directory_)) {
86      LOG(DFATAL) << "Failed creating temporary directory.";
87      return false;
88    }
89    return true;
90  }
91  const FilePath& directory() const {
92    DCHECK(!directory_.empty());
93    return directory_;
94  }
95
96 private:
97  FilePath directory_;
98  DISALLOW_COPY_AND_ASSIGN(ScopedTempDirectory);
99};  // class ScopedTempDirectory
100
101// A helper class for manipulating a Chrome product version.
102class ChromeVersion {
103 public:
104  static ChromeVersion FromHighLow(DWORD high, DWORD low) {
105    return ChromeVersion(static_cast<ULONGLONG>(high) << 32 |
106                         static_cast<ULONGLONG>(low));
107  }
108  static ChromeVersion FromString(const std::string& version_string) {
109    Version version(version_string);
110    DCHECK(version.IsValid());
111    const std::vector<uint16>& c(version.components());
112    return ChromeVersion(static_cast<ULONGLONG>(c[0]) << 48 |
113                         static_cast<ULONGLONG>(c[1]) << 32 |
114                         static_cast<ULONGLONG>(c[2]) << 16 |
115                         static_cast<ULONGLONG>(c[3]));
116  }
117
118  ChromeVersion() { }
119  explicit ChromeVersion(ULONGLONG value) : version_(value) { }
120  WORD major() const { return static_cast<WORD>(version_ >> 48); }
121  WORD minor() const { return static_cast<WORD>(version_ >> 32); }
122  WORD build() const { return static_cast<WORD>(version_ >> 16); }
123  WORD patch() const { return static_cast<WORD>(version_); }
124  DWORD high() const { return static_cast<DWORD>(version_ >> 32); }
125  DWORD low() const { return static_cast<DWORD>(version_); }
126  ULONGLONG value() const { return version_; }
127  void set_value(ULONGLONG value) { version_ = value; }
128  std::wstring ToString() const;
129 private:
130  ULONGLONG version_;
131};  // class ChromeVersion
132
133std::wstring ChromeVersion::ToString() const {
134  wchar_t buffer[24];
135  int string_len =
136      swprintf_s(&buffer[0], arraysize(buffer), L"%hu.%hu.%hu.%hu",
137                 major(), minor(), build(), patch());
138  DCHECK_NE(-1, string_len);
139  DCHECK_GT(static_cast<int>(arraysize(buffer)), string_len);
140  return std::wstring(&buffer[0], string_len);
141}
142
143
144// A read/write mapping of a file.
145// Note: base::MemoryMappedFile is not used because it doesn't support
146// read/write mappings.  Adding such support across all platforms for this
147// Windows-only test code seems like overkill.
148class MappedFile {
149 public:
150  MappedFile() : size_(), mapping_(), view_() { }
151  ~MappedFile();
152  bool Initialize(base::PlatformFile file);
153  void* data() const { return view_; }
154  size_t size() const { return size_; }
155 private:
156  size_t size_;
157  HANDLE mapping_;
158  void* view_;
159  DISALLOW_COPY_AND_ASSIGN(MappedFile);
160};  // class MappedFile
161
162MappedFile::~MappedFile() {
163  if (view_ != NULL) {
164    if (UnmapViewOfFile(view_) == 0) {
165      PLOG(DFATAL) << "MappedFile failed to unmap view.";
166    }
167  }
168  if (mapping_ != NULL) {
169    if (CloseHandle(mapping_) == 0) {
170      PLOG(DFATAL) << "Could not close file mapping handle.";
171    }
172  }
173}
174
175bool MappedFile::Initialize(base::PlatformFile file) {
176  DCHECK(mapping_ == NULL);
177  bool result = false;
178  base::PlatformFileInfo file_info;
179
180  if (base::GetPlatformFileInfo(file, &file_info)) {
181    if (file_info.size <=
182        static_cast<int64>(std::numeric_limits<size_t>::max())) {
183      mapping_ = CreateFileMapping(file, NULL, PAGE_READWRITE, 0,
184                                   static_cast<DWORD>(file_info.size), NULL);
185      if (mapping_ != NULL) {
186        view_ = MapViewOfFile(mapping_, FILE_MAP_WRITE, 0, 0,
187                              static_cast<size_t>(file_info.size));
188        if (view_ != NULL) {
189          result = true;
190        } else {
191          PLOG(DFATAL) << "MapViewOfFile failed";
192        }
193      } else {
194        PLOG(DFATAL) << "CreateFileMapping failed";
195      }
196    } else {
197      LOG(DFATAL) << "Files larger than " << std::numeric_limits<size_t>::max()
198                  << " are not supported.";
199    }
200  } else {
201    PLOG(DFATAL) << "GetPlatformFileInfo failed";
202  }
203  return result;
204}
205
206// Calls CreateProcess with good default parameters and waits for the process
207// to terminate returning the process exit code.
208bool RunProcessAndWait(const wchar_t* exe_path, const std::wstring& cmdline,
209                       int* exit_code) {
210  bool result = true;
211  base::ProcessHandle process;
212  base::LaunchOptions options;
213  options.wait = true;
214  options.start_hidden = true;
215  if (base::LaunchProcess(cmdline, options, &process)) {
216    if (exit_code) {
217      if (!GetExitCodeProcess(process,
218                              reinterpret_cast<DWORD*>(exit_code))) {
219        PLOG(DFATAL) << "Failed getting the exit code for \""
220                     << cmdline << "\".";
221        result = false;
222      } else {
223        DCHECK_NE(*exit_code, STILL_ACTIVE);
224      }
225    }
226  } else {
227    result = false;
228  }
229
230  CloseHandle(process);
231  return result;
232}
233
234// Retrieves the version number of |pe_file| from its version
235// resource, placing the value in |version|.  Returns true on success.
236bool GetFileVersion(const FilePath& pe_file, ChromeVersion* version) {
237  DCHECK(version);
238  bool result = false;
239  upgrade_test::ResourceLoader pe_file_loader;
240  std::pair<const uint8*, DWORD> version_info_data;
241
242  if (pe_file_loader.Initialize(pe_file) &&
243      pe_file_loader.Load(VS_VERSION_INFO, reinterpret_cast<WORD>(RT_VERSION),
244                          &version_info_data)) {
245    const VS_FIXEDFILEINFO* fixed_file_info;
246    UINT ver_info_len;
247    if (VerQueryValue(version_info_data.first, L"\\",
248                      reinterpret_cast<void**>(
249                          const_cast<VS_FIXEDFILEINFO**>(&fixed_file_info)),
250                      &ver_info_len) != 0) {
251      DCHECK_EQ(sizeof(VS_FIXEDFILEINFO), static_cast<size_t>(ver_info_len));
252      *version = ChromeVersion::FromHighLow(fixed_file_info->dwFileVersionMS,
253                                            fixed_file_info->dwFileVersionLS);
254      result = true;
255    } else {
256      LOG(DFATAL) << "VerQueryValue failed to retrieve VS_FIXEDFILEINFO";
257    }
258  }
259
260  return result;
261}
262
263// Retrieves the version number of setup.exe in |work_dir| from its version
264// resource, placing the value in |version|.  Returns true on success.
265bool GetSetupExeVersion(const FilePath& work_dir, ChromeVersion* version) {
266  return GetFileVersion(work_dir.Append(&kSetupExe[0]), version);
267}
268
269
270// Replace all occurrences in the sequence [|dest_first|, |dest_last) that
271// equals [|src_first|, |src_last) with the sequence at |replacement_first| of
272// the same length.  Returns true on success.  If non-NULL, |replacements_made|
273// is set to true/false accordingly.
274bool ReplaceAll(uint8* dest_first, uint8* dest_last,
275                const uint8* src_first, const uint8* src_last,
276                const uint8* replacement_first, bool* replacements_made) {
277  bool result = true;
278  bool changed = false;
279  do {
280    dest_first = std::search(dest_first, dest_last, src_first, src_last);
281    if (dest_first == dest_last) {
282      break;
283    }
284    changed = true;
285    if (memcpy_s(dest_first, dest_last - dest_first,
286                 replacement_first, src_last - src_first) != 0) {
287      result = false;
288      break;
289    }
290    dest_first += (src_last - src_first);
291  } while (true);
292
293  if (replacements_made != NULL) {
294    *replacements_made = changed;
295  }
296
297  return result;
298}
299
300// A context structure in support of our EnumResource_Fn callback.
301struct VisitResourceContext {
302  ChromeVersion current_version;
303  std::wstring current_version_str;
304  ChromeVersion new_version;
305  std::wstring new_version_str;
306};  // struct VisitResourceContext
307
308// Replaces the old version with the new in a resource.  A first pass is made to
309// replace the string form (e.g., "9.0.584.0").  If any replacements are made, a
310// second pass is made to replace the binary form (e.g., 0x0000024800000009).
311void VisitResource(const upgrade_test::EntryPath& path,
312                   uint8* data, DWORD size, DWORD code_page,
313                   uintptr_t context) {
314  VisitResourceContext& ctx = *reinterpret_cast<VisitResourceContext*>(context);
315
316  // Replace all occurrences of current_version_str with new_version_str
317  bool changing_version = false;
318  if (ReplaceAll(
319          data,
320          data + size,
321          reinterpret_cast<const uint8*>(ctx.current_version_str.c_str()),
322          reinterpret_cast<const uint8*>(ctx.current_version_str.c_str() +
323              ctx.current_version_str.size() + 1),
324          reinterpret_cast<const uint8*>(ctx.new_version_str.c_str()),
325          &changing_version) &&
326      changing_version) {
327    // Replace all occurrences of current_version with new_version
328    struct VersionPair {
329      DWORD high;
330      DWORD low;
331    };
332    VersionPair cur_ver = {
333      ctx.current_version.high(), ctx.current_version.low()
334    };
335    VersionPair new_ver = {
336      ctx.new_version.high(), ctx.new_version.low()
337    };
338    ReplaceAll(data, data + size, reinterpret_cast<const uint8*>(&cur_ver),
339               reinterpret_cast<const uint8*>(&cur_ver) + sizeof(cur_ver),
340               reinterpret_cast<const uint8*>(&new_ver), NULL);
341  }
342}
343
344// Updates the version strings and numbers in all of |image_file|'s resources.
345bool UpdateVersionIfMatch(const FilePath& image_file,
346                          VisitResourceContext* context) {
347  if (!context ||
348      context->current_version_str.size() < context->new_version_str.size()) {
349    return false;
350  }
351
352  bool result = false;
353  base::win::ScopedHandle image_handle(base::CreatePlatformFile(
354      image_file,
355      (base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ |
356       base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_EXCLUSIVE_READ |
357       base::PLATFORM_FILE_EXCLUSIVE_WRITE), NULL, NULL));
358  // It turns out that the underlying CreateFile can fail due to unhelpful
359  // security software locking the newly created DLL. So add a few brief
360  // retries to help tests that use this pass on machines thusly encumbered.
361  int retries = 3;
362  while (!image_handle.IsValid() && retries-- > 0) {
363    LOG(WARNING) << "Failed to open \"" << image_file.value() << "\"."
364                 << " Retrying " << retries << " more times.";
365    Sleep(1000);
366    image_handle.Set(base::CreatePlatformFile(
367      image_file,
368      (base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ |
369       base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_EXCLUSIVE_READ |
370       base::PLATFORM_FILE_EXCLUSIVE_WRITE), NULL, NULL));
371  }
372
373  if (image_handle.IsValid()) {
374    MappedFile image_mapping;
375    if (image_mapping.Initialize(image_handle)) {
376      base::win::PEImageAsData image(
377          reinterpret_cast<HMODULE>(image_mapping.data()));
378      // PEImage class does not support other-architecture images.
379      if (image.GetNTHeaders()->OptionalHeader.Magic ==
380          IMAGE_NT_OPTIONAL_HDR_MAGIC) {
381        result = upgrade_test::EnumResources(
382            image, &VisitResource, reinterpret_cast<uintptr_t>(context));
383      } else {
384        result = true;
385      }
386    }
387  } else {
388    PLOG(DFATAL) << "Failed to open \"" << image_file.value() << "\"";
389  }
390  return result;
391}
392
393bool IncrementNewVersion(upgrade_test::Direction direction,
394                         VisitResourceContext* ctx) {
395  DCHECK(ctx);
396
397  // Figure out a past or future version with the same string length as this one
398  // by decrementing or incrementing each component.
399  LONGLONG incrementer = (direction == upgrade_test::PREVIOUS_VERSION ? -1 : 1);
400
401  do {
402    if (incrementer == 0) {
403      LOG(DFATAL) << "Improbable version at the cusp of complete rollover";
404      return false;
405    }
406    ctx->new_version.set_value(ctx->current_version.value() + incrementer);
407    ctx->new_version_str = ctx->new_version.ToString();
408    incrementer <<= 16;
409  } while (ctx->new_version_str.size() != ctx->current_version_str.size());
410
411  return true;
412}
413
414// Raises or lowers the version of all .exe and .dll files in |work_dir| as well
415// as the |work-dir|\Chrome-bin\w.x.y.z directory.  |original_version| and
416// |new_version|, when non-NULL, are given the original and new version numbers
417// on success.
418bool ApplyAlternateVersion(const FilePath& work_dir,
419                           upgrade_test::Direction direction,
420                           std::wstring* original_version,
421                           std::wstring* new_version) {
422  VisitResourceContext ctx;
423  if (!GetSetupExeVersion(work_dir, &ctx.current_version)) {
424    return false;
425  }
426  ctx.current_version_str = ctx.current_version.ToString();
427
428  if (!IncrementNewVersion(direction, &ctx)) {
429    return false;
430  }
431
432  // Modify all .dll and .exe files with the current version.
433  bool doing_great = true;
434  file_util::FileEnumerator all_files(work_dir, true,
435                                      file_util::FileEnumerator::FILES);
436  do {
437    FilePath file = all_files.Next();
438    if (file.empty()) {
439      break;
440    }
441    std::wstring extension = file.Extension();
442    if (extension == &kExtExe[0] || extension == &kExtDll[0]) {
443      doing_great = UpdateVersionIfMatch(file, &ctx);
444    }
445  } while (doing_great);
446
447  // Change the versioned directory.
448  FilePath chrome_bin = work_dir.Append(&kChromeBin[0]);
449  doing_great = file_util::Move(chrome_bin.Append(ctx.current_version_str),
450                                chrome_bin.Append(ctx.new_version_str));
451
452  if (doing_great) {
453    // Report the version numbers if requested.
454    if (original_version != NULL)
455      original_version->assign(ctx.current_version_str);
456    if (new_version != NULL)
457      new_version->assign(ctx.new_version_str);
458  }
459
460  return doing_great;
461}
462
463// Returns the path to the directory holding the 7za executable.  By default, it
464// is assumed that the test resides in the tree's output directory, so the
465// relative path "..\..\third_party\lzma_sdk\Executable" is applied to the host
466// executable's directory.  This can be overridden with the --7za_path
467// command-line switch.
468FilePath Get7zaPath() {
469  FilePath l7za_path = CommandLine::ForCurrentProcess()->GetSwitchValuePath(
470      &kSwitch7zaPath[0]);
471  if (l7za_path.empty()) {
472    FilePath dir_exe;
473    if (!PathService::Get(base::DIR_EXE, &dir_exe))
474      LOG(DFATAL) << "Failed getting directory of host executable";
475    l7za_path = dir_exe.Append(&k7zaPathRelative[0]);
476  }
477  return l7za_path;
478}
479
480bool CreateArchive(const FilePath& output_file, const FilePath& input_path,
481                   int compression_level) {
482  DCHECK(compression_level == 0 ||
483         compression_level >= 1 && compression_level <= 9 &&
484         (compression_level & 0x01) != 0);
485
486  std::wstring command_line(1, L'"');
487  command_line
488      .append(Get7zaPath().Append(&k7zaExe[0]).value())
489      .append(L"\" a -bd -t7z \"")
490      .append(output_file.value())
491      .append(L"\" \"")
492      .append(input_path.value())
493      .append(L"\" -mx")
494      .append(1, L'0' + compression_level);
495  int exit_code;
496  if (!RunProcessAndWait(NULL, command_line, &exit_code))
497    return false;
498  if (exit_code != 0) {
499    LOG(DFATAL) << Get7zaPath().Append(&k7zaExe[0]).value()
500                << " exited with code " << exit_code
501                << " while creating " << output_file.value();
502    return false;
503  }
504  return true;
505}
506
507}  // namespace
508
509namespace upgrade_test {
510
511bool GenerateAlternateVersion(const FilePath& original_installer_path,
512                              const FilePath& target_path,
513                              Direction direction,
514                              std::wstring* original_version,
515                              std::wstring* new_version) {
516  // Create a temporary directory in which we'll do our work.
517  ScopedTempDirectory work_dir;
518  if (!work_dir.Initialize())
519    return false;
520
521  // Copy the original mini_installer.
522  FilePath mini_installer =
523      work_dir.directory().Append(original_installer_path.BaseName());
524  if (!file_util::CopyFile(original_installer_path, mini_installer)) {
525    LOG(DFATAL) << "Failed copying \"" << original_installer_path.value()
526                << "\" to \"" << mini_installer.value() << "\"";
527    return false;
528  }
529
530  FilePath setup_ex_ = work_dir.directory().Append(&kSetupEx_[0]);
531  FilePath chrome_packed_7z = work_dir.directory().Append(&kChromePacked7z[0]);
532  // Load the original file and extract setup.ex_ and chrome.packed.7z
533  {
534    ResourceLoader resource_loader;
535    std::pair<const uint8*, DWORD> resource_data;
536
537    if (!resource_loader.Initialize(mini_installer))
538      return false;
539
540    // Write out setup.ex_
541    if (!resource_loader.Load(&kSetupEx_[0], &kBl[0], &resource_data))
542      return false;
543    int written =
544        file_util::WriteFile(setup_ex_,
545                             reinterpret_cast<const char*>(resource_data.first),
546                             static_cast<int>(resource_data.second));
547    if (written != resource_data.second) {
548      LOG(DFATAL) << "Failed writing \"" << setup_ex_.value() << "\"";
549      return false;
550    }
551
552    // Write out chrome.packed.7z
553    if (!resource_loader.Load(&kChromePacked7z[0], &kB7[0], &resource_data))
554      return false;
555    written =
556        file_util::WriteFile(chrome_packed_7z,
557                             reinterpret_cast<const char*>(resource_data.first),
558                             static_cast<int>(resource_data.second));
559    if (written != resource_data.second) {
560      LOG(DFATAL) << "Failed writing \"" << chrome_packed_7z.value() << "\"";
561      return false;
562    }
563  }
564
565  // Expand setup.ex_
566  FilePath setup_exe = setup_ex_.ReplaceExtension(&kExe[0]);
567  std::wstring command_line;
568  command_line.append(1, L'"')
569    .append(&kExpandExe[0])
570    .append(L"\" \"")
571    .append(setup_ex_.value())
572    .append(L"\" \"")
573    .append(setup_exe.value())
574    .append(1, L'\"');
575  int exit_code;
576  if (!RunProcessAndWait(NULL, command_line, &exit_code))
577    return false;
578  if (exit_code != 0) {
579    LOG(DFATAL) << &kExpandExe[0] << " exited with code " << exit_code;
580    return false;
581  }
582
583  // Unpack chrome.packed.7z
584  std::wstring chrome_7z_name;
585  if (LzmaUtil::UnPackArchive(chrome_packed_7z.value(),
586                              work_dir.directory().value(),
587                              &chrome_7z_name) != NO_ERROR) {
588    LOG(DFATAL) << "Failed unpacking \"" << chrome_packed_7z.value() << "\"";
589    return false;
590  }
591
592  // Unpack chrome.7z
593  if (LzmaUtil::UnPackArchive(chrome_7z_name, work_dir.directory().value(),
594                              NULL) != NO_ERROR) {
595    LOG(DFATAL) << "Failed unpacking \"" << chrome_7z_name << "\"";
596    return false;
597  }
598
599  // Get rid of intermediate files
600  FilePath chrome_7z(chrome_7z_name);
601  if (!file_util::Delete(chrome_7z, false) ||
602      !file_util::Delete(chrome_packed_7z, false) ||
603      !file_util::Delete(setup_ex_, false)) {
604    LOG(DFATAL) << "Failed deleting intermediate files";
605    return false;
606  }
607
608  // Increment the version in all files.
609  ApplyAlternateVersion(work_dir.directory(), direction, original_version,
610                        new_version);
611
612  // Pack up files into chrome.7z
613  if (!CreateArchive(chrome_7z, work_dir.directory().Append(&kChromeBin[0]), 0))
614    return false;
615
616  // Compress chrome.7z into chrome.packed.7z
617  if (!CreateArchive(chrome_packed_7z, chrome_7z, 9))
618    return false;
619
620  // Compress setup.exe into setup.ex_
621  command_line.assign(1, L'"')
622      .append(&kMakeCab[0])
623      .append(L"\" /D CompressionType=LZX /L \"")
624      .append(work_dir.directory().value())
625      .append(L"\" \"")
626      .append(setup_exe.value());
627  if (!RunProcessAndWait(NULL, command_line, &exit_code))
628    return false;
629  if (exit_code != 0) {
630    LOG(DFATAL) << &kMakeCab[0] << " exited with code " << exit_code;
631    return false;
632  }
633
634  // Replace the mini_installer's setup.ex_ and chrome.packed.7z resources.
635  ResourceUpdater updater;
636  if (!updater.Initialize(mini_installer) ||
637      !updater.Update(&kSetupEx_[0], &kBl[0],
638                      MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
639                      setup_ex_) ||
640      !updater.Update(&kChromePacked7z[0], &kB7[0],
641                      MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
642                      chrome_packed_7z) ||
643      !updater.Commit()) {
644    return false;
645  }
646
647  // Finally, move the updated mini_installer into place.
648  return file_util::Move(mini_installer, target_path);
649}
650
651bool GenerateAlternatePEFileVersion(const FilePath& original_file,
652                                    const FilePath& target_file,
653                                    Direction direction) {
654  VisitResourceContext ctx;
655  if (!GetFileVersion(original_file, &ctx.current_version)) {
656    LOG(DFATAL) << "Failed reading version from \"" << original_file.value()
657                << "\"";
658    return false;
659  }
660  ctx.current_version_str = ctx.current_version.ToString();
661
662  if (!IncrementNewVersion(direction, &ctx)) {
663    LOG(DFATAL) << "Failed to increment version from \""
664                << original_file.value() << "\"";
665    return false;
666  }
667
668  Version new_version(WideToASCII(ctx.new_version_str));
669  GenerateSpecificPEFileVersion(original_file, target_file, new_version);
670
671  return true;
672}
673
674bool GenerateSpecificPEFileVersion(const FilePath& original_file,
675                                   const FilePath& target_file,
676                                   const Version& version) {
677  // First copy original_file to target_file.
678  if (!file_util::CopyFile(original_file, target_file)) {
679    LOG(DFATAL) << "Failed copying \"" << original_file.value()
680                << "\" to \"" << target_file.value() << "\"";
681    return false;
682  }
683
684  VisitResourceContext ctx;
685  if (!GetFileVersion(target_file, &ctx.current_version)) {
686    LOG(DFATAL) << "Failed reading version from \"" << target_file.value()
687                << "\"";
688    return false;
689  }
690  ctx.current_version_str = ctx.current_version.ToString();
691  ctx.new_version = ChromeVersion::FromString(version.GetString());
692  ctx.new_version_str = ctx.new_version.ToString();
693
694  return UpdateVersionIfMatch(target_file, &ctx);
695}
696
697}  // namespace upgrade_test
698