1// Copyright 2013 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/browser/install_verification/win/module_list.h"
6
7#include <Psapi.h>
8
9#include <algorithm>
10
11#include "base/logging.h"
12#include "chrome/browser/install_verification/win/module_info.h"
13
14namespace {
15
16void CheckFreeLibrary(HMODULE module) {
17  BOOL result = ::FreeLibrary(module);
18  DCHECK(result);
19}
20
21}  // namespace
22
23ModuleList::~ModuleList() {
24  std::for_each(modules_.begin(), modules_.end(), &CheckFreeLibrary);
25}
26
27scoped_ptr<ModuleList> ModuleList::FromLoadedModuleSnapshot(
28    const std::vector<HMODULE>& snapshot) {
29  scoped_ptr<ModuleList> instance(new ModuleList);
30
31  for (size_t i = 0; i < snapshot.size(); ++i) {
32    HMODULE module = NULL;
33    // ::GetModuleHandleEx add-ref's the module if successful.
34    if (::GetModuleHandleEx(
35            GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
36            reinterpret_cast<LPCWSTR>(snapshot[i]),
37            &module)) {
38        instance->modules_.push_back(module);
39    }
40  }
41
42  return instance.Pass();
43}
44
45void ModuleList::GetModuleInfoSet(std::set<ModuleInfo>* module_info_set) {
46  HANDLE current_process = ::GetCurrentProcess();
47  for (size_t i = 0; i < modules_.size(); ++i) {
48    wchar_t filename[MAX_PATH];
49    // Simply ignore modules where GetModuleFileName or GetModuleInformation
50    // failed, they might have been unloaded.
51    if (::GetModuleFileName(modules_[i], filename, MAX_PATH) &&
52        filename[0]) {
53      MODULEINFO sys_module_info = {};
54      if (::GetModuleInformation(
55              current_process, modules_[i],
56              &sys_module_info, sizeof(sys_module_info))) {
57        module_info_set->insert(ModuleInfo(
58            filename,
59            reinterpret_cast<uintptr_t>(sys_module_info.lpBaseOfDll),
60            sys_module_info.SizeOfImage));
61      }
62    }
63  }
64}
65
66ModuleList::ModuleList() {}
67