iat_patch_function.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. #ifndef BASE_WIN_IAT_PATCH_FUNCTION_H_
  5. #define BASE_WIN_IAT_PATCH_FUNCTION_H_
  6. #include <windows.h>
  7. #include "base/base_export.h"
  8. #include "base/macros.h"
  9. namespace base {
  10. namespace win {
  11. // A class that encapsulates Import Address Table patching helpers and restores
  12. // the original function in the destructor.
  13. //
  14. // It will intercept functions for a specific DLL imported from another DLL.
  15. // This is the case when, for example, we want to intercept
  16. // CertDuplicateCertificateContext function (exported from crypt32.dll) called
  17. // by wininet.dll.
  18. class BASE_EXPORT IATPatchFunction {
  19. public:
  20. IATPatchFunction();
  21. ~IATPatchFunction();
  22. // Intercept a function in an import table of a specific
  23. // module. Save the original function and the import
  24. // table address. These values will be used later
  25. // during Unpatch
  26. //
  27. // Arguments:
  28. // module Module to be intercepted
  29. // imported_from_module Module that exports the 'function_name'
  30. // function_name Name of the API to be intercepted
  31. //
  32. // Returns: Windows error code (winerror.h). NO_ERROR if successful
  33. //
  34. // Note: Patching a function will make the IAT patch take some "ownership" on
  35. // |module|. It will LoadLibrary(module) to keep the DLL alive until a call
  36. // to Unpatch(), which will call FreeLibrary() and allow the module to be
  37. // unloaded. The idea is to help prevent the DLL from going away while a
  38. // patch is still active.
  39. DWORD Patch(const wchar_t* module,
  40. const char* imported_from_module,
  41. const char* function_name,
  42. void* new_function);
  43. // Same as Patch(), but uses a handle to a |module| instead of the DLL name.
  44. DWORD PatchFromModule(HMODULE module,
  45. const char* imported_from_module,
  46. const char* function_name,
  47. void* new_function);
  48. // Unpatch the IAT entry using internally saved original
  49. // function.
  50. //
  51. // Returns: Windows error code (winerror.h). NO_ERROR if successful
  52. DWORD Unpatch();
  53. bool is_patched() const { return (nullptr != intercept_function_); }
  54. void* original_function() const;
  55. private:
  56. HMODULE module_handle_ = nullptr;
  57. void* intercept_function_ = nullptr;
  58. void* original_function_ = nullptr;
  59. IMAGE_THUNK_DATA* iat_thunk_ = nullptr;
  60. DISALLOW_COPY_AND_ASSIGN(IATPatchFunction);
  61. };
  62. } // namespace win
  63. } // namespace base
  64. #endif // BASE_WIN_IAT_PATCH_FUNCTION_H_