|
1 // Common/MemoryLock.cpp |
|
2 |
|
3 #include "StdAfx.h" |
|
4 |
|
5 namespace NWindows { |
|
6 namespace NSecurity { |
|
7 |
|
8 #ifndef _UNICODE |
|
9 typedef BOOL (WINAPI * OpenProcessTokenP)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); |
|
10 typedef BOOL (WINAPI * LookupPrivilegeValueP)(LPCTSTR lpSystemName, LPCTSTR lpName, PLUID lpLuid); |
|
11 typedef BOOL (WINAPI * AdjustTokenPrivilegesP)(HANDLE TokenHandle, BOOL DisableAllPrivileges, |
|
12 PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState,PDWORD ReturnLength); |
|
13 #endif |
|
14 |
|
15 #ifdef _UNICODE |
|
16 bool EnableLockMemoryPrivilege( |
|
17 #else |
|
18 static bool EnableLockMemoryPrivilege2(HMODULE hModule, |
|
19 #endif |
|
20 bool enable) |
|
21 { |
|
22 #ifndef _UNICODE |
|
23 if (hModule == NULL) |
|
24 return false; |
|
25 OpenProcessTokenP openProcessToken = (OpenProcessTokenP)GetProcAddress(hModule, "OpenProcessToken"); |
|
26 LookupPrivilegeValueP lookupPrivilegeValue = (LookupPrivilegeValueP)GetProcAddress(hModule, "LookupPrivilegeValueA" ); |
|
27 AdjustTokenPrivilegesP adjustTokenPrivileges = (AdjustTokenPrivilegesP)GetProcAddress(hModule, "AdjustTokenPrivileges"); |
|
28 if (openProcessToken == NULL || adjustTokenPrivileges == NULL || lookupPrivilegeValue == NULL) |
|
29 return false; |
|
30 #endif |
|
31 |
|
32 HANDLE token; |
|
33 if (! |
|
34 #ifdef _UNICODE |
|
35 ::OpenProcessToken |
|
36 #else |
|
37 openProcessToken |
|
38 #endif |
|
39 (::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token)) |
|
40 return false; |
|
41 TOKEN_PRIVILEGES tp; |
|
42 bool res = false; |
|
43 if ( |
|
44 #ifdef _UNICODE |
|
45 ::LookupPrivilegeValue |
|
46 #else |
|
47 lookupPrivilegeValue |
|
48 #endif |
|
49 (NULL, SE_LOCK_MEMORY_NAME, &(tp.Privileges[0].Luid))) |
|
50 { |
|
51 tp.PrivilegeCount = 1; |
|
52 tp.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED: 0; |
|
53 if ( |
|
54 #ifdef _UNICODE |
|
55 ::AdjustTokenPrivileges |
|
56 #else |
|
57 adjustTokenPrivileges |
|
58 #endif |
|
59 (token, FALSE, &tp, 0, NULL, NULL)) |
|
60 res = (GetLastError() == ERROR_SUCCESS); |
|
61 } |
|
62 ::CloseHandle(token); |
|
63 return res; |
|
64 } |
|
65 |
|
66 #ifndef _UNICODE |
|
67 bool EnableLockMemoryPrivilege(bool enable) |
|
68 { |
|
69 HMODULE hModule = LoadLibrary(TEXT("Advapi32.dll")); |
|
70 if(hModule == NULL) |
|
71 return false; |
|
72 bool res = EnableLockMemoryPrivilege2(hModule, enable); |
|
73 ::FreeLibrary(hModule); |
|
74 return res; |
|
75 } |
|
76 #endif |
|
77 |
|
78 }} |