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#include "chrome/installer/test/resource_loader.h"
6
7#include <windows.h>
8
9#include "base/files/file_path.h"
10#include "base/logging.h"
11
12namespace {
13
14// Populates |resource_data| with the address and size of the resource in
15// |module| identified by |name_or_id| of type |type_name_or_id|, returning
16// true on success.
17bool DoLoad(HMODULE module, const wchar_t* name_or_id,
18            const wchar_t* type_name_or_id,
19            std::pair<const uint8*, DWORD>* resource_data) {
20  bool loaded = false;
21  HRSRC resource_info;
22
23  resource_info = FindResource(module, name_or_id, type_name_or_id);
24  if (resource_info != NULL) {
25    HGLOBAL loaded_resource;
26
27    loaded_resource = LoadResource(module, resource_info);
28    if (loaded_resource != NULL) {
29      resource_data->first =
30          static_cast<const uint8*>(LockResource(loaded_resource));
31      if (resource_data->first != NULL) {
32        resource_data->second = SizeofResource(module, resource_info);
33        DPCHECK(resource_data->second != 0);
34        loaded = true;
35      } else {
36        DPCHECK(false) << "LockResource failed";
37      }
38    } else {
39      DPCHECK(false) << "LoadResource failed";
40    }
41  } else {
42    DPLOG(INFO) << "FindResource failed";
43  }
44
45  return loaded;
46}
47
48}  // namespace
49
50namespace upgrade_test {
51
52ResourceLoader::ResourceLoader() : module_(NULL) {
53}
54
55ResourceLoader::~ResourceLoader() {
56  if (module_ != NULL) {
57    BOOL result = FreeLibrary(module_);
58    DPCHECK(result != 0) << "FreeLibrary failed";
59  }
60}
61
62bool ResourceLoader::Initialize(const base::FilePath& pe_image_path) {
63  DCHECK(module_ == NULL);
64  module_ = LoadLibraryEx(pe_image_path.value().c_str(), NULL,
65                          (LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE |
66                           LOAD_LIBRARY_AS_IMAGE_RESOURCE));
67  DPLOG_IF(INFO, module_ == NULL)
68      << "Failed loading \"" << pe_image_path.value() << "\"";
69  return module_ != NULL;
70}
71
72bool ResourceLoader::Load(const std::wstring& name,
73                          const std::wstring& type,
74                          std::pair<const uint8*, DWORD>* resource_data) {
75  DCHECK(resource_data != NULL);
76  DCHECK(module_ != NULL);
77
78  return DoLoad(module_, name.c_str(), type.c_str(), resource_data);
79}
80
81bool ResourceLoader::Load(WORD id,
82                          WORD type,
83                          std::pair<const uint8*, DWORD>* resource_data) {
84  DCHECK(resource_data != NULL);
85  DCHECK(module_ != NULL);
86
87  return DoLoad(module_, MAKEINTRESOURCE(id), MAKEINTRESOURCE(type),
88                resource_data);
89}
90
91}  // namespace upgrade_test
92