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.
5 #include "sandbox/src/sandbox_utils.h"
9 #include "base/logging.h"
10 #include "base/win/windows_version.h"
11 #include "sandbox/src/internal_types.h"
12 #include "sandbox/src/nt_internals.h"
16 bool GetModuleHandleHelper(DWORD flags
, const wchar_t* module_name
,
20 HMODULE kernel32_base
= ::GetModuleHandle(kKerneldllName
);
26 GetModuleHandleExFunction get_module_handle_ex
= reinterpret_cast<
27 GetModuleHandleExFunction
>(::GetProcAddress(kernel32_base
,
28 "GetModuleHandleExW"));
29 if (get_module_handle_ex
) {
30 BOOL ret
= get_module_handle_ex(flags
, module_name
, module
);
31 return (ret
? true : false);
35 *module
= ::LoadLibrary(module_name
);
36 } else if (flags
& GET_MODULE_HANDLE_EX_FLAG_PIN
) {
39 } else if (!(flags
& GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
)) {
40 DCHECK((flags
& GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
) ==
41 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
);
43 *module
= ::GetModuleHandle(module_name
);
45 DCHECK((flags
& (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
|
46 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
)) ==
47 (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
|
48 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
));
50 MEMORY_BASIC_INFORMATION info
= {0};
51 size_t returned
= VirtualQuery(module_name
, &info
, sizeof(info
));
52 if (sizeof(info
) != returned
)
54 *module
= reinterpret_cast<HMODULE
>(info
.AllocationBase
);
59 bool IsXPSP2OrLater() {
60 base::win::Version version
= base::win::GetVersion();
61 return (version
> base::win::VERSION_XP
) ||
62 ((version
== base::win::VERSION_XP
) &&
63 (base::win::OSInfo::GetInstance()->service_pack().major
>= 2));
66 void InitObjectAttribs(const std::wstring
& name
, ULONG attributes
, HANDLE root
,
67 OBJECT_ATTRIBUTES
* obj_attr
, UNICODE_STRING
* uni_name
) {
68 static RtlInitUnicodeStringFunction RtlInitUnicodeString
;
69 if (!RtlInitUnicodeString
) {
70 HMODULE ntdll
= ::GetModuleHandle(kNtdllName
);
71 RtlInitUnicodeString
= reinterpret_cast<RtlInitUnicodeStringFunction
>(
72 GetProcAddress(ntdll
, "RtlInitUnicodeString"));
73 DCHECK(RtlInitUnicodeString
);
75 RtlInitUnicodeString(uni_name
, name
.c_str());
76 InitializeObjectAttributes(obj_attr
, uni_name
, attributes
, root
, NULL
);
79 }; // namespace sandbox