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