• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // This file was adapted from GreenBorder's Code.
6 // To understand what this class is about (for other than well known functions
7 // as GetProcAddress), a good starting point is "An In-Depth Look into the
8 // Win32 Portable Executable File Format" by Matt Pietrek:
9 // http://msdn.microsoft.com/msdnmag/issues/02/02/PE/default.aspx
10 
11 #ifndef BASE_WIN_PE_IMAGE_H_
12 #define BASE_WIN_PE_IMAGE_H_
13 
14 #include <windows.h>
15 
16 #if defined(_WIN32_WINNT_WIN8)
17 // The Windows 8 SDK defines FACILITY_VISUALCPP in winerror.h.
18 #undef FACILITY_VISUALCPP
19 #endif
20 #include <DelayIMP.h>
21 
22 namespace base {
23 namespace win {
24 
25 // This class is a wrapper for the Portable Executable File Format (PE).
26 // It's main purpose is to provide an easy way to work with imports and exports
27 // from a file, mapped in memory as image.
28 class PEImage {
29  public:
30   // Callback to enumerate sections.
31   // cookie is the value passed to the enumerate method.
32   // Returns true to continue the enumeration.
33   typedef bool (*EnumSectionsFunction)(const PEImage &image,
34                                        PIMAGE_SECTION_HEADER header,
35                                        PVOID section_start, DWORD section_size,
36                                        PVOID cookie);
37 
38   // Callback to enumerate exports.
39   // function is the actual address of the symbol. If forward is not null, it
40   // contains the dll and symbol to forward this export to. cookie is the value
41   // passed to the enumerate method.
42   // Returns true to continue the enumeration.
43   typedef bool (*EnumExportsFunction)(const PEImage &image, DWORD ordinal,
44                                       DWORD hint, LPCSTR name, PVOID function,
45                                       LPCSTR forward, PVOID cookie);
46 
47   // Callback to enumerate import blocks.
48   // name_table and iat point to the imports name table and address table for
49   // this block. cookie is the value passed to the enumerate method.
50   // Returns true to continue the enumeration.
51   typedef bool (*EnumImportChunksFunction)(const PEImage &image, LPCSTR module,
52                                            PIMAGE_THUNK_DATA name_table,
53                                            PIMAGE_THUNK_DATA iat, PVOID cookie);
54 
55   // Callback to enumerate imports.
56   // module is the dll that exports this symbol. cookie is the value passed to
57   // the enumerate method.
58   // Returns true to continue the enumeration.
59   typedef bool (*EnumImportsFunction)(const PEImage &image, LPCSTR module,
60                                       DWORD ordinal, LPCSTR name, DWORD hint,
61                                       PIMAGE_THUNK_DATA iat, PVOID cookie);
62 
63   // Callback to enumerate dalayed import blocks.
64   // module is the dll that exports this block of symbols. cookie is the value
65   // passed to the enumerate method.
66   // Returns true to continue the enumeration.
67   typedef bool (*EnumDelayImportChunksFunction)(const PEImage &image,
68                                                 PImgDelayDescr delay_descriptor,
69                                                 LPCSTR module,
70                                                 PIMAGE_THUNK_DATA name_table,
71                                                 PIMAGE_THUNK_DATA iat,
72                                                 PIMAGE_THUNK_DATA bound_iat,
73                                                 PIMAGE_THUNK_DATA unload_iat,
74                                                 PVOID cookie);
75 
76   // Callback to enumerate relocations.
77   // cookie is the value passed to the enumerate method.
78   // Returns true to continue the enumeration.
79   typedef bool (*EnumRelocsFunction)(const PEImage &image, WORD type,
80                                      PVOID address, PVOID cookie);
81 
PEImage(HMODULE module)82   explicit PEImage(HMODULE module) : module_(module) {}
PEImage(const void * module)83   explicit PEImage(const void* module) {
84     module_ = reinterpret_cast<HMODULE>(const_cast<void*>(module));
85   }
86 
87   // Gets the HMODULE for this object.
88   HMODULE module() const;
89 
90   // Sets this object's HMODULE.
91   void set_module(HMODULE module);
92 
93   // Checks if this symbol is actually an ordinal.
94   static bool IsOrdinal(LPCSTR name);
95 
96   // Converts a named symbol to the corresponding ordinal.
97   static WORD ToOrdinal(LPCSTR name);
98 
99   // Returns the DOS_HEADER for this PE.
100   PIMAGE_DOS_HEADER GetDosHeader() const;
101 
102   // Returns the NT_HEADER for this PE.
103   PIMAGE_NT_HEADERS GetNTHeaders() const;
104 
105   // Returns number of sections of this PE.
106   WORD GetNumSections() const;
107 
108   // Returns the header for a given section.
109   // returns NULL if there is no such section.
110   PIMAGE_SECTION_HEADER GetSectionHeader(UINT section) const;
111 
112   // Returns the size of a given directory entry.
113   DWORD GetImageDirectoryEntrySize(UINT directory) const;
114 
115   // Returns the address of a given directory entry.
116   PVOID GetImageDirectoryEntryAddr(UINT directory) const;
117 
118   // Returns the section header for a given address.
119   // Use: s = image.GetImageSectionFromAddr(a);
120   // Post: 's' is the section header of the section that contains 'a'
121   //       or NULL if there is no such section.
122   PIMAGE_SECTION_HEADER GetImageSectionFromAddr(PVOID address) const;
123 
124   // Returns the section header for a given section.
125   PIMAGE_SECTION_HEADER GetImageSectionHeaderByName(LPCSTR section_name) const;
126 
127   // Returns the first block of imports.
128   PIMAGE_IMPORT_DESCRIPTOR GetFirstImportChunk() const;
129 
130   // Returns the exports directory.
131   PIMAGE_EXPORT_DIRECTORY GetExportDirectory() const;
132 
133   // Returns a given export entry.
134   // Use: e = image.GetExportEntry(f);
135   // Pre: 'f' is either a zero terminated string or ordinal
136   // Post: 'e' is a pointer to the export directory entry
137   //       that contains 'f's export RVA, or NULL if 'f'
138   //       is not exported from this image
139   PDWORD GetExportEntry(LPCSTR name) const;
140 
141   // Returns the address for a given exported symbol.
142   // Use: p = image.GetProcAddress(f);
143   // Pre: 'f' is either a zero terminated string or ordinal.
144   // Post: if 'f' is a non-forwarded export from image, 'p' is
145   //       the exported function. If 'f' is a forwarded export
146   //       then p is the special value 0xFFFFFFFF. In this case
147   //       RVAToAddr(*GetExportEntry) can be used to resolve
148   //       the string that describes the forward.
149   FARPROC GetProcAddress(LPCSTR function_name) const;
150 
151   // Retrieves the ordinal for a given exported symbol.
152   // Returns true if the symbol was found.
153   bool GetProcOrdinal(LPCSTR function_name, WORD *ordinal) const;
154 
155   // Enumerates PE sections.
156   // cookie is a generic cookie to pass to the callback.
157   // Returns true on success.
158   bool EnumSections(EnumSectionsFunction callback, PVOID cookie) const;
159 
160   // Enumerates PE exports.
161   // cookie is a generic cookie to pass to the callback.
162   // Returns true on success.
163   bool EnumExports(EnumExportsFunction callback, PVOID cookie) const;
164 
165   // Enumerates PE imports.
166   // cookie is a generic cookie to pass to the callback.
167   // Returns true on success.
168   bool EnumAllImports(EnumImportsFunction callback, PVOID cookie) const;
169 
170   // Enumerates PE import blocks.
171   // cookie is a generic cookie to pass to the callback.
172   // Returns true on success.
173   bool EnumImportChunks(EnumImportChunksFunction callback, PVOID cookie) const;
174 
175   // Enumerates the imports from a single PE import block.
176   // cookie is a generic cookie to pass to the callback.
177   // Returns true on success.
178   bool EnumOneImportChunk(EnumImportsFunction callback, LPCSTR module_name,
179                           PIMAGE_THUNK_DATA name_table, PIMAGE_THUNK_DATA iat,
180                           PVOID cookie) const;
181 
182 
183   // Enumerates PE delay imports.
184   // cookie is a generic cookie to pass to the callback.
185   // Returns true on success.
186   bool EnumAllDelayImports(EnumImportsFunction callback, PVOID cookie) const;
187 
188   // Enumerates PE delay import blocks.
189   // cookie is a generic cookie to pass to the callback.
190   // Returns true on success.
191   bool EnumDelayImportChunks(EnumDelayImportChunksFunction callback,
192                              PVOID cookie) const;
193 
194   // Enumerates imports from a single PE delay import block.
195   // cookie is a generic cookie to pass to the callback.
196   // Returns true on success.
197   bool EnumOneDelayImportChunk(EnumImportsFunction callback,
198                                PImgDelayDescr delay_descriptor,
199                                LPCSTR module_name,
200                                PIMAGE_THUNK_DATA name_table,
201                                PIMAGE_THUNK_DATA iat,
202                                PIMAGE_THUNK_DATA bound_iat,
203                                PIMAGE_THUNK_DATA unload_iat,
204                                PVOID cookie) const;
205 
206   // Enumerates PE relocation entries.
207   // cookie is a generic cookie to pass to the callback.
208   // Returns true on success.
209   bool EnumRelocs(EnumRelocsFunction callback, PVOID cookie) const;
210 
211   // Verifies the magic values on the PE file.
212   // Returns true if all values are correct.
213   bool VerifyMagic() const;
214 
215   // Converts an rva value to the appropriate address.
216   virtual PVOID RVAToAddr(DWORD rva) const;
217 
218   // Converts an rva value to an offset on disk.
219   // Returns true on success.
220   bool ImageRVAToOnDiskOffset(DWORD rva, DWORD *on_disk_offset) const;
221 
222   // Converts an address to an offset on disk.
223   // Returns true on success.
224   bool ImageAddrToOnDiskOffset(LPVOID address, DWORD *on_disk_offset) const;
225 
226  private:
227   HMODULE module_;
228 };
229 
230 // This class is an extension to the PEImage class that allows working with PE
231 // files mapped as data instead of as image file.
232 class PEImageAsData : public PEImage {
233  public:
PEImageAsData(HMODULE hModule)234   explicit PEImageAsData(HMODULE hModule) : PEImage(hModule) {}
235 
236   virtual PVOID RVAToAddr(DWORD rva) const;
237 };
238 
IsOrdinal(LPCSTR name)239 inline bool PEImage::IsOrdinal(LPCSTR name) {
240 #pragma warning(push)
241 #pragma warning(disable: 4311)
242   // This cast generates a warning because it is 32 bit specific.
243   return reinterpret_cast<DWORD>(name) <= 0xFFFF;
244 #pragma warning(pop)
245 }
246 
ToOrdinal(LPCSTR name)247 inline WORD PEImage::ToOrdinal(LPCSTR name) {
248   return reinterpret_cast<WORD>(name);
249 }
250 
module()251 inline HMODULE PEImage::module() const {
252   return module_;
253 }
254 
GetFirstImportChunk()255 inline PIMAGE_IMPORT_DESCRIPTOR PEImage::GetFirstImportChunk() const {
256   return reinterpret_cast<PIMAGE_IMPORT_DESCRIPTOR>(
257              GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_IMPORT));
258 }
259 
GetExportDirectory()260 inline PIMAGE_EXPORT_DIRECTORY PEImage::GetExportDirectory() const {
261   return reinterpret_cast<PIMAGE_EXPORT_DIRECTORY>(
262              GetImageDirectoryEntryAddr(IMAGE_DIRECTORY_ENTRY_EXPORT));
263 }
264 
265 }  // namespace win
266 }  // namespace base
267 
268 #endif  // BASE_WIN_PE_IMAGE_H_
269