OSDN Git Service

862bf02459c3db833d14b05d7f3cd6ddc4b7f164
[mutilities/MUtilities.git] / src / OSSupport_Win32.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2019 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 <WinIoCtl.h>
31 #pragma warning(push)
32 #pragma warning(disable:4091) //for MSVC2015
33 #include <ShlObj.h>
34 #pragma warning(pop)
35
36 //CRT
37 #include <io.h>
38
39 //Internal
40 #include <MUtils/Global.h>
41 #include <MUtils/OSSupport.h>
42 #include <MUtils/GUI.h>
43 #include "Internal.h"
44 #include "CriticalSection_Win32.h"
45 #include "Utils_Win32.h"
46
47 //Qt
48 #include <QMap>
49 #include <QReadWriteLock>
50 #include <QDir>
51 #include <QWidget>
52 #include <QProcess>
53 #include <QSet>
54
55 //Main thread ID
56 static const DWORD g_main_thread_id = GetCurrentThreadId();
57
58 ///////////////////////////////////////////////////////////////////////////////
59 // SYSTEM MESSAGE
60 ///////////////////////////////////////////////////////////////////////////////
61
62 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
63
64 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
65 {
66         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
67 }
68
69 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
70 {
71         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
72 }
73
74 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
75 {
76         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
77 }
78
79 ///////////////////////////////////////////////////////////////////////////////
80 // FETCH CLI ARGUMENTS
81 ///////////////////////////////////////////////////////////////////////////////
82
83 static QReadWriteLock                          g_arguments_lock;
84 static QScopedPointer<MUtils::OS::ArgumentMap> g_arguments_list;
85
86 const QStringList MUtils::OS::crack_command_line(const QString &command_line)
87 {
88         int nArgs = 0;
89         LPWSTR *szArglist = CommandLineToArgvW(command_line.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line), &nArgs);
90
91         QStringList command_line_tokens;
92         if(NULL != szArglist)
93         {
94                 for(int i = 0; i < nArgs; i++)
95                 {
96                         const QString argStr = MUTILS_QSTR(szArglist[i]).trimmed();
97                         if(!argStr.isEmpty())
98                         {
99                                 command_line_tokens << argStr;
100                         }
101                 }
102                 LocalFree(szArglist);
103         }
104
105         return command_line_tokens;
106 }
107
108 const MUtils::OS::ArgumentMap &MUtils::OS::arguments(void)
109 {
110         QReadLocker readLock(&g_arguments_lock);
111
112         //Already initialized?
113         if(!g_arguments_list.isNull())
114         {
115                 return (*(g_arguments_list.data()));
116         }
117
118         readLock.unlock();
119         QWriteLocker writeLock(&g_arguments_lock);
120
121         //Still not initialized?
122         if(!g_arguments_list.isNull())
123         {
124                 return (*(g_arguments_list.data()));
125         }
126
127         g_arguments_list.reset(new ArgumentMap());
128         const QStringList argList = crack_command_line();
129
130         if(!argList.isEmpty())
131         {
132                 const QString argPrefix = QLatin1String("--");
133                 const QChar   separator = QLatin1Char('=');
134
135                 bool firstToken = true;
136                 for(QStringList::ConstIterator iter = argList.constBegin(); iter != argList.constEnd(); iter++)
137                 {
138                         if(firstToken)
139                         {
140                                 firstToken = false;
141                                 continue; /*skip executable file name*/
142                         }
143                         if(iter->startsWith(argPrefix))
144                         {
145                                 const QString argData = iter->mid(2).trimmed();
146                                 if(argData.length() > 0)
147                                 {
148                                         const int separatorIndex = argData.indexOf(separator);
149                                         if(separatorIndex > 0)
150                                         {
151                                                 const QString argKey = argData.left(separatorIndex).trimmed();
152                                                 const QString argVal = argData.mid(separatorIndex + 1).trimmed();
153                                                 g_arguments_list->insertMulti(argKey.toLower(), argVal);
154                                         }
155                                         else
156                                         {
157                                                 g_arguments_list->insertMulti(argData.toLower(), QString());
158                                         }
159                                 }
160                         }
161                 }
162         }
163         else if(argList.empty())
164         {
165                 qWarning("CommandLineToArgvW() has failed !!!");
166         }
167
168         return (*(g_arguments_list.data()));
169 }
170
171 ///////////////////////////////////////////////////////////////////////////////
172 // COPY FILE
173 ///////////////////////////////////////////////////////////////////////////////
174
175 typedef struct _progress_callback_data_t
176 {
177         MUtils::OS::progress_callback_t callback_function;
178         void *user_data;
179 }
180 progress_callback_data_t;
181
182 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)
183 {
184         if(const progress_callback_data_t *data = (progress_callback_data_t*) lpData)
185         {
186                 const double progress = qBound(0.0, double(TotalBytesTransferred.QuadPart) / double(TotalFileSize.QuadPart), 1.0);
187                 return data->callback_function(progress, data->user_data) ? PROGRESS_CONTINUE : PROGRESS_CANCEL;
188         }
189         return PROGRESS_CONTINUE;
190 }
191
192 MUTILS_API bool MUtils::OS::copy_file(const QString &sourcePath, const QString &outputPath, const bool &overwrite, const progress_callback_t callback, void *const userData)
193 {
194         progress_callback_data_t callback_data = { callback, userData };
195         BOOL cancel = FALSE;
196         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));
197
198         if(result == FALSE)
199         {
200                 const DWORD errorCode = GetLastError();
201                 if(errorCode != ERROR_REQUEST_ABORTED)
202                 {
203                         qWarning("CopyFile() failed with error code 0x%08X!", errorCode);
204                 }
205                 else
206                 {
207                         qWarning("CopyFile() operation was abroted by user!");
208                 }
209         }
210
211         return (result != FALSE);
212 }
213
214 ///////////////////////////////////////////////////////////////////////////////
215 // GET FILE VERSION
216 ///////////////////////////////////////////////////////////////////////////////
217
218 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)
219 {
220         if(!GetFileVersionInfo(MUTILS_WCHR(fileName), 0, size, buffer))
221         {
222                 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
223                 return false;
224         }
225
226         VS_FIXEDFILEINFO *verInfo;
227         UINT verInfoLen;
228         if(!VerQueryValue(buffer, L"\\", (LPVOID*)(&verInfo), &verInfoLen))
229         {
230                 qWarning("VerQueryValue() has failed, file version cannot be determined!");
231                 return false;
232         }
233
234         if(major) *major = quint16((verInfo->dwFileVersionMS >> 16) & 0x0000FFFF);
235         if(minor) *minor = quint16((verInfo->dwFileVersionMS)       & 0x0000FFFF);
236         if(patch) *patch = quint16((verInfo->dwFileVersionLS >> 16) & 0x0000FFFF);
237         if(build) *build = quint16((verInfo->dwFileVersionLS)       & 0x0000FFFF);
238
239         return true;
240 }
241
242 bool MUtils::OS::get_file_version(const QString fileName, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
243 {
244         if(major) *major = 0U; if(minor) *minor = 0U;
245         if(patch) *patch = 0U; if(build) *build = 0U;
246
247         const DWORD size = GetFileVersionInfoSize(MUTILS_WCHR(fileName), NULL);
248         if(size < 1)
249         {
250                 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
251                 return false;
252         }
253         
254         PVOID buffer = _malloca(size);
255         if(!buffer)
256         {
257                 qWarning("Memory allocation has failed!");
258                 return false;
259         }
260
261         const bool success = get_file_version_helper(fileName, buffer, size, major, minor, patch, build);
262
263         _freea(buffer);
264         return success;
265 }
266
267 ///////////////////////////////////////////////////////////////////////////////
268 // OS VERSION DETECTION
269 ///////////////////////////////////////////////////////////////////////////////
270
271 static bool g_os_version_initialized = false;
272 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
273 static QReadWriteLock g_os_version_lock;
274
275 //Maps marketing names to the actual Windows NT versions
276 static const struct
277 {
278         MUtils::OS::Version::os_version_t version;
279         const char friendlyName[64];
280 }
281 g_os_version_lut[] =
282 {
283         { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000"                                  },        //2000
284         { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" },        //XP
285         { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64"         },        //XP_x64
286         { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008"          },        //Vista
287         { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2"           },        //7
288         { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012"              },        //8
289         { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2"         },        //8.1
290         { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2016"             },        //10
291         { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
292 };
293
294 //OS version data dtructures
295 namespace MUtils
296 {
297         namespace OS
298         {
299                 namespace Version
300                 {
301                         //Comparision operators for os_version_t
302                         bool os_version_t::operator== (const os_version_t &rhs) const { return (type == rhs.type) && (versionMajor == rhs.versionMajor) && ((versionMinor == rhs.versionMinor)); }
303                         bool os_version_t::operator!= (const os_version_t &rhs) const { return (type != rhs.type) || (versionMajor != rhs.versionMajor) || ((versionMinor != rhs.versionMinor)); }
304                         bool os_version_t::operator>  (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >  rhs.versionMinor))); }
305                         bool os_version_t::operator>= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >= rhs.versionMinor))); }
306                         bool os_version_t::operator<  (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <  rhs.versionMinor))); }
307                         bool os_version_t::operator<= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <= rhs.versionMinor))); }
308
309                         //Known Windows NT versions
310                         const os_version_t WINDOWS_WIN2K = { OS_WINDOWS,  5, 0,  2195, 0 };     // 2000
311                         const os_version_t WINDOWS_WINXP = { OS_WINDOWS,  5, 1,  2600, 0 };     // XP
312                         const os_version_t WINDOWS_XPX64 = { OS_WINDOWS,  5, 2,  3790, 0 };     // XP_x64
313                         const os_version_t WINDOWS_VISTA = { OS_WINDOWS,  6, 0,  6000, 0 };     // Vista
314                         const os_version_t WINDOWS_WIN70 = { OS_WINDOWS,  6, 1,  7600, 0 };     // 7
315                         const os_version_t WINDOWS_WIN80 = { OS_WINDOWS,  6, 2,  9200, 0 };     // 8
316                         const os_version_t WINDOWS_WIN81 = { OS_WINDOWS,  6, 3,  9600, 0 };     // 8.1
317                         const os_version_t WINDOWS_WN100 = { OS_WINDOWS, 10, 0, 10240, 0 };     // 10
318
319                         //Unknown OS
320                         const os_version_t UNKNOWN_OPSYS = { OS_UNKNOWN, 0,  0,     0, 0 };     // N/A
321                 }
322         }
323 }
324
325 static inline DWORD SAFE_ADD(const DWORD &a, const DWORD &b, const DWORD &limit = MAXDWORD)
326 {
327         return ((a >= limit) || (b >= limit) || ((limit - a) <= b)) ? limit : (a + b);
328 }
329
330
331 static void initialize_os_version(OSVERSIONINFOEXW *const osInfo)
332 {
333         memset(osInfo, 0, sizeof(OSVERSIONINFOEXW));
334         osInfo->dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
335 }
336
337 static inline DWORD initialize_step_size(const DWORD &limit)
338 {
339         DWORD result = 1;
340         while (result < limit)
341         {
342                 result = SAFE_ADD(result, result);
343         }
344         return result;
345 }
346
347 #pragma warning(push)
348 #pragma warning(disable: 4996)
349
350 static bool rtl_get_version(OSVERSIONINFOEXW *const osInfo)
351 {
352         typedef LONG(__stdcall *RtlGetVersion)(LPOSVERSIONINFOEXW);
353         if (const HMODULE ntdll = GetModuleHandleW(L"ntdll"))
354         {
355                 if (const RtlGetVersion pRtlGetVersion = (RtlGetVersion)GetProcAddress(ntdll, "RtlGetVersion"))
356                 {
357                         initialize_os_version(osInfo);
358                         if (pRtlGetVersion(osInfo) == 0)
359                         {
360                                 return true;
361                         }
362                 }
363         }
364
365         //Fallback
366         initialize_os_version(osInfo);
367         return (GetVersionExW((LPOSVERSIONINFOW)osInfo) != FALSE);
368 }
369
370 #pragma warning(pop) 
371
372 static bool rtl_verify_version(OSVERSIONINFOEXW *const osInfo, const ULONG typeMask, const ULONGLONG condMask)
373 {
374         typedef LONG(__stdcall *RtlVerifyVersionInfo)(LPOSVERSIONINFOEXW, ULONG, ULONGLONG);
375         if (const HMODULE ntdll = GetModuleHandleW(L"ntdll"))
376         {
377                 if (const RtlVerifyVersionInfo pRtlVerifyVersionInfo = (RtlVerifyVersionInfo)GetProcAddress(ntdll, "RtlVerifyVersionInfo"))
378                 {
379                         if (pRtlVerifyVersionInfo(osInfo, typeMask, condMask) == 0)
380                         {
381                                 return true;
382                         }
383                 }
384         }
385
386         //Fallback
387         return (VerifyVersionInfoW(osInfo, typeMask, condMask) != FALSE);
388 }
389
390 static bool verify_os_version(const DWORD major, const DWORD minor)
391 {
392         OSVERSIONINFOEXW osvi;
393         DWORDLONG dwlConditionMask = 0;
394         initialize_os_version(&osvi);
395
396         //Initialize the OSVERSIONINFOEX structure
397         osvi.dwMajorVersion = major;
398         osvi.dwMinorVersion = minor;
399         osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
400
401         //Initialize the condition mask
402         VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
403         VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
404         VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID,   VER_EQUAL);
405
406         // Perform the test
407         const BOOL ret = rtl_verify_version(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
408
409         //Error checking
410         if(!ret)
411         {
412                 if(GetLastError() != ERROR_OLD_WIN_VERSION)
413                 {
414                         qWarning("VerifyVersionInfo() system call has failed!");
415                 }
416         }
417
418         return (ret != FALSE);
419 }
420
421 static bool verify_os_build(const DWORD build)
422 {
423         OSVERSIONINFOEXW osvi;
424         DWORDLONG dwlConditionMask = 0;
425         initialize_os_version(&osvi);
426
427         //Initialize the OSVERSIONINFOEX structure
428         osvi.dwBuildNumber = build;
429         osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
430
431         //Initialize the condition mask
432         VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
433         VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
434
435         // Perform the test
436         const BOOL ret = rtl_verify_version(&osvi, VER_BUILDNUMBER | VER_PLATFORMID, dwlConditionMask);
437
438         //Error checking
439         if (!ret)
440         {
441                 if (GetLastError() != ERROR_OLD_WIN_VERSION)
442                 {
443                         qWarning("VerifyVersionInfo() system call has failed!");
444                 }
445         }
446
447         return (ret != FALSE);
448 }
449
450 static bool verify_os_spack(const WORD spack)
451 {
452         OSVERSIONINFOEXW osvi;
453         DWORDLONG dwlConditionMask = 0;
454         initialize_os_version(&osvi);
455
456         //Initialize the OSVERSIONINFOEX structure
457         osvi.wServicePackMajor = spack;
458         osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
459
460         //Initialize the condition mask
461         VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
462         VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
463
464         // Perform the test
465         const BOOL ret = rtl_verify_version(&osvi, VER_SERVICEPACKMAJOR | VER_PLATFORMID, dwlConditionMask);
466
467         //Error checking
468         if (!ret)
469         {
470                 if (GetLastError() != ERROR_OLD_WIN_VERSION)
471                 {
472                         qWarning("VerifyVersionInfo() system call has failed!");
473                 }
474         }
475
476         return (ret != FALSE);
477 }
478
479 static bool get_real_os_version(unsigned int *const major, unsigned int *const minor, unsigned int *const build, unsigned int *const spack, bool *const pbOverride)
480 {
481         static const DWORD MAX_VERSION = MAXWORD;
482         static const DWORD MAX_BUILDNO = MAXINT;
483         static const DWORD MAX_SRVCPCK = MAXWORD;
484
485         *major = *minor = *build = *spack = 0U;
486         *pbOverride = false;
487         
488         //Initialize local variables
489         OSVERSIONINFOEXW osvi;
490         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
491         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
492
493         //Try GetVersionEx() first
494         if(rtl_get_version(&osvi) == FALSE)
495         {
496                 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
497                 return false;
498         }
499
500         //Make sure we are running on NT
501         if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
502         {
503                 *major = osvi.dwMajorVersion;
504                 *minor = osvi.dwMinorVersion;
505                 *build = osvi.dwBuildNumber;
506                 *spack = osvi.wServicePackMajor;
507         }
508         else
509         {
510                 if (verify_os_version(4, 0))
511                 {
512                         *major = 4;
513                         *build = 1381;
514                         *pbOverride = true;
515                 }
516                 else
517                 {
518                         qWarning("Not running on Windows NT, unsupported operating system!");
519                         return false;
520                 }
521         }
522
523         //Major Version
524         for (DWORD nextMajor = (*major) + 1; nextMajor <= MAX_VERSION; nextMajor++)
525         {
526                 if (verify_os_version(nextMajor, 0))
527                 {
528                         *major = nextMajor;
529                         *minor = 0;
530                         *pbOverride = true;
531                         continue;
532                 }
533                 break;
534         }
535
536         //Minor Version
537         for (DWORD nextMinor = (*minor) + 1; nextMinor <= MAX_VERSION; nextMinor++)
538         {
539                 if (verify_os_version((*major), nextMinor))
540                 {
541                         *minor = nextMinor;
542                         *pbOverride = true;
543                         continue;
544                 }
545                 break;
546         }
547
548         //Build Version
549         if (verify_os_build(SAFE_ADD((*build), 1, MAX_BUILDNO)))
550         {
551                 DWORD stepSize = initialize_step_size(MAX_BUILDNO);
552                 for (DWORD nextBuildNo = SAFE_ADD((*build), stepSize, MAX_BUILDNO); (*build) < MAX_BUILDNO; nextBuildNo = SAFE_ADD((*build), stepSize, MAX_BUILDNO))
553                 {
554                         if (verify_os_build(nextBuildNo))
555                         {
556                                 *build = nextBuildNo;
557                                 *pbOverride = true;
558                                 continue;
559                         }
560                         if (stepSize > 1)
561                         {
562                                 stepSize = stepSize / 2;
563                                 continue;
564                         }
565                         break;
566                 }
567         }
568
569         //Service Pack
570         if (verify_os_spack(SAFE_ADD((*spack), 1, MAX_SRVCPCK)))
571         {
572                 DWORD stepSize = initialize_step_size(MAX_SRVCPCK);
573                 for (DWORD nextSPackNo = SAFE_ADD((*spack), stepSize, MAX_SRVCPCK); (*spack) < MAX_SRVCPCK; nextSPackNo = SAFE_ADD((*spack), stepSize, MAX_SRVCPCK))
574                 {
575                         if (verify_os_spack(nextSPackNo))
576                         {
577                                 *build = nextSPackNo;
578                                 *pbOverride = true;
579                                 continue;
580                         }
581                         if (stepSize > 1)
582                         {
583                                 stepSize = stepSize / 2;
584                                 continue;
585                         }
586                         break;
587                 }
588         }
589
590         return true;
591 }
592
593 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
594 {
595         QReadLocker readLock(&g_os_version_lock);
596
597         //Already initialized?
598         if(g_os_version_initialized)
599         {
600                 return g_os_version_info;
601         }
602         
603         readLock.unlock();
604         QWriteLocker writeLock(&g_os_version_lock);
605
606         //Initialized now?
607         if(g_os_version_initialized)
608         {
609                 return g_os_version_info;
610         }
611
612         //Detect OS version
613         unsigned int major, minor, build, spack; bool overrideFlg;
614         if(get_real_os_version(&major, &minor, &build, &spack, &overrideFlg))
615         {
616                 g_os_version_info.type = Version::OS_WINDOWS;
617                 g_os_version_info.versionMajor = major;
618                 g_os_version_info.versionMinor = minor;
619                 g_os_version_info.versionBuild = build;
620                 g_os_version_info.versionSPack = spack;
621                 g_os_version_info.overrideFlag = overrideFlg;
622         }
623         else
624         {
625                 qWarning("Failed to determine the operating system version!");
626         }
627
628         //Completed
629         g_os_version_initialized = true;
630         return g_os_version_info;
631 }
632
633 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
634 {
635         for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
636         {
637                 if(os_version == g_os_version_lut[i].version)
638                 {
639                         return g_os_version_lut[i].friendlyName;
640                 }
641         }
642
643         return NULL;
644 }
645
646 ///////////////////////////////////////////////////////////////////////////////
647 // WINE DETECTION
648 ///////////////////////////////////////////////////////////////////////////////
649
650 static bool g_wine_deteced = false;
651 static bool g_wine_initialized = false;
652 static QReadWriteLock g_wine_lock;
653
654 static const bool detect_wine(void)
655 {
656         void *const ptr = MUtils::Win32Utils::resolve<void*>(QLatin1String("ntdll"), QLatin1String("wine_get_version"));
657         return (ptr != NULL);
658 }
659
660 const bool &MUtils::OS::running_on_wine(void)
661 {
662         QReadLocker readLock(&g_wine_lock);
663
664         //Already initialized?
665         if(g_wine_initialized)
666         {
667                 return g_wine_deteced;
668         }
669
670         readLock.unlock();
671         QWriteLocker writeLock(&g_wine_lock);
672
673         //Initialized now?
674         if(g_wine_initialized)
675         {
676                 return g_wine_deteced;
677         }
678
679         //Try to detect Wine
680         g_wine_deteced = detect_wine();
681         g_wine_initialized = true;
682
683         return g_wine_deteced;
684 }
685
686 ///////////////////////////////////////////////////////////////////////////////
687 // KNWON FOLDERS
688 ///////////////////////////////////////////////////////////////////////////////
689
690 static QReadWriteLock                         g_known_folders_lock;
691 static QScopedPointer<QHash<size_t, QString>> g_known_folders_data;
692
693 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
694 typedef HRESULT (WINAPI *SHGetFolderPath_t)     (HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
695
696 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
697 {
698         typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
699         
700         struct
701         {
702                 const int csidl;
703                 const GUID guid;
704         }
705         static s_folders[] =
706         {
707                 { 0x001a, {0x3EB685DB,0x65F9,0x4CF6,{0xA0,0x3A,0xE3,0xEF,0x65,0x72,0x9F,0x3D}} },  //CSIDL_APPDATA
708                 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} },  //CSIDL_LOCAL_APPDATA
709                 { 0x0028, {0x5E6C858F,0x0E22,0x4760,{0x9A,0xFE,0xEA,0x33,0x17,0xB6,0x71,0x73}} },  //CSIDL_PROFILE
710                 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} },  //CSIDL_PROGRAM_FILES
711                 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} },  //CSIDL_SYSTEM_FOLDER
712                 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} },  //CSIDL_WINDOWS_FOLDER
713         };
714
715         size_t folderId = size_t(-1);
716
717         switch(folder_id)
718         {
719                 case FOLDER_ROAMING_DATA: folderId = 0; break;
720                 case FOLDER_LOCALAPPDATA: folderId = 1; break;
721                 case FOLDER_USER_PROFILE: folderId = 2; break;
722                 case FOLDER_PROGRAMFILES: folderId = 3; break;
723                 case FOLDER_SYSTEMFOLDER: folderId = 4; break;
724                 case FOLDER_SYSTROOT_DIR: folderId = 5; break;
725                 default:
726                         qWarning("Invalid 'known' folder was requested!");
727                         return Internal::g_empty;
728         }
729
730         QReadLocker readLock(&g_known_folders_lock);
731
732         //Already in cache?
733         if(!g_known_folders_data.isNull())
734         {
735                 if(g_known_folders_data->contains(folderId))
736                 {
737                         return (*g_known_folders_data)[folderId];
738                 }
739         }
740
741         //Obtain write lock to initialize
742         readLock.unlock();
743         QWriteLocker writeLock(&g_known_folders_lock);
744
745         //Still not in cache?
746         if(!g_known_folders_data.isNull())
747         {
748                 if(g_known_folders_data->contains(folderId))
749                 {
750                         return (*g_known_folders_data)[folderId];
751                 }
752         }
753
754         //Initialize on first call
755         if(g_known_folders_data.isNull())
756         {
757                 g_known_folders_data.reset(new QHash<size_t, QString>());
758         }
759
760         QString folderPath;
761
762         //Try SHGetKnownFolderPath() first!
763         if(const SHGetKnownFolderPath_t known_folders_fpGetKnownFolderPath = MUtils::Win32Utils::resolve<SHGetKnownFolderPath_t>(QLatin1String("shell32"), QLatin1String("SHGetKnownFolderPath")))
764         {
765                 WCHAR *path = NULL;
766                 if(known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
767                 {
768                         //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
769                         const QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
770                         if(folderTemp.exists())
771                         {
772                                 folderPath = folderTemp.canonicalPath();
773                         }
774                         CoTaskMemFree(path);
775                 }
776         }
777
778         //Fall back to SHGetFolderPathW()
779         if (folderPath.isEmpty())
780         {
781                 if (const SHGetFolderPath_t known_folders_fpGetFolderPath = MUtils::Win32Utils::resolve<SHGetFolderPath_t>(QLatin1String("shell32"), QLatin1String("SHGetFolderPathW")))
782                 {
783                         QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
784                         if (known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
785                         {
786                                 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
787                                 const QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
788                                 if (folderTemp.exists())
789                                 {
790                                         folderPath = folderTemp.canonicalPath();
791                                 }
792                         }
793                 }
794         }
795
796         //Update cache
797         if (!folderPath.isEmpty())
798         {
799                 g_known_folders_data->insert(folderId, folderPath);
800                 return (*g_known_folders_data)[folderId];
801         }
802
803         return Internal::g_empty;
804 }
805
806 ///////////////////////////////////////////////////////////////////////////////
807 // CURRENT DATA & TIME
808 ///////////////////////////////////////////////////////////////////////////////
809
810 QDate MUtils::OS::current_date(void)
811 {
812         const DWORD MAX_PROC = 1024;
813         QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
814         DWORD bytesReturned = 0;
815         
816         if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
817         {
818                 return QDate::currentDate();
819         }
820
821         const DWORD procCount = bytesReturned / sizeof(DWORD);
822         ULARGE_INTEGER lastStartTime;
823         memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
824
825         for(DWORD i = 0; i < procCount; i++)
826         {
827                 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
828                 {
829                         FILETIME processTime[4];
830                         if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
831                         {
832                                 ULARGE_INTEGER timeCreation;
833                                 timeCreation.LowPart  = processTime[0].dwLowDateTime;
834                                 timeCreation.HighPart = processTime[0].dwHighDateTime;
835                                 if(timeCreation.QuadPart > lastStartTime.QuadPart)
836                                 {
837                                         lastStartTime.QuadPart = timeCreation.QuadPart;
838                                 }
839                         }
840                         CloseHandle(hProc);
841                 }
842         }
843         
844         FILETIME lastStartTime_fileTime;
845         lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
846         lastStartTime_fileTime.dwLowDateTime  = lastStartTime.LowPart;
847
848         FILETIME lastStartTime_localTime;
849         if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
850         {
851                 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
852         }
853         
854         SYSTEMTIME lastStartTime_system;
855         if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
856         {
857                 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
858                 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
859         }
860
861         const QDate currentDate = QDate::currentDate();
862         const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
863         return (currentDate >= processDate) ? currentDate : processDate;
864 }
865
866 quint64 MUtils::OS::current_file_time(void)
867 {
868         FILETIME fileTime;
869         GetSystemTimeAsFileTime(&fileTime);
870
871         ULARGE_INTEGER temp;
872         temp.HighPart = fileTime.dwHighDateTime;
873         temp.LowPart = fileTime.dwLowDateTime;
874
875         return temp.QuadPart;
876 }
877
878 ///////////////////////////////////////////////////////////////////////////////
879 // FILE PATH FROM FD
880 ///////////////////////////////////////////////////////////////////////////////
881
882 typedef DWORD(_stdcall *GetPathNameByHandleFun)(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags);
883
884 static QString get_file_path_drive_list(void)
885 {
886         QString list;
887         const DWORD len = GetLogicalDriveStringsW(0, NULL);
888         if (len > 0)
889         {
890                 if (wchar_t *const buffer = (wchar_t*) _malloca(sizeof(wchar_t) * len))
891                 {
892                         const DWORD ret = GetLogicalDriveStringsW(len, buffer);
893                         if ((ret > 0) && (ret < len))
894                         {
895                                 const wchar_t *ptr = buffer;
896                                 while (const size_t current_len = wcslen(ptr))
897                                 {
898                                         list.append(QChar(*reinterpret_cast<const ushort*>(ptr)));
899                                         ptr += (current_len + 1);
900                                 }
901                         }
902                         _freea(buffer);
903                 }
904         }
905         return list;
906 }
907
908 static void get_file_path_translate(QString &path)
909 {
910         static const DWORD BUFSIZE = 2048;
911         wchar_t buffer[BUFSIZE], drive[3];
912
913         const QString driveList = get_file_path_drive_list();
914         wcscpy_s(drive, 3, L"?:");
915         for (const wchar_t *current = MUTILS_WCHR(driveList); *current; current++)
916         {
917                 drive[0] = (*current);
918                 if (QueryDosDeviceW(drive, buffer, MAX_PATH))
919                 {
920                         const QString prefix = MUTILS_QSTR(buffer);
921                         if (path.startsWith(prefix, Qt::CaseInsensitive))
922                         {
923                                 path.remove(0, prefix.length()).prepend(QLatin1Char(':')).prepend(QChar(*reinterpret_cast<const ushort*>(current)));
924                                 break;
925                         }
926                 }
927         }
928 }
929
930 static QString get_file_path_fallback(const HANDLE &hFile)
931 {
932         QString filePath;
933
934         const HANDLE hFileMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 1, NULL);
935         if (hFileMap)
936         {
937                 void *const pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
938                 if (pMem)
939                 {
940                         static const size_t BUFFSIZE = 2048;
941                         wchar_t buffer[BUFFSIZE];
942                         if (GetMappedFileNameW(GetCurrentProcess(), pMem, buffer, BUFFSIZE) > 0)
943                         {
944                                 filePath = MUTILS_QSTR(buffer);
945                         }
946                         UnmapViewOfFile(pMem);
947                 }
948                 CloseHandle(hFileMap);
949         }
950
951         if (!filePath.isEmpty())
952         {
953                 get_file_path_translate(filePath);
954         }
955
956         return filePath;
957 }
958
959 QString MUtils::OS::get_file_path(const int &fd)
960 {
961         if (fd >= 0)
962         {
963                 const GetPathNameByHandleFun getPathNameByHandleFun = MUtils::Win32Utils::resolve<GetPathNameByHandleFun>(QLatin1String("kernel32"), QLatin1String("GetFinalPathNameByHandleW"));
964                 if (!getPathNameByHandleFun)
965                 {
966                         return get_file_path_fallback((HANDLE)_get_osfhandle(fd));
967                 }
968
969                 const HANDLE handle = (HANDLE) _get_osfhandle(fd);
970                 const DWORD len = getPathNameByHandleFun(handle, NULL, 0, FILE_NAME_OPENED);
971                 if (len > 0)
972                 {
973                         if (wchar_t *const buffer = (wchar_t*)_malloca(sizeof(wchar_t) * len))
974                         {
975                                 const DWORD ret = getPathNameByHandleFun(handle, buffer, len, FILE_NAME_OPENED);
976                                 if ((ret > 0) && (ret < len))
977                                 {
978                                         const QString path(MUTILS_QSTR(buffer));
979                                         return path.startsWith(QLatin1String("\\\\?\\")) ? path.mid(4) : path;
980                                 }
981                                 _freea(buffer);
982                         }
983                 }
984         }
985
986         return QString();
987 }
988
989 ///////////////////////////////////////////////////////////////////////////////
990 // PROCESS ELEVATION
991 ///////////////////////////////////////////////////////////////////////////////
992
993 static bool user_is_admin_helper(void)
994 {
995         HANDLE hToken = NULL;
996         if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
997         {
998                 return false;
999         }
1000
1001         DWORD dwSize = 0;
1002         if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
1003         {
1004                 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1005                 {
1006                         CloseHandle(hToken);
1007                         return false;
1008                 }
1009         }
1010
1011         PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
1012         if(!lpGroups)
1013         {
1014                 CloseHandle(hToken);
1015                 return false;
1016         }
1017
1018         if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
1019         {
1020                 free(lpGroups);
1021                 CloseHandle(hToken);
1022                 return false;
1023         }
1024
1025         PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
1026         if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
1027         {
1028                 free(lpGroups);
1029                 CloseHandle(hToken);
1030                 return false;
1031         }
1032
1033         bool bResult = false;
1034         for(DWORD i = 0; i < lpGroups->GroupCount; i++)
1035         {
1036                 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
1037                 {
1038                         bResult = true;
1039                         break;
1040                 }
1041         }
1042
1043         FreeSid(lpSid);
1044         free(lpGroups);
1045         CloseHandle(hToken);
1046         return bResult;
1047 }
1048
1049 bool MUtils::OS::is_elevated(bool *bIsUacEnabled)
1050 {
1051         if(bIsUacEnabled)
1052         {
1053                 *bIsUacEnabled = false;
1054         }
1055
1056         bool bIsProcessElevated = false;
1057         HANDLE hToken = NULL;
1058         
1059         if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1060         {
1061                 TOKEN_ELEVATION_TYPE tokenElevationType;
1062                 DWORD returnLength;
1063                 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
1064                 {
1065                         if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
1066                         {
1067                                 switch(tokenElevationType)
1068                                 {
1069                                 case TokenElevationTypeDefault:
1070                                         qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1071                                         break;
1072                                 case TokenElevationTypeFull:
1073                                         qWarning("Process token elevation type: Full -> potential security risk!\n");
1074                                         bIsProcessElevated = true;
1075                                         if(bIsUacEnabled) *bIsUacEnabled = true;
1076                                         break;
1077                                 case TokenElevationTypeLimited:
1078                                         qDebug("Process token elevation type: Limited -> not elevated.\n");
1079                                         if(bIsUacEnabled) *bIsUacEnabled = true;
1080                                         break;
1081                                 default:
1082                                         qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
1083                                         break;
1084                                 }
1085                         }
1086                         else
1087                         {
1088                                 qWarning("GetTokenInformation() return an unexpected size!");
1089                         }
1090                 }
1091                 CloseHandle(hToken);
1092         }
1093         else
1094         {
1095                 qWarning("Failed to open process token!");
1096         }
1097
1098         return bIsProcessElevated;
1099 }
1100
1101 bool MUtils::OS::user_is_admin(void)
1102 {
1103         bool isAdmin = false;
1104
1105         //Check for process elevation and UAC support first!
1106         if(MUtils::OS::is_elevated(&isAdmin))
1107         {
1108                 qWarning("Process is elevated -> user is admin!");
1109                 return true;
1110         }
1111         
1112         //If not elevated and UAC is not available -> user must be in admin group!
1113         if(!isAdmin)
1114         {
1115                 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
1116                 isAdmin = user_is_admin_helper();
1117         }
1118
1119         return isAdmin;
1120 }
1121
1122 ///////////////////////////////////////////////////////////////////////////////
1123 // NETWORK STATE
1124 ///////////////////////////////////////////////////////////////////////////////
1125
1126 int MUtils::OS::network_status(void)
1127 {
1128         DWORD dwFlags;
1129         const BOOL ret = IsNetworkAlive(&dwFlags);
1130         if(GetLastError() == 0)
1131         {
1132                 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
1133         }
1134         return NETWORK_TYPE_ERR;
1135 }
1136
1137 ///////////////////////////////////////////////////////////////////////////////
1138 // MESSAGE HANDLER
1139 ///////////////////////////////////////////////////////////////////////////////
1140
1141 bool MUtils::OS::handle_os_message(const void *const message, long *result)
1142 {
1143         const MSG *const msg = reinterpret_cast<const MSG*>(message);
1144
1145         switch(msg->message)
1146         {
1147         case WM_QUERYENDSESSION:
1148                 qWarning("WM_QUERYENDSESSION message received!");
1149                 *result = MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION, false) ? TRUE : FALSE;
1150                 return true;
1151         case WM_ENDSESSION:
1152                 qWarning("WM_ENDSESSION message received!");
1153                 if(msg->wParam == TRUE)
1154                 {
1155                         MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION, false);
1156                         MUtils::GUI::force_quit();
1157                         exit(1);
1158                 }
1159                 *result = 0;
1160                 return true;
1161         default:
1162                 /*ignore this message and let Qt handle it*/
1163                 return false;
1164         }
1165 }
1166
1167 ///////////////////////////////////////////////////////////////////////////////
1168 // SLEEP
1169 ///////////////////////////////////////////////////////////////////////////////
1170
1171 void MUtils::OS::sleep_ms(const size_t &duration)
1172 {
1173         Sleep((DWORD) duration);
1174 }
1175
1176 ///////////////////////////////////////////////////////////////////////////////
1177 // EXECUTABLE CHECK
1178 ///////////////////////////////////////////////////////////////////////////////
1179
1180 static int g_library_as_image_resource_supported = -1;
1181 static QReadWriteLock g_library_as_image_resource_supported_lock;
1182
1183 static bool library_as_image_resource_supported()
1184 {
1185         QReadLocker readLocker(&g_library_as_image_resource_supported_lock);
1186         if (g_library_as_image_resource_supported >= 0)
1187         {
1188                 return (g_library_as_image_resource_supported > 0);
1189         }
1190
1191         readLocker.unlock();
1192         QWriteLocker writeLocker(&g_library_as_image_resource_supported_lock);
1193
1194         if (g_library_as_image_resource_supported < 0)
1195         {
1196                 g_library_as_image_resource_supported = 0;
1197                 OSVERSIONINFOEXW osvi;
1198                 if (rtl_get_version(&osvi))
1199                 {
1200                         if ((osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osvi.dwMajorVersion >= 6U))
1201                         {
1202                                 g_library_as_image_resource_supported = 1;
1203                         }
1204                 }
1205         }
1206
1207         return (g_library_as_image_resource_supported > 0);
1208 }
1209
1210 bool MUtils::OS::is_executable_file(const QString &path)
1211 {
1212         DWORD binaryType;
1213         if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
1214         {
1215                 return ((binaryType == SCS_32BIT_BINARY) || (binaryType == SCS_64BIT_BINARY));
1216         }
1217
1218         const DWORD errorCode = GetLastError();
1219         qWarning("GetBinaryType() failed with error: 0x%08X", errorCode);
1220         return false;
1221 }
1222
1223 bool MUtils::OS::is_library_file(const QString &path)
1224 {
1225         const DWORD flags = library_as_image_resource_supported() ? (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE) : (LOAD_LIBRARY_AS_DATAFILE | DONT_RESOLVE_DLL_REFERENCES);
1226         if (const HMODULE hMod = LoadLibraryEx(MUTILS_WCHR(QDir::toNativeSeparators(path)), NULL, flags))
1227         {
1228                 FreeLibrary(hMod);
1229                 return true;
1230         }
1231
1232         const DWORD errorCode = GetLastError();
1233         qWarning("LoadLibraryEx() failed with error: 0x%08X", errorCode);
1234         return false;
1235 }
1236
1237 ///////////////////////////////////////////////////////////////////////////////
1238 // HIBERNATION / SHUTDOWN
1239 ///////////////////////////////////////////////////////////////////////////////
1240
1241 bool MUtils::OS::is_hibernation_supported(void)
1242 {
1243         bool hibernationSupported = false;
1244
1245         SYSTEM_POWER_CAPABILITIES pwrCaps;
1246         SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1247         
1248         if(GetPwrCapabilities(&pwrCaps))
1249         {
1250                 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1251         }
1252
1253         return hibernationSupported;
1254 }
1255
1256 bool MUtils::OS::shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1257 {
1258         HANDLE hToken = NULL;
1259
1260         if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1261         {
1262                 TOKEN_PRIVILEGES privileges;
1263                 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1264                 privileges.PrivilegeCount = 1;
1265                 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1266                 
1267                 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1268                 {
1269                         if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1270                         {
1271                                 if(hibernate)
1272                                 {
1273                                         if(SetSuspendState(TRUE, TRUE, TRUE))
1274                                         {
1275                                                 return true;
1276                                         }
1277                                 }
1278                                 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1279                                 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1280                         }
1281                 }
1282         }
1283         
1284         return false;
1285 }
1286
1287 ///////////////////////////////////////////////////////////////////////////////
1288 // FREE DISKSPACE
1289 ///////////////////////////////////////////////////////////////////////////////
1290
1291 bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace)
1292 {
1293         ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1294         if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1295         {
1296                 freeSpace = freeBytesAvailable.QuadPart;
1297                 return true;;
1298         }
1299
1300         freeSpace = -1;
1301         return false;
1302 }
1303
1304 ///////////////////////////////////////////////////////////////////////////////
1305 // DRIVE TYPE
1306 ///////////////////////////////////////////////////////////////////////////////
1307
1308 static wchar_t get_drive_letter(const QString &path)
1309 {
1310         QString nativePath = QDir::toNativeSeparators(path);
1311         while (nativePath.startsWith("\\\\?\\") || nativePath.startsWith("\\\\.\\"))
1312         {
1313                 nativePath = QDir::toNativeSeparators(nativePath.mid(4));
1314         }
1315         if ((path.length() > 1) && (path[1] == QLatin1Char(':')))
1316         {
1317                 const wchar_t letter = static_cast<wchar_t>(path[0].unicode());
1318                 if (((letter >= 'A') && (letter <= 'Z')) || ((letter >= 'a') && (letter <= 'z')))
1319                 {
1320                         return towupper(letter);
1321                 }
1322         }
1323         return L'\0'; /*invalid path spec*/
1324 }
1325
1326 static QSet<DWORD> get_physical_drive_ids(const wchar_t drive_letter)
1327 {
1328         QSet<DWORD> physical_drives;
1329         wchar_t driveName[8];
1330         _snwprintf_s(driveName, 8, _TRUNCATE, L"\\\\.\\%c:", drive_letter);
1331         const HANDLE hDrive = CreateFileW(driveName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
1332         if (hDrive && (hDrive != INVALID_HANDLE_VALUE))
1333         {
1334                 const size_t BUFF_SIZE = sizeof(VOLUME_DISK_EXTENTS) + (32U * sizeof(DISK_EXTENT));
1335                 VOLUME_DISK_EXTENTS *const diskExtents = (VOLUME_DISK_EXTENTS*)_malloca(BUFF_SIZE);
1336                 DWORD dwSize;
1337                 if (DeviceIoControl(hDrive, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, (LPVOID)diskExtents, (DWORD)BUFF_SIZE, (LPDWORD)&dwSize, NULL))
1338                 {
1339                         for (DWORD index = 0U; index < diskExtents->NumberOfDiskExtents; ++index)
1340                         {
1341                                 physical_drives.insert(diskExtents->Extents[index].DiskNumber);
1342                         }
1343                 }
1344                 _freea(diskExtents);
1345                 CloseHandle(hDrive);
1346         }
1347         return physical_drives;
1348 }
1349
1350 static bool incurs_seek_penalty(const DWORD device_id)
1351 {
1352         wchar_t driveName[24];
1353         _snwprintf_s(driveName, 24, _TRUNCATE, L"\\\\?\\PhysicalDrive%u", device_id);
1354         const HANDLE hDevice = CreateFileW(driveName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
1355         bool seeking_penalty = true;
1356         if (hDevice && (hDevice != INVALID_HANDLE_VALUE))
1357         {
1358                 STORAGE_PROPERTY_QUERY spq;
1359                 DEVICE_SEEK_PENALTY_DESCRIPTOR dspd;
1360                 memset(&spq, 0, sizeof(STORAGE_PROPERTY_QUERY));
1361                 spq.PropertyId = (STORAGE_PROPERTY_ID)StorageDeviceSeekPenaltyProperty;
1362                 spq.QueryType = PropertyStandardQuery;
1363                 DWORD dwSize;
1364                 if (DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY, (LPVOID)&spq, (DWORD)sizeof(spq), (LPVOID)&dspd, (DWORD)sizeof(dspd), (LPDWORD)&dwSize, NULL))
1365                 {
1366                         seeking_penalty = dspd.IncursSeekPenalty;
1367                 }
1368                 CloseHandle(hDevice);
1369         }
1370         return seeking_penalty;
1371 }
1372
1373 static bool is_fast_seeking_drive(const wchar_t drive_letter)
1374 {
1375         bool fast_seeking = false;
1376         const QSet<DWORD> physical_drive_ids = get_physical_drive_ids(drive_letter);
1377         if (!physical_drive_ids.empty())
1378         {
1379                 fast_seeking = true;
1380                 for (QSet<DWORD>::const_iterator iter = physical_drive_ids.constBegin(); iter != physical_drive_ids.constEnd(); ++iter)
1381                 {
1382                         fast_seeking = fast_seeking && (!incurs_seek_penalty(*iter));
1383                 }
1384         }
1385         return fast_seeking;
1386 }
1387
1388 MUtils::OS::drive_type_t MUtils::OS::get_drive_type(const QString &path, bool *fast_seeking)
1389 {
1390         drive_type_t driveType = DRIVE_TYPE_ERR;
1391         const wchar_t driveLetter = get_drive_letter(path);
1392         if (driveLetter)
1393         {
1394                 wchar_t driveName[8];
1395                 _snwprintf_s(driveName, 8, _TRUNCATE, L"\\\\.\\%c:\\", driveLetter);
1396                 switch (GetDriveTypeW(driveName))
1397                 {
1398                         case DRIVE_REMOVABLE: driveType = DRIVE_TYPE_FDD; break;
1399                         case DRIVE_FIXED:     driveType = DRIVE_TYPE_HDD; break;
1400                         case DRIVE_REMOTE:    driveType = DRIVE_TYPE_NET; break;
1401                         case DRIVE_CDROM:     driveType = DRIVE_TYPE_OPT; break;
1402                         case DRIVE_RAMDISK:   driveType = DRIVE_TYPE_RAM; break;
1403                 }
1404         }
1405         if (fast_seeking)
1406         {
1407                 if (driveType == DRIVE_TYPE_HDD)
1408                 {
1409                         *fast_seeking = is_fast_seeking_drive(driveLetter);
1410                 }
1411                 else
1412                 {
1413                         *fast_seeking = (driveType == DRIVE_TYPE_RAM);
1414                 }
1415         }
1416         return driveType;
1417 }
1418
1419 ///////////////////////////////////////////////////////////////////////////////
1420 // SHELL OPEN
1421 ///////////////////////////////////////////////////////////////////////////////
1422
1423 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString &parameters, const QString &directory, const bool explore)
1424 {
1425         return ((int) ShellExecuteW((parent ? reinterpret_cast<HWND>(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;
1426 }
1427
1428 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore)
1429 {
1430         return shell_open(parent, url, QString(), QString(), explore);
1431 }
1432
1433 ///////////////////////////////////////////////////////////////////////////////
1434 // OPEN MEDIA FILE
1435 ///////////////////////////////////////////////////////////////////////////////
1436
1437 bool MUtils::OS::open_media_file(const QString &mediaFilePath)
1438 {
1439         const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1440         const static wchar_t *registryKeys[3] = 
1441         {
1442                 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1443                 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1444                 L"foobar2000"
1445         };
1446         const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1447         const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1448
1449         for(size_t i = 0; i < 3; i++)
1450         {
1451                 for(size_t j = 0; j < 2; j++)
1452                 {
1453                         QString mplayerPath;
1454                         HKEY registryKeyHandle = NULL;
1455
1456                         const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
1457                         if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
1458                         {
1459                                 for(size_t k = 0; k < 2; k++)
1460                                 {
1461                                         wchar_t Buffer[4096];
1462                                         DWORD BuffSize = sizeof(wchar_t*) * 4096;
1463                                         DWORD DataType = REG_NONE;
1464                                         if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1465                                         {
1466                                                 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1467                                                 {
1468                                                         mplayerPath = MUTILS_QSTR(Buffer);
1469                                                         break;
1470                                                 }
1471                                         }
1472                                 }
1473                                 RegCloseKey(registryKeyHandle);
1474                         }
1475
1476                         if(!mplayerPath.isEmpty())
1477                         {
1478                                 QDir mplayerDir(mplayerPath);
1479                                 if(mplayerDir.exists())
1480                                 {
1481                                         for(size_t k = 0; k < 4; k++)
1482                                         {
1483                                                 if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
1484                                                 {
1485                                                         qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
1486                                                         QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1487                                                         return true;
1488                                                 }
1489                                         }
1490                                 }
1491                         }
1492                 }
1493         }
1494         return false;
1495 }
1496
1497 ///////////////////////////////////////////////////////////////////////////////
1498 // DEBUGGER CHECK
1499 ///////////////////////////////////////////////////////////////////////////////
1500
1501 static bool change_process_priority_helper(const HANDLE hProcess, const int priority)
1502 {
1503         bool ok = false;
1504
1505         switch(qBound(-2, priority, 2))
1506         {
1507         case 2:
1508                 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1509                 break;
1510         case 1:
1511                 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1512                 {
1513                         ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1514                 }
1515                 break;
1516         case 0:
1517                 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1518                 break;
1519         case -1:
1520                 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1521                 {
1522                         ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1523                 }
1524                 break;
1525         case -2:
1526                 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1527                 break;
1528         }
1529
1530         return ok;
1531 }
1532
1533 bool MUtils::OS::change_process_priority(const int priority)
1534 {
1535         return change_process_priority_helper(GetCurrentProcess(), priority);
1536 }
1537
1538 bool MUtils::OS::change_process_priority(const QProcess *proc, const int priority)
1539 {
1540         if(Q_PID qPid = proc->pid())
1541         {
1542                 return change_process_priority_helper(qPid->hProcess, priority);
1543         }
1544         else
1545         {
1546                 return false;
1547         }
1548 }
1549
1550 ///////////////////////////////////////////////////////////////////////////////
1551 // PROCESS ID
1552 ///////////////////////////////////////////////////////////////////////////////
1553
1554 quint32 MUtils::OS::process_id(void)
1555 {
1556         return GetCurrentProcessId();
1557 }
1558
1559 quint32 MUtils::OS::process_id(const QProcess *const proc)
1560 {
1561         PROCESS_INFORMATION *procInf = proc->pid();
1562         return (procInf) ? procInf->dwProcessId : 0;
1563 }
1564
1565 quint32 MUtils::OS::thread_id(void)
1566 {
1567         return GetCurrentThreadId();
1568 }
1569
1570 quint32 MUtils::OS::thread_id(const QProcess *const proc)
1571 {
1572         PROCESS_INFORMATION *procInf = proc->pid();
1573         return (procInf) ? procInf->dwThreadId : 0;
1574 }
1575
1576 ///////////////////////////////////////////////////////////////////////////////
1577 // PROCESS SUSPEND/RESUME
1578 ///////////////////////////////////////////////////////////////////////////////
1579
1580 bool MUtils::OS::suspend_process(const QProcess *proc, const bool suspend)
1581 {
1582         if(Q_PID pid = proc->pid())
1583         {
1584                 if(suspend)
1585                 {
1586                         return (SuspendThread(pid->hThread) != ((DWORD) -1));
1587                 }
1588                 else
1589                 {
1590                         return (ResumeThread(pid->hThread)  != ((DWORD) -1));
1591                 }
1592         }
1593         else
1594         {
1595                 return false;
1596         }
1597 }
1598
1599 ///////////////////////////////////////////////////////////////////////////////
1600 // SYSTEM TIMER
1601 ///////////////////////////////////////////////////////////////////////////////
1602
1603 bool MUtils::OS::setup_timer_resolution(const quint32 &interval)
1604 {
1605         return timeBeginPeriod(interval) == TIMERR_NOERROR;
1606 }
1607
1608 bool MUtils::OS::reset_timer_resolution(const quint32 &interval)
1609 {
1610         return timeEndPeriod(interval) == TIMERR_NOERROR;
1611 }
1612
1613 ///////////////////////////////////////////////////////////////////////////////
1614 // SET FILE TIME
1615 ///////////////////////////////////////////////////////////////////////////////
1616
1617 static QScopedPointer<QDateTime> s_epoch;
1618 static QReadWriteLock            s_epochLock;
1619
1620 static const QDateTime *get_epoch(void)
1621 {
1622         QReadLocker rdLock(&s_epochLock);
1623
1624         if (s_epoch.isNull())
1625         {
1626                 rdLock.unlock();
1627                 QWriteLocker wrLock(&s_epochLock);
1628                 if (s_epoch.isNull())
1629                 {
1630                         s_epoch.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC));
1631                 }
1632                 wrLock.unlock();
1633                 rdLock.relock();
1634         }
1635
1636         return s_epoch.data();
1637 }
1638
1639 static FILETIME *qt_time_to_file_time(FILETIME *const fileTime, const QDateTime &dateTime)
1640 {
1641         memset(fileTime, 0, sizeof(FILETIME));
1642
1643         if (const QDateTime *const epoch = get_epoch())
1644         {
1645                 const qint64 msecs = epoch->msecsTo(dateTime);
1646                 if (msecs > 0)
1647                 {
1648                         const quint64 ticks = 10000U * quint64(msecs);
1649                         fileTime->dwHighDateTime = ((ticks >> 32) & 0xFFFFFFFF);
1650                         fileTime->dwLowDateTime = (ticks & 0xFFFFFFFF);
1651                         return fileTime;
1652                 }
1653         }
1654
1655         return NULL;
1656 }
1657
1658 static bool set_file_time(const HANDLE hFile, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1659 {
1660         FILETIME ftCreated, ftLastMod, ftLastAcc;
1661
1662         FILETIME *const pCreated = created.isValid() ? qt_time_to_file_time(&ftCreated, created) : NULL;
1663         FILETIME *const pLastMod = lastMod.isValid() ? qt_time_to_file_time(&ftLastMod, lastMod) : NULL;
1664         FILETIME *const pLastAcc = lastAcc.isValid() ? qt_time_to_file_time(&ftLastAcc, lastAcc) : NULL;
1665
1666         if (pCreated || pLastMod || pLastAcc)
1667         {
1668                 return (SetFileTime(hFile, pCreated, pLastAcc, pLastMod) != FALSE);
1669         }
1670
1671         return false;
1672 }
1673
1674 bool MUtils::OS::set_file_time(const QFile &file, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1675 {
1676         const int fd = file.handle();
1677         if (fd >= 0)
1678         {
1679                 return set_file_time((HANDLE)_get_osfhandle(fd), created, lastMod, lastAcc);
1680         }
1681         return false;
1682 }
1683
1684 bool MUtils::OS::set_file_time(const QString &path, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1685 {
1686         const HANDLE hFile = CreateFileW(MUTILS_WCHR(path), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1687         bool okay = false;
1688         if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
1689         {
1690                 okay = set_file_time(hFile, created, lastMod, lastAcc);
1691                 CloseHandle(hFile);
1692         }
1693         return okay;
1694 }
1695
1696 ///////////////////////////////////////////////////////////////////////////////
1697 // CHECK KEY STATE
1698 ///////////////////////////////////////////////////////////////////////////////
1699
1700 bool MUtils::OS::check_key_state_esc(void)
1701 {
1702         return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1703 }
1704
1705 ///////////////////////////////////////////////////////////////////////////////
1706 // SHELL CHANGE NOTIFICATION
1707 ///////////////////////////////////////////////////////////////////////////////
1708
1709 void MUtils::OS::shell_change_notification(void)
1710 {
1711         SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
1712 }
1713
1714 ///////////////////////////////////////////////////////////////////////////////
1715 // WOW64 REDIRECTION
1716 ///////////////////////////////////////////////////////////////////////////////
1717
1718 typedef BOOL (_stdcall *Wow64DisableWow64FsRedirectionFun)(PVOID *OldValue);
1719 typedef BOOL (_stdcall *Wow64RevertWow64FsRedirectionFun) (PVOID  OldValue);
1720
1721 bool MUtils::OS::wow64fsredir_disable(uintptr_t &oldValue)
1722 {
1723         oldValue = reinterpret_cast<uintptr_t>(nullptr);
1724         const Wow64DisableWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve<Wow64DisableWow64FsRedirectionFun>(QLatin1String("kernel32"), QLatin1String("Wow64DisableWow64FsRedirection"));
1725         if(wow64redir_disable)
1726         {
1727                 PVOID temp = NULL;
1728                 if (wow64redir_disable(&temp))
1729                 {
1730                         oldValue = reinterpret_cast<uintptr_t>(temp);
1731                         return true;
1732                 }
1733         }
1734         return false;
1735 }
1736
1737 bool MUtils::OS::wow64fsredir_revert(const uintptr_t oldValue)
1738 {
1739         const Wow64RevertWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve<Wow64RevertWow64FsRedirectionFun>(QLatin1String("kernel32"), QLatin1String("Wow64RevertWow64FsRedirection"));
1740         if (wow64redir_disable)
1741         {
1742                 if (wow64redir_disable(reinterpret_cast<PVOID>(oldValue)))
1743                 {
1744                         return true;
1745                 }
1746         }
1747         return false;
1748 }
1749
1750 ///////////////////////////////////////////////////////////////////////////////
1751 // DEBUGGER CHECK
1752 ///////////////////////////////////////////////////////////////////////////////
1753
1754 QString MUtils::OS::get_envvar(const QString &name)
1755 {
1756         wchar_t *buffer = NULL;
1757         size_t requiredSize = 0, buffSize = 0;
1758         QString result;
1759
1760         forever
1761         {
1762                 //Adjust the buffer size as required first!
1763                 if (buffSize < requiredSize)
1764                 {
1765                         if (buffer)
1766                         {
1767                                 _freea(buffer);
1768                         }
1769                         if (!(buffer = (wchar_t*)_malloca(sizeof(wchar_t) * requiredSize)))
1770                         {
1771                                 break; /*out of memory error!*/
1772                         }
1773                         buffSize = requiredSize;
1774                 }
1775
1776                 //Try to fetch the environment variable now
1777                 const errno_t error = _wgetenv_s(&requiredSize, buffer, buffSize, MUTILS_WCHR(name));
1778                 if(!error)
1779                 {
1780                         if (requiredSize > 0)
1781                         {
1782                                 result = MUTILS_QSTR(buffer);
1783                         }
1784                         break; /*done*/
1785                 }
1786                 else if (error != ERANGE)
1787                 {
1788                         break; /*somethging else went wrong!*/
1789                 }
1790         }
1791         
1792         if (buffer)
1793         {
1794                 _freea(buffer);
1795                 buffSize = 0;
1796                 buffer = NULL;
1797         }
1798
1799         return result;
1800 }
1801
1802 bool MUtils::OS::set_envvar(const QString &name, const QString &value)
1803 {
1804         if (!_wputenv_s(MUTILS_WCHR(name), MUTILS_WCHR(value)))
1805         {
1806                 return true;
1807         }
1808         return false;
1809 }
1810
1811 ///////////////////////////////////////////////////////////////////////////////
1812 // NULL DEVICE
1813 ///////////////////////////////////////////////////////////////////////////////
1814
1815 static const QLatin1String NULL_DEVICE("NUL");
1816
1817 const QLatin1String &MUtils::OS::null_device(void)
1818 {
1819         return NULL_DEVICE;
1820 }
1821
1822 ///////////////////////////////////////////////////////////////////////////////
1823 // DEBUGGER CHECK
1824 ///////////////////////////////////////////////////////////////////////////////
1825
1826 #if (!(MUTILS_DEBUG))
1827 static __forceinline bool is_debugger_present(void)
1828 {
1829         __try
1830         {
1831                 CloseHandle((HANDLE)((DWORD_PTR)-3));
1832         }
1833         __except(1)
1834         {
1835                 return true;
1836         }
1837
1838         BOOL bHaveDebugger = FALSE;
1839         if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
1840         {
1841                 if(bHaveDebugger) return true;
1842         }
1843
1844         return IsDebuggerPresent();
1845 }
1846 static __forceinline bool check_debugger_helper(void)
1847 {
1848         if(is_debugger_present())
1849         {
1850                 MUtils::OS::fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1851                 return true;
1852         }
1853         return false;
1854 }
1855 #else
1856 #define check_debugger_helper() (false)
1857 #endif
1858
1859 void MUtils::OS::check_debugger(void)
1860 {
1861         check_debugger_helper();
1862 }
1863
1864 static volatile bool g_debug_check = check_debugger_helper();
1865
1866 ///////////////////////////////////////////////////////////////////////////////
1867 // FATAL EXIT
1868 ///////////////////////////////////////////////////////////////////////////////
1869
1870 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
1871 static QAtomicInt g_fatal_exit_flag;
1872
1873 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
1874 {
1875         MUtils::OS::system_message_err(L"GURU MEDITATION", (LPWSTR) lpParameter);
1876         return 0;
1877 }
1878
1879 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
1880 {
1881         g_fatal_exit_lock.enter();
1882         
1883         if(!g_fatal_exit_flag.testAndSetOrdered(0, 1))
1884         {
1885                 return; /*prevent recursive invocation*/
1886         }
1887
1888         if(g_main_thread_id != GetCurrentThreadId())
1889         {
1890                 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
1891                 {
1892                         SuspendThread(hThreadMain); /*stop main thread*/
1893                 }
1894         }
1895
1896         if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID)errorMessage, 0, NULL))
1897         {
1898                 WaitForSingleObject(hThread, INFINITE);
1899         }
1900         else
1901         {
1902                 fatal_exit_helper((LPVOID)errorMessage);
1903         }
1904
1905         for(;;)
1906         {
1907                 TerminateProcess(GetCurrentProcess(), 666);
1908         }
1909 }
1910
1911 ///////////////////////////////////////////////////////////////////////////////