• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2006-2008 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 #include <windows.h>
5 #include <ImageHlp.h>
6 #include <psapi.h>
7 
8 #include "base/image_util.h"
9 #include "base/process_util.h"
10 
11 // imagehlp.dll appears to ship in all win versions after Win95.
12 // nsylvain verified it is present in win2k.
13 // Using #pragma comment for dependency, instead of LoadLibrary/GetProcAddress.
14 #pragma comment(lib, "imagehlp.lib")
15 
16 namespace image_util {
17 
18 // ImageMetrics
ImageMetrics(HANDLE process)19 ImageMetrics::ImageMetrics(HANDLE process) : process_(process) {
20 }
21 
~ImageMetrics()22 ImageMetrics::~ImageMetrics() {
23 }
24 
GetDllImageSectionData(const std::string & loaded_dll_name,ImageSectionsData * section_sizes)25 bool ImageMetrics::GetDllImageSectionData(const std::string& loaded_dll_name,
26                                           ImageSectionsData* section_sizes) {
27   // Get a handle to the loaded DLL
28   HMODULE the_dll = GetModuleHandleA(loaded_dll_name.c_str());
29   char full_filename[MAX_PATH];
30   // Get image path
31   if (GetModuleFileNameExA(process_, the_dll, full_filename, MAX_PATH)) {
32     return GetImageSectionSizes(full_filename, section_sizes);
33   }
34   return false;
35 }
36 
GetProcessImageSectionData(ImageSectionsData * section_sizes)37 bool ImageMetrics::GetProcessImageSectionData(ImageSectionsData*
38                                               section_sizes) {
39   char exe_path[MAX_PATH];
40   // Get image path
41   if (GetModuleFileNameExA(process_, NULL, exe_path, MAX_PATH)) {
42     return GetImageSectionSizes(exe_path, section_sizes);
43   }
44   return false;
45 }
46 
47 // private
GetImageSectionSizes(char * qualified_path,ImageSectionsData * result)48 bool ImageMetrics::GetImageSectionSizes(char* qualified_path,
49                                         ImageSectionsData* result) {
50   LOADED_IMAGE li;
51   // TODO (timsteele): There is no unicode version for MapAndLoad, hence
52   // why ansi functions are used in this class. Should we try and rewrite
53   // this call ourselves to be safe?
54   if (MapAndLoad(qualified_path, 0, &li, FALSE, TRUE)) {
55     IMAGE_SECTION_HEADER* section_header = li.Sections;
56     for (unsigned i = 0; i < li.NumberOfSections; i++, section_header++) {
57       std::string name(reinterpret_cast<char*>(section_header->Name));
58       ImageSectionData data(name, section_header->Misc.VirtualSize ?
59           section_header->Misc.VirtualSize :
60           section_header->SizeOfRawData);
61       // copy into result
62       result->push_back(data);
63     }
64   } else {
65     // map and load failed
66     return false;
67   }
68   UnMapAndLoad(&li);
69   return true;
70 }
71 
72 } // namespace image_util
73