OSDN Git Service

Added get_file_version() function + workaround to make get_real_os_version() give...
[mutilities/MUtilities.git] / src / OSSupport_Win32.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2015 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Lesser General Public License for more details.
14 //
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18 //
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
21
22 //Win32 API
23 #define WIN32_LEAN_AND_MEAN 1
24 #include <Windows.h>
25 #include <Psapi.h>
26 #include <Sensapi.h>
27 #include <Shellapi.h>
28 #include <PowrProf.h>
29 #include <Mmsystem.h>
30 #include <ShlObj.h>
31
32 //Internal
33 #include <MUtils/Global.h>
34 #include <MUtils/OSSupport.h>
35 #include <MUtils/GUI.h>
36 #include "CriticalSection_Win32.h"
37
38 //Qt
39 #include <QMap>
40 #include <QReadWriteLock>
41 #include <QLibrary>
42 #include <QDir>
43 #include <QWidget>
44 #include <QProcess>
45
46 //Main thread ID
47 static const DWORD g_main_thread_id = GetCurrentThreadId();
48
49 ///////////////////////////////////////////////////////////////////////////////
50 // SYSTEM MESSAGE
51 ///////////////////////////////////////////////////////////////////////////////
52
53 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
54
55 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
56 {
57         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
58 }
59
60 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
61 {
62         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
63 }
64
65 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
66 {
67         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
68 }
69
70 ///////////////////////////////////////////////////////////////////////////////
71 // FETCH CLI ARGUMENTS
72 ///////////////////////////////////////////////////////////////////////////////
73
74 static QReadWriteLock                          g_arguments_lock;
75 static QScopedPointer<MUtils::OS::ArgumentMap> g_arguments_list;
76
77 const MUtils::OS::ArgumentMap &MUtils::OS::arguments(void)
78 {
79         QReadLocker readLock(&g_arguments_lock);
80
81         //Already initialized?
82         if(!g_arguments_list.isNull())
83         {
84                 return (*(g_arguments_list.data()));
85         }
86
87         readLock.unlock();
88         QWriteLocker writeLock(&g_arguments_lock);
89
90         //Still not initialized?
91         if(!g_arguments_list.isNull())
92         {
93                 return (*(g_arguments_list.data()));
94         }
95
96         g_arguments_list.reset(new ArgumentMap());
97         int nArgs = 0;
98         LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
99
100         if(NULL != szArglist)
101         {
102                 const QChar separator = QLatin1Char('=');
103                 const QString argPrefix = QLatin1String("--");
104                 for(int i = 0; i < nArgs; i++)
105                 {
106                         const QString argStr = MUTILS_QSTR(szArglist[i]).trimmed();
107                         if(argStr.startsWith(argPrefix))
108                         {
109                                 const QString argData = argStr.mid(2).trimmed();
110                                 if(argData.length() > 0)
111                                 {
112                                         const int separatorIndex = argData.indexOf(separator);
113                                         if(separatorIndex > 0)
114                                         {
115                                                 const QString argKey = argData.left(separatorIndex).trimmed();
116                                                 const QString argVal = argData.mid(separatorIndex + 1).trimmed();
117                                                 g_arguments_list->insertMulti(argKey.toLower(), argVal);
118                                         }
119                                         else
120                                         {
121                                                 g_arguments_list->insertMulti(argData.toLower(), QString());
122                                         }
123                                 }
124                         }
125                 }
126                 LocalFree(szArglist);
127         }
128         else
129         {
130                 qWarning("CommandLineToArgvW() has failed !!!");
131         }
132
133         return (*(g_arguments_list.data()));
134 }
135
136 ///////////////////////////////////////////////////////////////////////////////
137 // COPY FILE
138 ///////////////////////////////////////////////////////////////////////////////
139
140 typedef struct _progress_callback_data_t
141 {
142         MUtils::OS::progress_callback_t callback_function;
143         void *user_data;
144 }
145 progress_callback_data_t;
146
147 static DWORD __stdcall copy_file_progress(LARGE_INTEGER TotalFileSize, LARGE_INTEGER TotalBytesTransferred, LARGE_INTEGER StreamSize, LARGE_INTEGER StreamBytesTransferred, DWORD dwStreamNumber, DWORD dwCallbackReason, HANDLE hSourceFile, HANDLE hDestinationFile, LPVOID lpData)
148 {
149         if(const progress_callback_data_t *data = (progress_callback_data_t*) lpData)
150         {
151                 const double progress = qBound(0.0, double(TotalBytesTransferred.QuadPart) / double(TotalFileSize.QuadPart), 1.0);
152                 return data->callback_function(progress, data->user_data) ? PROGRESS_CONTINUE : PROGRESS_CANCEL;
153         }
154         return PROGRESS_CONTINUE;
155 }
156
157 MUTILS_API bool MUtils::OS::copy_file(const QString &sourcePath, const QString &outputPath, const bool &overwrite, const progress_callback_t callback, void *const userData)
158 {
159         progress_callback_data_t callback_data = { callback, userData };
160         BOOL cancel = FALSE;
161         const BOOL result = CopyFileExW(MUTILS_WCHR(QDir::toNativeSeparators(sourcePath)), MUTILS_WCHR(QDir::toNativeSeparators(outputPath)), ((callback_data.callback_function) ? copy_file_progress : NULL), ((callback_data.callback_function) ? &callback_data : NULL), &cancel, (overwrite ? 0 : COPY_FILE_FAIL_IF_EXISTS));
162
163         if(result == FALSE)
164         {
165                 const DWORD errorCode = GetLastError();
166                 if(errorCode != ERROR_REQUEST_ABORTED)
167                 {
168                         qWarning("CopyFile() failed with error code 0x%08X!", errorCode);
169                 }
170                 else
171                 {
172                         qWarning("CopyFile() operation was abroted by user!");
173                 }
174         }
175
176         return (result != FALSE);
177 }
178
179 ///////////////////////////////////////////////////////////////////////////////
180 // GET FILE VERSION
181 ///////////////////////////////////////////////////////////////////////////////
182
183 static bool get_file_version_helper(const QString fileName, PVOID buffer, const size_t &size, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
184 {
185         if(!GetFileVersionInfo(MUTILS_WCHR(fileName), 0, size, buffer))
186         {
187                 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
188                 return false;
189         }
190
191         VS_FIXEDFILEINFO *verInfo;
192         UINT verInfoLen;
193         if(!VerQueryValue(buffer, L"\\", (LPVOID*)(&verInfo), &verInfoLen))
194         {
195                 qWarning("VerQueryValue() has failed, file version cannot be determined!");
196                 return false;
197         }
198
199         if(major) *major = quint16((verInfo->dwFileVersionMS >> 16) & 0x0000FFFF);
200         if(minor) *minor = quint16((verInfo->dwFileVersionMS)       & 0x0000FFFF);
201         if(patch) *patch = quint16((verInfo->dwFileVersionLS >> 16) & 0x0000FFFF);
202         if(build) *build = quint16((verInfo->dwFileVersionLS)       & 0x0000FFFF);
203
204         return true;
205 }
206
207 bool MUtils::OS::get_file_version(const QString fileName, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
208 {
209         if(major) *major = 0U; if(minor) *minor = 0U;
210         if(patch) *patch = 0U; if(build) *build = 0U;
211
212         const DWORD size = GetFileVersionInfoSize(MUTILS_WCHR(fileName), NULL);
213         if(size < 1)
214         {
215                 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
216                 return false;
217         }
218         
219         PVOID buffer = _malloca(size);
220         if(!buffer)
221         {
222                 qWarning("Memory allocation has failed!");
223                 return false;
224         }
225
226         const bool success = get_file_version_helper(fileName, buffer, size, major, minor, patch, build);
227
228         _freea(buffer);
229         return success;
230 }
231
232 ///////////////////////////////////////////////////////////////////////////////
233 // OS VERSION DETECTION
234 ///////////////////////////////////////////////////////////////////////////////
235
236 static bool g_os_version_initialized = false;
237 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
238 static QReadWriteLock g_os_version_lock;
239
240 //Maps marketing names to the actual Windows NT versions
241 static const struct
242 {
243         MUtils::OS::Version::os_version_t version;
244         const char friendlyName[64];
245 }
246 g_os_version_lut[] =
247 {
248         { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000"                                  },        //2000
249         { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" },        //XP
250         { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64"         },        //XP_x64
251         { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008"          },        //Vista
252         { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2"           },        //7
253         { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012"              },        //8
254         { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2"         },        //8.1
255         { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2014 (Preview)"   },        //10
256         { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
257 };
258
259 //OS version data dtructures
260 namespace MUtils
261 {
262         namespace OS
263         {
264                 namespace Version
265                 {
266                         //Comparision operators for os_version_t
267                         bool os_version_t::operator== (const os_version_t &rhs) const { return (type == rhs.type) && (versionMajor == rhs.versionMajor) && ((versionMinor == rhs.versionMinor)); }
268                         bool os_version_t::operator!= (const os_version_t &rhs) const { return (type != rhs.type) || (versionMajor != rhs.versionMajor) || ((versionMinor != rhs.versionMinor)); }
269                         bool os_version_t::operator>  (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >  rhs.versionMinor))); }
270                         bool os_version_t::operator>= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >= rhs.versionMinor))); }
271                         bool os_version_t::operator<  (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <  rhs.versionMinor))); }
272                         bool os_version_t::operator<= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <= rhs.versionMinor))); }
273
274                         //Known Windows NT versions
275                         const os_version_t WINDOWS_WIN2K = { OS_WINDOWS,  5, 0 };       // 2000
276                         const os_version_t WINDOWS_WINXP = { OS_WINDOWS,  5, 1 };       // XP
277                         const os_version_t WINDOWS_XPX64 = { OS_WINDOWS,  5, 2 };       // XP_x64
278                         const os_version_t WINDOWS_VISTA = { OS_WINDOWS,  6, 0 };       // Vista
279                         const os_version_t WINDOWS_WIN70 = { OS_WINDOWS,  6, 1 };       // 7
280                         const os_version_t WINDOWS_WIN80 = { OS_WINDOWS,  6, 2 };       // 8
281                         const os_version_t WINDOWS_WIN81 = { OS_WINDOWS,  6, 3 };       // 8.1
282                         const os_version_t WINDOWS_WN100 = { OS_WINDOWS, 10, 0 };       // 10
283
284                         //Unknown OS
285                         const os_version_t UNKNOWN_OPSYS = { OS_UNKNOWN, 0, 0 };        // N/A
286                 }
287         }
288 }
289
290 static bool verify_os_version(const DWORD major, const DWORD minor)
291 {
292         OSVERSIONINFOEXW osvi;
293         DWORDLONG dwlConditionMask = 0;
294
295         //Initialize the OSVERSIONINFOEX structure
296         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
297         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
298         osvi.dwMajorVersion = major;
299         osvi.dwMinorVersion = minor;
300         osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
301
302         //Initialize the condition mask
303         VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
304         VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
305         VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID,   VER_EQUAL);
306
307         // Perform the test
308         const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
309
310         //Error checking
311         if(!ret)
312         {
313                 if(GetLastError() != ERROR_OLD_WIN_VERSION)
314                 {
315                         qWarning("VerifyVersionInfo() system call has failed!");
316                 }
317         }
318
319         return (ret != FALSE);
320 }
321
322 static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
323 {
324         *major = *minor = 0;
325         *pbOverride = false;
326         
327         //Initialize local variables
328         OSVERSIONINFOEXW osvi;
329         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
330         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
331
332         //Try GetVersionEx() first
333         if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
334         {
335                 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
336                 return false;
337         }
338
339         //Make sure we are running on NT
340         if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
341         {
342                 *major = osvi.dwMajorVersion;
343                 *minor = osvi.dwMinorVersion;
344         }
345         else
346         {
347                 qWarning("Not running on Windows NT, unsupported operating system!");
348                 return false;
349         }
350
351         //Determine the real *major* version first
352         forever
353         {
354                 const DWORD nextMajor = (*major) + 1;
355                 if(verify_os_version(nextMajor, 0))
356                 {
357                         *pbOverride = true;
358                         *major = nextMajor;
359                         *minor = 0;
360                         continue;
361                 }
362                 break;
363         }
364
365         //Now also determine the real *minor* version
366         forever
367         {
368                 const DWORD nextMinor = (*minor) + 1;
369                 if(verify_os_version((*major), nextMinor))
370                 {
371                         *pbOverride = true;
372                         *minor = nextMinor;
373                         continue;
374                 }
375                 break;
376         }
377
378         //Workaround for the mess that is sometimes referred to as "Windows 10"
379         if(((*major) > 6) || (((*major) == 6) && ((*minor) >= 2)))
380         {
381                 quint16 kernel32_major, kernel32_minor;
382                 if(MUtils::OS::get_file_version(QLatin1String("kernel32"), &kernel32_major, &kernel32_minor))
383                 {
384                         if((kernel32_major > (*major)) || ((kernel32_major == (*major)) && (kernel32_minor > (*minor))))
385                         {
386                                 *major = kernel32_major;
387                                 *minor = kernel32_minor;
388                                 *pbOverride = true;
389                         }
390                 }
391         }
392
393         return true;
394 }
395
396 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
397 {
398         QReadLocker readLock(&g_os_version_lock);
399
400         //Already initialized?
401         if(g_os_version_initialized)
402         {
403                 return g_os_version_info;
404         }
405         
406         readLock.unlock();
407         QWriteLocker writeLock(&g_os_version_lock);
408
409         //Initialized now?
410         if(g_os_version_initialized)
411         {
412                 return g_os_version_info;
413         }
414
415         //Detect OS version
416         unsigned int major, minor; bool overrideFlg;
417         if(get_real_os_version(&major, &minor, &overrideFlg))
418         {
419                 g_os_version_info.type = Version::OS_WINDOWS;
420                 g_os_version_info.versionMajor = major;
421                 g_os_version_info.versionMinor = minor;
422                 g_os_version_info.overrideFlag = overrideFlg;
423         }
424         else
425         {
426                 qWarning("Failed to determin the operating system version!");
427         }
428
429         //Completed
430         g_os_version_initialized = true;
431         return g_os_version_info;
432 }
433
434 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
435 {
436         for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
437         {
438                 if(os_version == g_os_version_lut[i].version)
439                 {
440                         return g_os_version_lut[i].friendlyName;
441                 }
442         }
443
444         return NULL;
445 }
446
447 ///////////////////////////////////////////////////////////////////////////////
448 // WINE DETECTION
449 ///////////////////////////////////////////////////////////////////////////////
450
451 static bool g_wine_deteced = false;
452 static bool g_wine_initialized = false;
453 static QReadWriteLock g_wine_lock;
454
455 static const bool detect_wine(void)
456 {
457         bool is_wine = false;
458         
459         QLibrary ntdll("ntdll.dll");
460         if(ntdll.load())
461         {
462                 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) is_wine = true;
463                 if(ntdll.resolve("wine_get_version")          != NULL) is_wine = true;
464                 ntdll.unload();
465         }
466
467         return is_wine;
468 }
469
470 const bool &MUtils::OS::running_on_wine(void)
471 {
472         QReadLocker readLock(&g_wine_lock);
473
474         //Already initialized?
475         if(g_wine_initialized)
476         {
477                 return g_wine_deteced;
478         }
479
480         readLock.unlock();
481         QWriteLocker writeLock(&g_wine_lock);
482
483         //Initialized now?
484         if(g_wine_initialized)
485         {
486                 return g_wine_deteced;
487         }
488
489         //Try to detect Wine
490         g_wine_deteced = detect_wine();
491         g_wine_initialized = true;
492
493         return g_wine_deteced;
494 }
495
496 ///////////////////////////////////////////////////////////////////////////////
497 // KNWON FOLDERS
498 ///////////////////////////////////////////////////////////////////////////////
499
500 typedef QMap<size_t, QString> KFMap;
501 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
502 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
503
504 static QScopedPointer<KFMap>  g_known_folders_map;
505 static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath;
506 static SHGetFolderPath_t      g_known_folders_fpGetFolderPath;
507 static QReadWriteLock         g_known_folders_lock;
508
509 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
510 {
511         typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
512         
513         struct
514         {
515                 const int csidl;
516                 const GUID guid;
517         }
518         static s_folders[] =
519         {
520                 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} },  //CSIDL_LOCAL_APPDATA
521                 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} },  //CSIDL_PROGRAM_FILES
522                 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} },  //CSIDL_WINDOWS_FOLDER
523                 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} },  //CSIDL_SYSTEM_FOLDER
524         };
525
526         size_t folderId = size_t(-1);
527
528         switch(folder_id)
529         {
530                 case FOLDER_LOCALAPPDATA: folderId = 0; break;
531                 case FOLDER_PROGRAMFILES: folderId = 1; break;
532                 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
533                 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
534         }
535
536         if(folderId == size_t(-1))
537         {
538                 qWarning("Invalid 'known' folder was requested!");
539                 return *reinterpret_cast<QString*>(NULL);
540         }
541
542         QReadLocker readLock(&g_known_folders_lock);
543
544         //Already in cache?
545         if(!g_known_folders_map.isNull())
546         {
547                 if(g_known_folders_map->contains(folderId))
548                 {
549                         return g_known_folders_map->operator[](folderId);
550                 }
551         }
552
553         //Obtain write lock to initialize
554         readLock.unlock();
555         QWriteLocker writeLock(&g_known_folders_lock);
556
557         //Still not in cache?
558         if(!g_known_folders_map.isNull())
559         {
560                 if(g_known_folders_map->contains(folderId))
561                 {
562                         return g_known_folders_map->operator[](folderId);
563                 }
564         }
565
566         //Initialize on first call
567         if(g_known_folders_map.isNull())
568         {
569                 QLibrary shell32("shell32.dll");
570                 if(shell32.load())
571                 {
572                         g_known_folders_fpGetFolderPath =      (SHGetFolderPath_t)      shell32.resolve("SHGetFolderPathW");
573                         g_known_folders_fpGetKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
574                 }
575                 g_known_folders_map.reset(new QMap<size_t, QString>());
576         }
577
578         QString folderPath;
579
580         //Now try to get the folder path!
581         if(g_known_folders_fpGetKnownFolderPath)
582         {
583                 WCHAR *path = NULL;
584                 if(g_known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
585                 {
586                         //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
587                         QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
588                         if(folderTemp.exists())
589                         {
590                                 folderPath = folderTemp.canonicalPath();
591                         }
592                         CoTaskMemFree(path);
593                 }
594         }
595         else if(g_known_folders_fpGetFolderPath)
596         {
597                 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
598                 if(g_known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
599                 {
600                         //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
601                         QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
602                         if(folderTemp.exists())
603                         {
604                                 folderPath = folderTemp.canonicalPath();
605                         }
606                 }
607         }
608
609         //Update cache
610         g_known_folders_map->insert(folderId, folderPath);
611         return g_known_folders_map->operator[](folderId);
612 }
613
614 ///////////////////////////////////////////////////////////////////////////////
615 // CURRENT DATA & TIME
616 ///////////////////////////////////////////////////////////////////////////////
617
618 QDate MUtils::OS::current_date(void)
619 {
620         const DWORD MAX_PROC = 1024;
621         QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
622         DWORD bytesReturned = 0;
623         
624         if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
625         {
626                 return QDate::currentDate();
627         }
628
629         const DWORD procCount = bytesReturned / sizeof(DWORD);
630         ULARGE_INTEGER lastStartTime;
631         memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
632
633         for(DWORD i = 0; i < procCount; i++)
634         {
635                 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
636                 {
637                         FILETIME processTime[4];
638                         if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
639                         {
640                                 ULARGE_INTEGER timeCreation;
641                                 timeCreation.LowPart  = processTime[0].dwLowDateTime;
642                                 timeCreation.HighPart = processTime[0].dwHighDateTime;
643                                 if(timeCreation.QuadPart > lastStartTime.QuadPart)
644                                 {
645                                         lastStartTime.QuadPart = timeCreation.QuadPart;
646                                 }
647                         }
648                         CloseHandle(hProc);
649                 }
650         }
651         
652         FILETIME lastStartTime_fileTime;
653         lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
654         lastStartTime_fileTime.dwLowDateTime  = lastStartTime.LowPart;
655
656         FILETIME lastStartTime_localTime;
657         if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
658         {
659                 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
660         }
661         
662         SYSTEMTIME lastStartTime_system;
663         if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
664         {
665                 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
666                 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
667         }
668
669         const QDate currentDate = QDate::currentDate();
670         const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
671         return (currentDate >= processDate) ? currentDate : processDate;
672 }
673
674 quint64 MUtils::OS::current_file_time(void)
675 {
676         FILETIME fileTime;
677         GetSystemTimeAsFileTime(&fileTime);
678
679         ULARGE_INTEGER temp;
680         temp.HighPart = fileTime.dwHighDateTime;
681         temp.LowPart = fileTime.dwLowDateTime;
682
683         return temp.QuadPart;
684 }
685
686 ///////////////////////////////////////////////////////////////////////////////
687 // PROCESS ELEVATION
688 ///////////////////////////////////////////////////////////////////////////////
689
690 static bool user_is_admin_helper(void)
691 {
692         HANDLE hToken = NULL;
693         if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
694         {
695                 return false;
696         }
697
698         DWORD dwSize = 0;
699         if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
700         {
701                 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
702                 {
703                         CloseHandle(hToken);
704                         return false;
705                 }
706         }
707
708         PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
709         if(!lpGroups)
710         {
711                 CloseHandle(hToken);
712                 return false;
713         }
714
715         if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
716         {
717                 free(lpGroups);
718                 CloseHandle(hToken);
719                 return false;
720         }
721
722         PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
723         if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
724         {
725                 free(lpGroups);
726                 CloseHandle(hToken);
727                 return false;
728         }
729
730         bool bResult = false;
731         for(DWORD i = 0; i < lpGroups->GroupCount; i++)
732         {
733                 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
734                 {
735                         bResult = true;
736                         break;
737                 }
738         }
739
740         FreeSid(lpSid);
741         free(lpGroups);
742         CloseHandle(hToken);
743         return bResult;
744 }
745
746 bool MUtils::OS::is_elevated(bool *bIsUacEnabled)
747 {
748         if(bIsUacEnabled)
749         {
750                 *bIsUacEnabled = false;
751         }
752
753         bool bIsProcessElevated = false;
754         HANDLE hToken = NULL;
755         
756         if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
757         {
758                 TOKEN_ELEVATION_TYPE tokenElevationType;
759                 DWORD returnLength;
760                 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
761                 {
762                         if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
763                         {
764                                 switch(tokenElevationType)
765                                 {
766                                 case TokenElevationTypeDefault:
767                                         qDebug("Process token elevation type: Default -> UAC is disabled.\n");
768                                         break;
769                                 case TokenElevationTypeFull:
770                                         qWarning("Process token elevation type: Full -> potential security risk!\n");
771                                         bIsProcessElevated = true;
772                                         if(bIsUacEnabled) *bIsUacEnabled = true;
773                                         break;
774                                 case TokenElevationTypeLimited:
775                                         qDebug("Process token elevation type: Limited -> not elevated.\n");
776                                         if(bIsUacEnabled) *bIsUacEnabled = true;
777                                         break;
778                                 default:
779                                         qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
780                                         break;
781                                 }
782                         }
783                         else
784                         {
785                                 qWarning("GetTokenInformation() return an unexpected size!");
786                         }
787                 }
788                 CloseHandle(hToken);
789         }
790         else
791         {
792                 qWarning("Failed to open process token!");
793         }
794
795         return bIsProcessElevated;
796 }
797
798 bool MUtils::OS::user_is_admin(void)
799 {
800         bool isAdmin = false;
801
802         //Check for process elevation and UAC support first!
803         if(MUtils::OS::is_elevated(&isAdmin))
804         {
805                 qWarning("Process is elevated -> user is admin!");
806                 return true;
807         }
808         
809         //If not elevated and UAC is not available -> user must be in admin group!
810         if(!isAdmin)
811         {
812                 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
813                 isAdmin = user_is_admin_helper();
814         }
815
816         return isAdmin;
817 }
818
819 ///////////////////////////////////////////////////////////////////////////////
820 // NETWORK STATE
821 ///////////////////////////////////////////////////////////////////////////////
822
823 int MUtils::OS::network_status(void)
824 {
825         DWORD dwFlags;
826         const BOOL ret = IsNetworkAlive(&dwFlags);
827         if(GetLastError() == 0)
828         {
829                 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
830         }
831         return NETWORK_TYPE_ERR;
832 }
833
834 ///////////////////////////////////////////////////////////////////////////////
835 // MESSAGE HANDLER
836 ///////////////////////////////////////////////////////////////////////////////
837
838 bool MUtils::OS::handle_os_message(const void *const message, long *result)
839 {
840         const MSG *const msg = reinterpret_cast<const MSG*>(message);
841
842         switch(msg->message)
843         {
844         case WM_QUERYENDSESSION:
845                 qWarning("WM_QUERYENDSESSION message received!");
846                 *result = MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION, false) ? TRUE : FALSE;
847                 return true;
848         case WM_ENDSESSION:
849                 qWarning("WM_ENDSESSION message received!");
850                 if(msg->wParam == TRUE)
851                 {
852                         MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION, false);
853                         MUtils::GUI::force_quit();
854                         exit(1);
855                 }
856                 *result = 0;
857                 return true;
858         default:
859                 /*ignore this message and let Qt handle it*/
860                 return false;
861         }
862 }
863
864 ///////////////////////////////////////////////////////////////////////////////
865 // SLEEP
866 ///////////////////////////////////////////////////////////////////////////////
867
868 void MUtils::OS::sleep_ms(const size_t &duration)
869 {
870         Sleep((DWORD) duration);
871 }
872
873 ///////////////////////////////////////////////////////////////////////////////
874 // EXECUTABLE CHECK
875 ///////////////////////////////////////////////////////////////////////////////
876
877 bool MUtils::OS::is_executable_file(const QString &path)
878 {
879         bool bIsExecutable = false;
880         DWORD binaryType;
881         if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
882         {
883                 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
884         }
885         return bIsExecutable;
886 }
887
888 ///////////////////////////////////////////////////////////////////////////////
889 // HIBERNATION / SHUTDOWN
890 ///////////////////////////////////////////////////////////////////////////////
891
892 bool MUtils::OS::is_hibernation_supported(void)
893 {
894         bool hibernationSupported = false;
895
896         SYSTEM_POWER_CAPABILITIES pwrCaps;
897         SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
898         
899         if(GetPwrCapabilities(&pwrCaps))
900         {
901                 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
902         }
903
904         return hibernationSupported;
905 }
906
907 bool MUtils::OS::shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
908 {
909         HANDLE hToken = NULL;
910
911         if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
912         {
913                 TOKEN_PRIVILEGES privileges;
914                 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
915                 privileges.PrivilegeCount = 1;
916                 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
917                 
918                 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
919                 {
920                         if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
921                         {
922                                 if(hibernate)
923                                 {
924                                         if(SetSuspendState(TRUE, TRUE, TRUE))
925                                         {
926                                                 return true;
927                                         }
928                                 }
929                                 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
930                                 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
931                         }
932                 }
933         }
934         
935         return false;
936 }
937
938 ///////////////////////////////////////////////////////////////////////////////
939 // FREE DISKSPACE
940 ///////////////////////////////////////////////////////////////////////////////
941
942 bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace)
943 {
944         ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
945         if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
946         {
947                 freeSpace = freeBytesAvailable.QuadPart;
948                 return true;;
949         }
950
951         freeSpace = -1;
952         return false;
953 }
954
955 ///////////////////////////////////////////////////////////////////////////////
956 // SHELL OPEN
957 ///////////////////////////////////////////////////////////////////////////////
958
959 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString &parameters, const QString &directory, const bool explore)
960 {
961         return ((int) ShellExecuteW((parent ? parent->winId() : NULL), (explore ? L"explore" : L"open"), MUTILS_WCHR(url), ((!parameters.isEmpty()) ? MUTILS_WCHR(parameters) : NULL), ((!directory.isEmpty()) ? MUTILS_WCHR(directory) : NULL), SW_SHOW)) > 32;
962 }
963
964 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore)
965 {
966         return shell_open(parent, url, QString(), QString(), explore);
967 }
968
969 ///////////////////////////////////////////////////////////////////////////////
970 // OPEN MEDIA FILE
971 ///////////////////////////////////////////////////////////////////////////////
972
973 bool MUtils::OS::open_media_file(const QString &mediaFilePath)
974 {
975         const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
976         const static wchar_t *registryKeys[3] = 
977         {
978                 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
979                 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
980                 L"foobar2000"
981         };
982         const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
983         const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
984
985         for(size_t i = 0; i < 3; i++)
986         {
987                 for(size_t j = 0; j < 2; j++)
988                 {
989                         QString mplayerPath;
990                         HKEY registryKeyHandle = NULL;
991
992                         const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
993                         if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
994                         {
995                                 for(size_t k = 0; k < 2; k++)
996                                 {
997                                         wchar_t Buffer[4096];
998                                         DWORD BuffSize = sizeof(wchar_t*) * 4096;
999                                         DWORD DataType = REG_NONE;
1000                                         if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1001                                         {
1002                                                 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1003                                                 {
1004                                                         mplayerPath = MUTILS_QSTR(Buffer);
1005                                                         break;
1006                                                 }
1007                                         }
1008                                 }
1009                                 RegCloseKey(registryKeyHandle);
1010                         }
1011
1012                         if(!mplayerPath.isEmpty())
1013                         {
1014                                 QDir mplayerDir(mplayerPath);
1015                                 if(mplayerDir.exists())
1016                                 {
1017                                         for(size_t k = 0; k < 4; k++)
1018                                         {
1019                                                 if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
1020                                                 {
1021                                                         qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
1022                                                         QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1023                                                         return true;
1024                                                 }
1025                                         }
1026                                 }
1027                         }
1028                 }
1029         }
1030         return false;
1031 }
1032
1033 ///////////////////////////////////////////////////////////////////////////////
1034 // DEBUGGER CHECK
1035 ///////////////////////////////////////////////////////////////////////////////
1036
1037 static bool change_process_priority_helper(const HANDLE hProcess, const int priority)
1038 {
1039         bool ok = false;
1040
1041         switch(qBound(-2, priority, 2))
1042         {
1043         case 2:
1044                 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1045                 break;
1046         case 1:
1047                 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1048                 {
1049                         ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1050                 }
1051                 break;
1052         case 0:
1053                 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1054                 break;
1055         case -1:
1056                 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1057                 {
1058                         ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1059                 }
1060                 break;
1061         case -2:
1062                 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1063                 break;
1064         }
1065
1066         return ok;
1067 }
1068
1069 bool MUtils::OS::change_process_priority(const int priority)
1070 {
1071         return change_process_priority_helper(GetCurrentProcess(), priority);
1072 }
1073
1074 bool MUtils::OS::change_process_priority(const QProcess *proc, const int priority)
1075 {
1076         if(Q_PID qPid = proc->pid())
1077         {
1078                 return change_process_priority_helper(qPid->hProcess, priority);
1079         }
1080         else
1081         {
1082                 return false;
1083         }
1084 }
1085
1086 ///////////////////////////////////////////////////////////////////////////////
1087 // PROCESS ID
1088 ///////////////////////////////////////////////////////////////////////////////
1089
1090 quint32 MUtils::OS::process_id(const QProcess *const proc)
1091 {
1092         PROCESS_INFORMATION *procInf = proc->pid();
1093         return (procInf) ? procInf->dwProcessId : NULL;
1094 }
1095
1096 ///////////////////////////////////////////////////////////////////////////////
1097 // PROCESS SUSPEND/RESUME
1098 ///////////////////////////////////////////////////////////////////////////////
1099
1100 bool MUtils::OS::suspend_process(const QProcess *proc, const bool suspend)
1101 {
1102         if(Q_PID pid = proc->pid())
1103         {
1104                 if(suspend)
1105                 {
1106                         return (SuspendThread(pid->hThread) != ((DWORD) -1));
1107                 }
1108                 else
1109                 {
1110                         return (ResumeThread(pid->hThread)  != ((DWORD) -1));
1111                 }
1112         }
1113         else
1114         {
1115                 return false;
1116         }
1117 }
1118
1119 ///////////////////////////////////////////////////////////////////////////////
1120 // SYSTEM TIMER
1121 ///////////////////////////////////////////////////////////////////////////////
1122
1123 bool MUtils::OS::setup_timer_resolution(const quint32 &interval)
1124 {
1125         return timeBeginPeriod(interval) == TIMERR_NOERROR;
1126 }
1127
1128 bool MUtils::OS::reset_timer_resolution(const quint32 &interval)
1129 {
1130         return timeEndPeriod(interval) == TIMERR_NOERROR;
1131 }
1132
1133 ///////////////////////////////////////////////////////////////////////////////
1134 // CHECK KEY STATE
1135 ///////////////////////////////////////////////////////////////////////////////
1136
1137 bool MUtils::OS::check_key_state_esc(void)
1138 {
1139         return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1140 }
1141
1142 ///////////////////////////////////////////////////////////////////////////////
1143 // SHELL CHANGE NOTIFICATION
1144 ///////////////////////////////////////////////////////////////////////////////
1145
1146 void MUtils::OS::shell_change_notification(void)
1147 {
1148         SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
1149 }
1150
1151 ///////////////////////////////////////////////////////////////////////////////
1152 // WOW64 REDIRECTION
1153 ///////////////////////////////////////////////////////////////////////////////
1154
1155 typedef BOOL (_stdcall *Wow64DisableWow64FsRedirectionFun)(void *OldValue);
1156 typedef BOOL (_stdcall *Wow64RevertWow64FsRedirectionFun )(void *OldValue);
1157
1158 static QReadWriteLock                    g_wow64redir_lock;
1159 static QScopedPointer<QLibrary>          g_wow64redir_kernel32;
1160 static Wow64DisableWow64FsRedirectionFun g_wow64redir_disable = NULL;
1161 static Wow64RevertWow64FsRedirectionFun  g_wow64redir_revert  = NULL;
1162
1163 static bool wow64fsredir_init()
1164 {
1165         QWriteLocker writeLock(&g_wow64redir_lock);
1166         if(g_wow64redir_disable && g_wow64redir_revert)
1167         {
1168                 return true; /*already initialized*/
1169         }
1170
1171         if(g_wow64redir_kernel32.isNull())
1172         {
1173                 g_wow64redir_kernel32.reset(new QLibrary("kernel32.dll"));
1174         }
1175
1176         if(!g_wow64redir_kernel32->isLoaded())
1177         {
1178                 if(!g_wow64redir_kernel32->load())
1179                 {
1180                         return false; /*faild to load kernel32.dll*/
1181                 }
1182         }
1183
1184         g_wow64redir_disable = (Wow64DisableWow64FsRedirectionFun) g_wow64redir_kernel32->resolve("Wow64DisableWow64FsRedirection");
1185         g_wow64redir_revert  = (Wow64RevertWow64FsRedirectionFun)  g_wow64redir_kernel32->resolve("Wow64RevertWow64FsRedirection");
1186
1187         return (g_wow64redir_disable && g_wow64redir_revert);
1188 }
1189
1190 #define WOW64FSREDIR_INIT(RDLOCK) do \
1191 { \
1192         while(!(g_wow64redir_disable && g_wow64redir_revert)) \
1193         { \
1194                 (RDLOCK).unlock(); \
1195                 if(!wow64fsredir_init()) return false; \
1196                 (RDLOCK).relock(); \
1197         } \
1198 } \
1199 while(0)
1200
1201 bool MUtils::OS::wow64fsredir_disable(void *oldValue)
1202 {
1203         QReadLocker readLock(&g_wow64redir_lock);
1204         WOW64FSREDIR_INIT(readLock);
1205         if(g_wow64redir_disable(oldValue))
1206         {
1207                 return true;
1208         }
1209         return false;
1210 }
1211
1212 bool MUtils::OS::wow64fsredir_revert(void *oldValue)
1213 {
1214         QReadLocker readLock(&g_wow64redir_lock);
1215         WOW64FSREDIR_INIT(readLock);
1216         if(g_wow64redir_revert(oldValue))
1217         {
1218                 return true;
1219         }
1220         return false;
1221 }
1222
1223 ///////////////////////////////////////////////////////////////////////////////
1224 // DEBUGGER CHECK
1225 ///////////////////////////////////////////////////////////////////////////////
1226
1227 #if (!(MUTILS_DEBUG))
1228 static __forceinline bool is_debugger_present(void)
1229 {
1230         __try
1231         {
1232                 CloseHandle((HANDLE)((DWORD_PTR)-3));
1233         }
1234         __except(1)
1235         {
1236                 return true;
1237         }
1238
1239         BOOL bHaveDebugger = FALSE;
1240         if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
1241         {
1242                 if(bHaveDebugger) return true;
1243         }
1244
1245         return IsDebuggerPresent();
1246 }
1247 static __forceinline bool check_debugger_helper(void)
1248 {
1249         if(is_debugger_present())
1250         {
1251                 MUtils::OS::fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1252                 return true;
1253         }
1254         return false;
1255 }
1256 #else
1257 #define check_debugger_helper() (false)
1258 #endif
1259
1260 void MUtils::OS::check_debugger(void)
1261 {
1262         check_debugger_helper();
1263 }
1264
1265 static volatile bool g_debug_check = check_debugger_helper();
1266
1267 ///////////////////////////////////////////////////////////////////////////////
1268 // FATAL EXIT
1269 ///////////////////////////////////////////////////////////////////////////////
1270
1271 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
1272 static volatile bool g_fatal_exit_flag = true;
1273
1274 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
1275 {
1276         MUtils::OS::system_message_err(L"GURU MEDITATION", (LPWSTR) lpParameter);
1277         return 0;
1278 }
1279
1280 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
1281 {
1282         g_fatal_exit_lock.enter();
1283         
1284         if(!g_fatal_exit_flag)
1285         {
1286                 return; /*prevent recursive invocation*/
1287         }
1288
1289         g_fatal_exit_flag = false;
1290
1291         if(g_main_thread_id != GetCurrentThreadId())
1292         {
1293                 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
1294                 {
1295                         SuspendThread(hThreadMain); /*stop main thread*/
1296                 }
1297         }
1298
1299         if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL))
1300         {
1301                 WaitForSingleObject(hThread, INFINITE);
1302         }
1303
1304         for(;;)
1305         {
1306                 TerminateProcess(GetCurrentProcess(), 666);
1307         }
1308 }
1309
1310 ///////////////////////////////////////////////////////////////////////////////