Some clean-up and simplification for JobObject class.
[MUtilities.git] / src / OSSupport_Win32.cpp
blob088e5f1bc7766033ac17dc32994abf76b6379a8c
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2016 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.
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
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
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 #pragma warning(push)
31 #pragma warning(disable:4091) //for MSVC2015
32 #include <ShlObj.h>
33 #pragma warning(pop)
35 //CRT
36 #include <io.h>
38 //Internal
39 #include <MUtils/Global.h>
40 #include <MUtils/OSSupport.h>
41 #include <MUtils/GUI.h>
42 #include "CriticalSection_Win32.h"
43 #include "Utils_Win32.h"
45 //Qt
46 #include <QMap>
47 #include <QReadWriteLock>
48 #include <QDir>
49 #include <QWidget>
50 #include <QProcess>
52 //Main thread ID
53 static const DWORD g_main_thread_id = GetCurrentThreadId();
55 ///////////////////////////////////////////////////////////////////////////////
56 // SYSTEM MESSAGE
57 ///////////////////////////////////////////////////////////////////////////////
59 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
61 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
63 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
66 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
68 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
71 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
73 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
76 ///////////////////////////////////////////////////////////////////////////////
77 // FETCH CLI ARGUMENTS
78 ///////////////////////////////////////////////////////////////////////////////
80 static QReadWriteLock g_arguments_lock;
81 static QScopedPointer<MUtils::OS::ArgumentMap> g_arguments_list;
83 const QStringList MUtils::OS::crack_command_line(const QString &command_line)
85 int nArgs = 0;
86 LPWSTR *szArglist = CommandLineToArgvW(command_line.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line), &nArgs);
88 QStringList command_line_tokens;
89 if(NULL != szArglist)
91 for(int i = 0; i < nArgs; i++)
93 const QString argStr = MUTILS_QSTR(szArglist[i]).trimmed();
94 if(!argStr.isEmpty())
96 command_line_tokens << argStr;
99 LocalFree(szArglist);
102 return command_line_tokens;
105 const MUtils::OS::ArgumentMap &MUtils::OS::arguments(void)
107 QReadLocker readLock(&g_arguments_lock);
109 //Already initialized?
110 if(!g_arguments_list.isNull())
112 return (*(g_arguments_list.data()));
115 readLock.unlock();
116 QWriteLocker writeLock(&g_arguments_lock);
118 //Still not initialized?
119 if(!g_arguments_list.isNull())
121 return (*(g_arguments_list.data()));
124 g_arguments_list.reset(new ArgumentMap());
125 const QStringList argList = crack_command_line();
127 if(!argList.isEmpty())
129 const QString argPrefix = QLatin1String("--");
130 const QChar separator = QLatin1Char('=');
132 bool firstToken = true;
133 for(QStringList::ConstIterator iter = argList.constBegin(); iter != argList.constEnd(); iter++)
135 if(firstToken)
137 firstToken = false;
138 continue; /*skip executable file name*/
140 if(iter->startsWith(argPrefix))
142 const QString argData = iter->mid(2).trimmed();
143 if(argData.length() > 0)
145 const int separatorIndex = argData.indexOf(separator);
146 if(separatorIndex > 0)
148 const QString argKey = argData.left(separatorIndex).trimmed();
149 const QString argVal = argData.mid(separatorIndex + 1).trimmed();
150 g_arguments_list->insertMulti(argKey.toLower(), argVal);
152 else
154 g_arguments_list->insertMulti(argData.toLower(), QString());
160 else if(argList.empty())
162 qWarning("CommandLineToArgvW() has failed !!!");
165 return (*(g_arguments_list.data()));
168 ///////////////////////////////////////////////////////////////////////////////
169 // COPY FILE
170 ///////////////////////////////////////////////////////////////////////////////
172 typedef struct _progress_callback_data_t
174 MUtils::OS::progress_callback_t callback_function;
175 void *user_data;
177 progress_callback_data_t;
179 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)
181 if(const progress_callback_data_t *data = (progress_callback_data_t*) lpData)
183 const double progress = qBound(0.0, double(TotalBytesTransferred.QuadPart) / double(TotalFileSize.QuadPart), 1.0);
184 return data->callback_function(progress, data->user_data) ? PROGRESS_CONTINUE : PROGRESS_CANCEL;
186 return PROGRESS_CONTINUE;
189 MUTILS_API bool MUtils::OS::copy_file(const QString &sourcePath, const QString &outputPath, const bool &overwrite, const progress_callback_t callback, void *const userData)
191 progress_callback_data_t callback_data = { callback, userData };
192 BOOL cancel = FALSE;
193 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));
195 if(result == FALSE)
197 const DWORD errorCode = GetLastError();
198 if(errorCode != ERROR_REQUEST_ABORTED)
200 qWarning("CopyFile() failed with error code 0x%08X!", errorCode);
202 else
204 qWarning("CopyFile() operation was abroted by user!");
208 return (result != FALSE);
211 ///////////////////////////////////////////////////////////////////////////////
212 // GET FILE VERSION
213 ///////////////////////////////////////////////////////////////////////////////
215 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)
217 if(!GetFileVersionInfo(MUTILS_WCHR(fileName), 0, size, buffer))
219 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
220 return false;
223 VS_FIXEDFILEINFO *verInfo;
224 UINT verInfoLen;
225 if(!VerQueryValue(buffer, L"\\", (LPVOID*)(&verInfo), &verInfoLen))
227 qWarning("VerQueryValue() has failed, file version cannot be determined!");
228 return false;
231 if(major) *major = quint16((verInfo->dwFileVersionMS >> 16) & 0x0000FFFF);
232 if(minor) *minor = quint16((verInfo->dwFileVersionMS) & 0x0000FFFF);
233 if(patch) *patch = quint16((verInfo->dwFileVersionLS >> 16) & 0x0000FFFF);
234 if(build) *build = quint16((verInfo->dwFileVersionLS) & 0x0000FFFF);
236 return true;
239 bool MUtils::OS::get_file_version(const QString fileName, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
241 if(major) *major = 0U; if(minor) *minor = 0U;
242 if(patch) *patch = 0U; if(build) *build = 0U;
244 const DWORD size = GetFileVersionInfoSize(MUTILS_WCHR(fileName), NULL);
245 if(size < 1)
247 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
248 return false;
251 PVOID buffer = _malloca(size);
252 if(!buffer)
254 qWarning("Memory allocation has failed!");
255 return false;
258 const bool success = get_file_version_helper(fileName, buffer, size, major, minor, patch, build);
260 _freea(buffer);
261 return success;
264 ///////////////////////////////////////////////////////////////////////////////
265 // OS VERSION DETECTION
266 ///////////////////////////////////////////////////////////////////////////////
268 static bool g_os_version_initialized = false;
269 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
270 static QReadWriteLock g_os_version_lock;
272 //Maps marketing names to the actual Windows NT versions
273 static const struct
275 MUtils::OS::Version::os_version_t version;
276 const char friendlyName[64];
278 g_os_version_lut[] =
280 { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000" }, //2000
281 { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" }, //XP
282 { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64" }, //XP_x64
283 { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008" }, //Vista
284 { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2" }, //7
285 { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012" }, //8
286 { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
287 { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2016" }, //10
288 { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
291 //OS version data dtructures
292 namespace MUtils
294 namespace OS
296 namespace Version
298 //Comparision operators for os_version_t
299 bool os_version_t::operator== (const os_version_t &rhs) const { return (type == rhs.type) && (versionMajor == rhs.versionMajor) && ((versionMinor == rhs.versionMinor)); }
300 bool os_version_t::operator!= (const os_version_t &rhs) const { return (type != rhs.type) || (versionMajor != rhs.versionMajor) || ((versionMinor != rhs.versionMinor)); }
301 bool os_version_t::operator> (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor > rhs.versionMinor))); }
302 bool os_version_t::operator>= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((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) || ((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))); }
306 //Known Windows NT versions
307 const os_version_t WINDOWS_WIN2K = { OS_WINDOWS, 5, 0, 2195 }; // 2000
308 const os_version_t WINDOWS_WINXP = { OS_WINDOWS, 5, 1, 2600 }; // XP
309 const os_version_t WINDOWS_XPX64 = { OS_WINDOWS, 5, 2, 3790 }; // XP_x64
310 const os_version_t WINDOWS_VISTA = { OS_WINDOWS, 6, 0, 6000 }; // Vista
311 const os_version_t WINDOWS_WIN70 = { OS_WINDOWS, 6, 1, 7600 }; // 7
312 const os_version_t WINDOWS_WIN80 = { OS_WINDOWS, 6, 2, 9200 }; // 8
313 const os_version_t WINDOWS_WIN81 = { OS_WINDOWS, 6, 3, 9600 }; // 8.1
314 const os_version_t WINDOWS_WN100 = { OS_WINDOWS, 10, 0, 10240 }; // 10
316 //Unknown OS
317 const os_version_t UNKNOWN_OPSYS = { OS_UNKNOWN, 0, 0, 0 }; // N/A
322 static inline DWORD SAFE_ADD(const DWORD &a, const DWORD &b, const DWORD &limit = MAXDWORD)
324 return ((a >= limit) || (b >= limit) || ((limit - a) <= b)) ? limit : (a + b);
328 static void initialize_os_version(OSVERSIONINFOEXW *const osInfo)
330 memset(osInfo, 0, sizeof(OSVERSIONINFOEXW));
331 osInfo->dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
334 static inline DWORD initialize_step_size(const DWORD &limit)
336 DWORD result = 1;
337 while (result < limit)
339 result = SAFE_ADD(result, result);
341 return result;
344 static bool rtl_get_version(OSVERSIONINFOEXW *const osInfo)
346 typedef LONG(__stdcall *RtlGetVersion)(LPOSVERSIONINFOEXW);
347 if (const HMODULE ntdll = GetModuleHandleW(L"ntdll"))
349 if (const RtlGetVersion pRtlGetVersion = (RtlGetVersion)GetProcAddress(ntdll, "RtlGetVersion"))
351 initialize_os_version(osInfo);
352 if (pRtlGetVersion(osInfo) == 0)
354 return true;
359 //Fallback
360 initialize_os_version(osInfo);
361 return (GetVersionExW((LPOSVERSIONINFOW)osInfo) != FALSE);
364 static bool rtl_verify_version(OSVERSIONINFOEXW *const osInfo, const ULONG typeMask, const ULONGLONG condMask)
366 typedef LONG(__stdcall *RtlVerifyVersionInfo)(LPOSVERSIONINFOEXW, ULONG, ULONGLONG);
367 if (const HMODULE ntdll = GetModuleHandleW(L"ntdll"))
369 if (const RtlVerifyVersionInfo pRtlVerifyVersionInfo = (RtlVerifyVersionInfo)GetProcAddress(ntdll, "RtlVerifyVersionInfo"))
371 if (pRtlVerifyVersionInfo(osInfo, typeMask, condMask) == 0)
373 return true;
378 //Fallback
379 return (VerifyVersionInfoW(osInfo, typeMask, condMask) != FALSE);
382 static bool verify_os_version(const DWORD major, const DWORD minor)
384 OSVERSIONINFOEXW osvi;
385 DWORDLONG dwlConditionMask = 0;
386 initialize_os_version(&osvi);
388 //Initialize the OSVERSIONINFOEX structure
389 osvi.dwMajorVersion = major;
390 osvi.dwMinorVersion = minor;
391 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
393 //Initialize the condition mask
394 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
395 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
396 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
398 // Perform the test
399 const BOOL ret = rtl_verify_version(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
401 //Error checking
402 if(!ret)
404 if(GetLastError() != ERROR_OLD_WIN_VERSION)
406 qWarning("VerifyVersionInfo() system call has failed!");
410 return (ret != FALSE);
413 static bool verify_os_build(const DWORD build)
415 OSVERSIONINFOEXW osvi;
416 DWORDLONG dwlConditionMask = 0;
417 initialize_os_version(&osvi);
419 //Initialize the OSVERSIONINFOEX structure
420 osvi.dwBuildNumber = build;
421 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
423 //Initialize the condition mask
424 VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
425 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
427 // Perform the test
428 const BOOL ret = rtl_verify_version(&osvi, VER_BUILDNUMBER | VER_PLATFORMID, dwlConditionMask);
430 //Error checking
431 if (!ret)
433 if (GetLastError() != ERROR_OLD_WIN_VERSION)
435 qWarning("VerifyVersionInfo() system call has failed!");
439 return (ret != FALSE);
442 static bool get_real_os_version(unsigned int *major, unsigned int *minor, unsigned int *build, bool *pbOverride)
444 static const DWORD MAX_VERSION = 0xFFFF;
445 static const DWORD MAX_BUILDNO = MAXINT;
447 *major = *minor = *build = 0;
448 *pbOverride = false;
450 //Initialize local variables
451 OSVERSIONINFOEXW osvi;
452 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
453 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
455 //Try GetVersionEx() first
456 if(rtl_get_version(&osvi) == FALSE)
458 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
459 return false;
462 //Make sure we are running on NT
463 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
465 *major = osvi.dwMajorVersion;
466 *minor = osvi.dwMinorVersion;
467 *build = osvi.dwBuildNumber;
469 else
471 if (verify_os_version(4, 0))
473 *major = 4;
474 *build = 1381;
475 *pbOverride = true;
477 else
479 qWarning("Not running on Windows NT, unsupported operating system!");
480 return false;
484 //Major Version
485 for (DWORD nextMajor = (*major) + 1; nextMajor <= MAX_VERSION; nextMajor++)
487 if (verify_os_version(nextMajor, 0))
489 *major = nextMajor;
490 *minor = 0;
491 *pbOverride = true;
492 continue;
494 break;
497 //Minor Version
498 for (DWORD nextMinor = (*minor) + 1; nextMinor <= MAX_VERSION; nextMinor++)
500 if (verify_os_version((*major), nextMinor))
502 *minor = nextMinor;
503 *pbOverride = true;
504 continue;
506 break;
509 //Build Version
510 if (verify_os_build(SAFE_ADD((*build), 1, MAX_BUILDNO)))
512 DWORD stepSize = initialize_step_size(MAX_BUILDNO);
513 for (DWORD nextBuildNo = SAFE_ADD((*build), stepSize, MAX_BUILDNO); (*build) < MAX_BUILDNO; nextBuildNo = SAFE_ADD((*build), stepSize, MAX_BUILDNO))
515 if (verify_os_build(nextBuildNo))
517 *build = nextBuildNo;
518 *pbOverride = true;
519 continue;
521 if (stepSize > 1)
523 stepSize = stepSize / 2;
524 continue;
526 break;
530 return true;
533 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
535 QReadLocker readLock(&g_os_version_lock);
537 //Already initialized?
538 if(g_os_version_initialized)
540 return g_os_version_info;
543 readLock.unlock();
544 QWriteLocker writeLock(&g_os_version_lock);
546 //Initialized now?
547 if(g_os_version_initialized)
549 return g_os_version_info;
552 //Detect OS version
553 unsigned int major, minor, build; bool overrideFlg;
554 if(get_real_os_version(&major, &minor, &build, &overrideFlg))
556 g_os_version_info.type = Version::OS_WINDOWS;
557 g_os_version_info.versionMajor = major;
558 g_os_version_info.versionMinor = minor;
559 g_os_version_info.versionBuild = build;
560 g_os_version_info.overrideFlag = overrideFlg;
562 else
564 qWarning("Failed to determin the operating system version!");
567 //Completed
568 g_os_version_initialized = true;
569 return g_os_version_info;
572 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
574 for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
576 if(os_version == g_os_version_lut[i].version)
578 return g_os_version_lut[i].friendlyName;
582 return NULL;
585 ///////////////////////////////////////////////////////////////////////////////
586 // WINE DETECTION
587 ///////////////////////////////////////////////////////////////////////////////
589 static bool g_wine_deteced = false;
590 static bool g_wine_initialized = false;
591 static QReadWriteLock g_wine_lock;
593 static const bool detect_wine(void)
595 void *const ptr = MUtils::Win32Utils::resolve<void*>(QLatin1String("ntdll"), QLatin1String("wine_get_version"));
596 return (ptr != NULL);
599 const bool &MUtils::OS::running_on_wine(void)
601 QReadLocker readLock(&g_wine_lock);
603 //Already initialized?
604 if(g_wine_initialized)
606 return g_wine_deteced;
609 readLock.unlock();
610 QWriteLocker writeLock(&g_wine_lock);
612 //Initialized now?
613 if(g_wine_initialized)
615 return g_wine_deteced;
618 //Try to detect Wine
619 g_wine_deteced = detect_wine();
620 g_wine_initialized = true;
622 return g_wine_deteced;
625 ///////////////////////////////////////////////////////////////////////////////
626 // KNWON FOLDERS
627 ///////////////////////////////////////////////////////////////////////////////
629 typedef QMap<size_t, QString> KFMap;
630 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
631 typedef HRESULT (WINAPI *SHGetFolderPath_t) (HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
633 static QScopedPointer<KFMap> g_known_folders_map;
634 static QReadWriteLock g_known_folders_lock;
636 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
638 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
640 struct
642 const int csidl;
643 const GUID guid;
645 static s_folders[] =
647 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
648 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
649 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
650 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
653 size_t folderId = size_t(-1);
655 switch(folder_id)
657 case FOLDER_LOCALAPPDATA: folderId = 0; break;
658 case FOLDER_PROGRAMFILES: folderId = 1; break;
659 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
660 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
663 if(folderId == size_t(-1))
665 qWarning("Invalid 'known' folder was requested!");
666 return *reinterpret_cast<QString*>(NULL);
669 QReadLocker readLock(&g_known_folders_lock);
671 //Already in cache?
672 if(!g_known_folders_map.isNull())
674 if(g_known_folders_map->contains(folderId))
676 return g_known_folders_map->operator[](folderId);
680 //Obtain write lock to initialize
681 readLock.unlock();
682 QWriteLocker writeLock(&g_known_folders_lock);
684 //Still not in cache?
685 if(!g_known_folders_map.isNull())
687 if(g_known_folders_map->contains(folderId))
689 return g_known_folders_map->operator[](folderId);
693 //Initialize on first call
694 if(g_known_folders_map.isNull())
696 g_known_folders_map.reset(new QMap<size_t, QString>());
699 QString folderPath;
701 //Now try to get the folder path!
702 if(const SHGetKnownFolderPath_t known_folders_fpGetKnownFolderPath = MUtils::Win32Utils::resolve<SHGetKnownFolderPath_t>(QLatin1String("shell32"), QLatin1String("SHGetKnownFolderPath")))
704 WCHAR *path = NULL;
705 if(known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
707 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
708 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
709 if(folderTemp.exists())
711 folderPath = folderTemp.canonicalPath();
713 CoTaskMemFree(path);
716 else if(const SHGetFolderPath_t known_folders_fpGetFolderPath = MUtils::Win32Utils::resolve<SHGetFolderPath_t>(QLatin1String("shell32"), QLatin1String("SHGetFolderPathW")))
718 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
719 if(known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
721 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
722 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
723 if(folderTemp.exists())
725 folderPath = folderTemp.canonicalPath();
730 //Update cache
731 g_known_folders_map->insert(folderId, folderPath);
732 return g_known_folders_map->operator[](folderId);
735 ///////////////////////////////////////////////////////////////////////////////
736 // CURRENT DATA & TIME
737 ///////////////////////////////////////////////////////////////////////////////
739 QDate MUtils::OS::current_date(void)
741 const DWORD MAX_PROC = 1024;
742 QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
743 DWORD bytesReturned = 0;
745 if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
747 return QDate::currentDate();
750 const DWORD procCount = bytesReturned / sizeof(DWORD);
751 ULARGE_INTEGER lastStartTime;
752 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
754 for(DWORD i = 0; i < procCount; i++)
756 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
758 FILETIME processTime[4];
759 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
761 ULARGE_INTEGER timeCreation;
762 timeCreation.LowPart = processTime[0].dwLowDateTime;
763 timeCreation.HighPart = processTime[0].dwHighDateTime;
764 if(timeCreation.QuadPart > lastStartTime.QuadPart)
766 lastStartTime.QuadPart = timeCreation.QuadPart;
769 CloseHandle(hProc);
773 FILETIME lastStartTime_fileTime;
774 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
775 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
777 FILETIME lastStartTime_localTime;
778 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
780 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
783 SYSTEMTIME lastStartTime_system;
784 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
786 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
787 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
790 const QDate currentDate = QDate::currentDate();
791 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
792 return (currentDate >= processDate) ? currentDate : processDate;
795 quint64 MUtils::OS::current_file_time(void)
797 FILETIME fileTime;
798 GetSystemTimeAsFileTime(&fileTime);
800 ULARGE_INTEGER temp;
801 temp.HighPart = fileTime.dwHighDateTime;
802 temp.LowPart = fileTime.dwLowDateTime;
804 return temp.QuadPart;
807 ///////////////////////////////////////////////////////////////////////////////
808 // FILE PATH FROM FD
809 ///////////////////////////////////////////////////////////////////////////////
811 typedef DWORD(_stdcall *GetPathNameByHandleFun)(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags);
813 static QString get_file_path_drive_list(void)
815 QString list;
816 const DWORD len = GetLogicalDriveStringsW(0, NULL);
817 if (len > 0)
819 if (wchar_t *const buffer = (wchar_t*) _malloca(sizeof(wchar_t) * len))
821 const DWORD ret = GetLogicalDriveStringsW(len, buffer);
822 if ((ret > 0) && (ret < len))
824 const wchar_t *ptr = buffer;
825 while (const size_t current_len = wcslen(ptr))
827 list.append(QChar(*reinterpret_cast<const ushort*>(ptr)));
828 ptr += (current_len + 1);
831 _freea(buffer);
834 return list;
837 static void get_file_path_translate(QString &path)
839 static const DWORD BUFSIZE = 2048;
840 wchar_t buffer[BUFSIZE], drive[3];
842 const QString driveList = get_file_path_drive_list();
843 wcscpy_s(drive, 3, L"?:");
844 for (const wchar_t *current = MUTILS_WCHR(driveList); *current; current++)
846 drive[0] = (*current);
847 if (QueryDosDeviceW(drive, buffer, MAX_PATH))
849 const QString prefix = MUTILS_QSTR(buffer);
850 if (path.startsWith(prefix, Qt::CaseInsensitive))
852 path.remove(0, prefix.length()).prepend(QLatin1Char(':')).prepend(QChar(*reinterpret_cast<const ushort*>(current)));
853 break;
859 static QString get_file_path_fallback(const HANDLE &hFile)
861 QString filePath;
863 const HANDLE hFileMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 1, NULL);
864 if (hFileMap)
866 void *const pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
867 if (pMem)
869 static const size_t BUFFSIZE = 2048;
870 wchar_t buffer[BUFFSIZE];
871 if (GetMappedFileNameW(GetCurrentProcess(), pMem, buffer, BUFFSIZE) > 0)
873 filePath = MUTILS_QSTR(buffer);
875 UnmapViewOfFile(pMem);
877 CloseHandle(hFileMap);
880 if (!filePath.isEmpty())
882 get_file_path_translate(filePath);
885 return filePath;
888 QString MUtils::OS::get_file_path(const int &fd)
890 if (fd >= 0)
892 const GetPathNameByHandleFun getPathNameByHandleFun = MUtils::Win32Utils::resolve<GetPathNameByHandleFun>(QLatin1String("kernel32"), QLatin1String("GetFinalPathNameByHandleW"));
893 if (!getPathNameByHandleFun)
895 return get_file_path_fallback((HANDLE)_get_osfhandle(fd));
898 const HANDLE handle = (HANDLE) _get_osfhandle(fd);
899 const DWORD len = getPathNameByHandleFun(handle, NULL, 0, FILE_NAME_OPENED);
900 if (len > 0)
902 if (wchar_t *const buffer = (wchar_t*)_malloca(sizeof(wchar_t) * len))
904 const DWORD ret = getPathNameByHandleFun(handle, buffer, len, FILE_NAME_OPENED);
905 if ((ret > 0) && (ret < len))
907 const QString path(MUTILS_QSTR(buffer));
908 return path.startsWith(QLatin1String("\\\\?\\")) ? path.mid(4) : path;
910 _freea(buffer);
915 return QString();
918 ///////////////////////////////////////////////////////////////////////////////
919 // PROCESS ELEVATION
920 ///////////////////////////////////////////////////////////////////////////////
922 static bool user_is_admin_helper(void)
924 HANDLE hToken = NULL;
925 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
927 return false;
930 DWORD dwSize = 0;
931 if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
933 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
935 CloseHandle(hToken);
936 return false;
940 PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
941 if(!lpGroups)
943 CloseHandle(hToken);
944 return false;
947 if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
949 free(lpGroups);
950 CloseHandle(hToken);
951 return false;
954 PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
955 if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
957 free(lpGroups);
958 CloseHandle(hToken);
959 return false;
962 bool bResult = false;
963 for(DWORD i = 0; i < lpGroups->GroupCount; i++)
965 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
967 bResult = true;
968 break;
972 FreeSid(lpSid);
973 free(lpGroups);
974 CloseHandle(hToken);
975 return bResult;
978 bool MUtils::OS::is_elevated(bool *bIsUacEnabled)
980 if(bIsUacEnabled)
982 *bIsUacEnabled = false;
985 bool bIsProcessElevated = false;
986 HANDLE hToken = NULL;
988 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
990 TOKEN_ELEVATION_TYPE tokenElevationType;
991 DWORD returnLength;
992 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
994 if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
996 switch(tokenElevationType)
998 case TokenElevationTypeDefault:
999 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1000 break;
1001 case TokenElevationTypeFull:
1002 qWarning("Process token elevation type: Full -> potential security risk!\n");
1003 bIsProcessElevated = true;
1004 if(bIsUacEnabled) *bIsUacEnabled = true;
1005 break;
1006 case TokenElevationTypeLimited:
1007 qDebug("Process token elevation type: Limited -> not elevated.\n");
1008 if(bIsUacEnabled) *bIsUacEnabled = true;
1009 break;
1010 default:
1011 qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
1012 break;
1015 else
1017 qWarning("GetTokenInformation() return an unexpected size!");
1020 CloseHandle(hToken);
1022 else
1024 qWarning("Failed to open process token!");
1027 return bIsProcessElevated;
1030 bool MUtils::OS::user_is_admin(void)
1032 bool isAdmin = false;
1034 //Check for process elevation and UAC support first!
1035 if(MUtils::OS::is_elevated(&isAdmin))
1037 qWarning("Process is elevated -> user is admin!");
1038 return true;
1041 //If not elevated and UAC is not available -> user must be in admin group!
1042 if(!isAdmin)
1044 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
1045 isAdmin = user_is_admin_helper();
1048 return isAdmin;
1051 ///////////////////////////////////////////////////////////////////////////////
1052 // NETWORK STATE
1053 ///////////////////////////////////////////////////////////////////////////////
1055 int MUtils::OS::network_status(void)
1057 DWORD dwFlags;
1058 const BOOL ret = IsNetworkAlive(&dwFlags);
1059 if(GetLastError() == 0)
1061 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
1063 return NETWORK_TYPE_ERR;
1066 ///////////////////////////////////////////////////////////////////////////////
1067 // MESSAGE HANDLER
1068 ///////////////////////////////////////////////////////////////////////////////
1070 bool MUtils::OS::handle_os_message(const void *const message, long *result)
1072 const MSG *const msg = reinterpret_cast<const MSG*>(message);
1074 switch(msg->message)
1076 case WM_QUERYENDSESSION:
1077 qWarning("WM_QUERYENDSESSION message received!");
1078 *result = MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION, false) ? TRUE : FALSE;
1079 return true;
1080 case WM_ENDSESSION:
1081 qWarning("WM_ENDSESSION message received!");
1082 if(msg->wParam == TRUE)
1084 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION, false);
1085 MUtils::GUI::force_quit();
1086 exit(1);
1088 *result = 0;
1089 return true;
1090 default:
1091 /*ignore this message and let Qt handle it*/
1092 return false;
1096 ///////////////////////////////////////////////////////////////////////////////
1097 // SLEEP
1098 ///////////////////////////////////////////////////////////////////////////////
1100 void MUtils::OS::sleep_ms(const size_t &duration)
1102 Sleep((DWORD) duration);
1105 ///////////////////////////////////////////////////////////////////////////////
1106 // EXECUTABLE CHECK
1107 ///////////////////////////////////////////////////////////////////////////////
1109 static int g_library_as_image_resource_supported = -1;
1110 static QReadWriteLock g_library_as_image_resource_supported_lock;
1112 static bool library_as_image_resource_supported()
1114 QReadLocker readLocker(&g_library_as_image_resource_supported_lock);
1115 if (g_library_as_image_resource_supported >= 0)
1117 return (g_library_as_image_resource_supported > 0);
1120 readLocker.unlock();
1121 QWriteLocker writeLocker(&g_library_as_image_resource_supported_lock);
1123 if (g_library_as_image_resource_supported < 0)
1125 g_library_as_image_resource_supported = 0;
1126 OSVERSIONINFOEXW osvi;
1127 if (rtl_get_version(&osvi))
1129 if ((osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osvi.dwMajorVersion >= 6U))
1131 g_library_as_image_resource_supported = 1;
1136 return (g_library_as_image_resource_supported > 0);
1139 bool MUtils::OS::is_executable_file(const QString &path)
1141 DWORD binaryType;
1142 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
1144 return ((binaryType == SCS_32BIT_BINARY) || (binaryType == SCS_64BIT_BINARY));
1147 const DWORD errorCode = GetLastError();
1148 qWarning("GetBinaryType() failed with error: 0x%08X", errorCode);
1149 return false;
1152 bool MUtils::OS::is_library_file(const QString &path)
1154 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);
1155 if (const HMODULE hMod = LoadLibraryEx(MUTILS_WCHR(QDir::toNativeSeparators(path)), NULL, flags))
1157 FreeLibrary(hMod);
1158 return true;
1161 const DWORD errorCode = GetLastError();
1162 qWarning("LoadLibraryEx() failed with error: 0x%08X", errorCode);
1163 return false;
1166 ///////////////////////////////////////////////////////////////////////////////
1167 // HIBERNATION / SHUTDOWN
1168 ///////////////////////////////////////////////////////////////////////////////
1170 bool MUtils::OS::is_hibernation_supported(void)
1172 bool hibernationSupported = false;
1174 SYSTEM_POWER_CAPABILITIES pwrCaps;
1175 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1177 if(GetPwrCapabilities(&pwrCaps))
1179 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1182 return hibernationSupported;
1185 bool MUtils::OS::shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1187 HANDLE hToken = NULL;
1189 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1191 TOKEN_PRIVILEGES privileges;
1192 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1193 privileges.PrivilegeCount = 1;
1194 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1196 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1198 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1200 if(hibernate)
1202 if(SetSuspendState(TRUE, TRUE, TRUE))
1204 return true;
1207 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1208 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1213 return false;
1216 ///////////////////////////////////////////////////////////////////////////////
1217 // FREE DISKSPACE
1218 ///////////////////////////////////////////////////////////////////////////////
1220 bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace)
1222 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1223 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1225 freeSpace = freeBytesAvailable.QuadPart;
1226 return true;;
1229 freeSpace = -1;
1230 return false;
1233 ///////////////////////////////////////////////////////////////////////////////
1234 // SHELL OPEN
1235 ///////////////////////////////////////////////////////////////////////////////
1237 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString &parameters, const QString &directory, const bool explore)
1239 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;
1242 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore)
1244 return shell_open(parent, url, QString(), QString(), explore);
1247 ///////////////////////////////////////////////////////////////////////////////
1248 // OPEN MEDIA FILE
1249 ///////////////////////////////////////////////////////////////////////////////
1251 bool MUtils::OS::open_media_file(const QString &mediaFilePath)
1253 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1254 const static wchar_t *registryKeys[3] =
1256 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1257 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1258 L"foobar2000"
1260 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1261 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1263 for(size_t i = 0; i < 3; i++)
1265 for(size_t j = 0; j < 2; j++)
1267 QString mplayerPath;
1268 HKEY registryKeyHandle = NULL;
1270 const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
1271 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
1273 for(size_t k = 0; k < 2; k++)
1275 wchar_t Buffer[4096];
1276 DWORD BuffSize = sizeof(wchar_t*) * 4096;
1277 DWORD DataType = REG_NONE;
1278 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1280 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1282 mplayerPath = MUTILS_QSTR(Buffer);
1283 break;
1287 RegCloseKey(registryKeyHandle);
1290 if(!mplayerPath.isEmpty())
1292 QDir mplayerDir(mplayerPath);
1293 if(mplayerDir.exists())
1295 for(size_t k = 0; k < 4; k++)
1297 if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
1299 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
1300 QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1301 return true;
1308 return false;
1311 ///////////////////////////////////////////////////////////////////////////////
1312 // DEBUGGER CHECK
1313 ///////////////////////////////////////////////////////////////////////////////
1315 static bool change_process_priority_helper(const HANDLE hProcess, const int priority)
1317 bool ok = false;
1319 switch(qBound(-2, priority, 2))
1321 case 2:
1322 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1323 break;
1324 case 1:
1325 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1327 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1329 break;
1330 case 0:
1331 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1332 break;
1333 case -1:
1334 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1336 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1338 break;
1339 case -2:
1340 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1341 break;
1344 return ok;
1347 bool MUtils::OS::change_process_priority(const int priority)
1349 return change_process_priority_helper(GetCurrentProcess(), priority);
1352 bool MUtils::OS::change_process_priority(const QProcess *proc, const int priority)
1354 if(Q_PID qPid = proc->pid())
1356 return change_process_priority_helper(qPid->hProcess, priority);
1358 else
1360 return false;
1364 ///////////////////////////////////////////////////////////////////////////////
1365 // PROCESS ID
1366 ///////////////////////////////////////////////////////////////////////////////
1368 quint32 MUtils::OS::process_id(void)
1370 return GetCurrentProcessId();
1373 quint32 MUtils::OS::process_id(const QProcess *const proc)
1375 PROCESS_INFORMATION *procInf = proc->pid();
1376 return (procInf) ? procInf->dwProcessId : 0;
1379 quint32 MUtils::OS::thread_id(void)
1381 return GetCurrentThreadId();
1384 quint32 MUtils::OS::thread_id(const QProcess *const proc)
1386 PROCESS_INFORMATION *procInf = proc->pid();
1387 return (procInf) ? procInf->dwThreadId : 0;
1390 ///////////////////////////////////////////////////////////////////////////////
1391 // PROCESS SUSPEND/RESUME
1392 ///////////////////////////////////////////////////////////////////////////////
1394 bool MUtils::OS::suspend_process(const QProcess *proc, const bool suspend)
1396 if(Q_PID pid = proc->pid())
1398 if(suspend)
1400 return (SuspendThread(pid->hThread) != ((DWORD) -1));
1402 else
1404 return (ResumeThread(pid->hThread) != ((DWORD) -1));
1407 else
1409 return false;
1413 ///////////////////////////////////////////////////////////////////////////////
1414 // SYSTEM TIMER
1415 ///////////////////////////////////////////////////////////////////////////////
1417 bool MUtils::OS::setup_timer_resolution(const quint32 &interval)
1419 return timeBeginPeriod(interval) == TIMERR_NOERROR;
1422 bool MUtils::OS::reset_timer_resolution(const quint32 &interval)
1424 return timeEndPeriod(interval) == TIMERR_NOERROR;
1427 ///////////////////////////////////////////////////////////////////////////////
1428 // SET FILE TIME
1429 ///////////////////////////////////////////////////////////////////////////////
1431 static QScopedPointer<QDateTime> s_epoch;
1432 static QReadWriteLock s_epochLock;
1434 static const QDateTime *get_epoch(void)
1436 QReadLocker rdLock(&s_epochLock);
1438 if (s_epoch.isNull())
1440 rdLock.unlock();
1441 QWriteLocker wrLock(&s_epochLock);
1442 if (s_epoch.isNull())
1444 s_epoch.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC));
1446 wrLock.unlock();
1447 rdLock.relock();
1450 return s_epoch.data();
1453 static FILETIME *qt_time_to_file_time(FILETIME *const fileTime, const QDateTime &dateTime)
1455 memset(fileTime, 0, sizeof(FILETIME));
1457 if (const QDateTime *const epoch = get_epoch())
1459 const qint64 msecs = epoch->msecsTo(dateTime);
1460 if (msecs > 0)
1462 const quint64 ticks = 10000U * quint64(msecs);
1463 fileTime->dwHighDateTime = ((ticks >> 32) & 0xFFFFFFFF);
1464 fileTime->dwLowDateTime = (ticks & 0xFFFFFFFF);
1465 return fileTime;
1469 return NULL;
1472 static bool set_file_time(const HANDLE hFile, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1474 FILETIME ftCreated, ftLastMod, ftLastAcc;
1476 FILETIME *const pCreated = created.isValid() ? qt_time_to_file_time(&ftCreated, created) : NULL;
1477 FILETIME *const pLastMod = lastMod.isValid() ? qt_time_to_file_time(&ftLastMod, lastMod) : NULL;
1478 FILETIME *const pLastAcc = lastAcc.isValid() ? qt_time_to_file_time(&ftLastAcc, lastAcc) : NULL;
1480 if (pCreated || pLastMod || pLastAcc)
1482 return (SetFileTime(hFile, pCreated, pLastAcc, pLastMod) != FALSE);
1485 return false;
1488 bool MUtils::OS::set_file_time(const QFile &file, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1490 const int fd = file.handle();
1491 if (fd >= 0)
1493 return set_file_time((HANDLE)_get_osfhandle(fd), created, lastMod, lastAcc);
1495 return false;
1498 bool MUtils::OS::set_file_time(const QString &path, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1500 const HANDLE hFile = CreateFileW(MUTILS_WCHR(path), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1501 bool okay = false;
1502 if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
1504 okay = set_file_time(hFile, created, lastMod, lastAcc);
1505 CloseHandle(hFile);
1507 return okay;
1510 ///////////////////////////////////////////////////////////////////////////////
1511 // CHECK KEY STATE
1512 ///////////////////////////////////////////////////////////////////////////////
1514 bool MUtils::OS::check_key_state_esc(void)
1516 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1519 ///////////////////////////////////////////////////////////////////////////////
1520 // SHELL CHANGE NOTIFICATION
1521 ///////////////////////////////////////////////////////////////////////////////
1523 void MUtils::OS::shell_change_notification(void)
1525 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
1528 ///////////////////////////////////////////////////////////////////////////////
1529 // WOW64 REDIRECTION
1530 ///////////////////////////////////////////////////////////////////////////////
1532 typedef BOOL (_stdcall *Wow64DisableWow64FsRedirectionFun)(void *OldValue);
1533 typedef BOOL (_stdcall *Wow64RevertWow64FsRedirectionFun )(void *OldValue);
1535 bool MUtils::OS::wow64fsredir_disable(void *oldValue)
1537 const Wow64DisableWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve<Wow64DisableWow64FsRedirectionFun>(QLatin1String("kernel32"), QLatin1String("Wow64DisableWow64FsRedirection"));
1538 if(wow64redir_disable)
1540 if (wow64redir_disable(oldValue))
1542 return true;
1545 return false;
1548 bool MUtils::OS::wow64fsredir_revert(void *oldValue)
1550 const Wow64RevertWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve<Wow64RevertWow64FsRedirectionFun>(QLatin1String("kernel32"), QLatin1String("Wow64RevertWow64FsRedirection"));
1551 if (wow64redir_disable)
1553 if (wow64redir_disable(oldValue))
1555 return true;
1558 return false;
1561 ///////////////////////////////////////////////////////////////////////////////
1562 // DEBUGGER CHECK
1563 ///////////////////////////////////////////////////////////////////////////////
1565 QString MUtils::OS::get_envvar(const QString &name)
1567 wchar_t *buffer = NULL;
1568 size_t requiredSize = 0, buffSize = 0;
1569 QString result;
1571 forever
1573 //Adjust the buffer size as required first!
1574 if (buffSize < requiredSize)
1576 if (buffer)
1578 _freea(buffer);
1580 if (!(buffer = (wchar_t*)_malloca(sizeof(wchar_t) * requiredSize)))
1582 break; /*out of memory error!*/
1584 buffSize = requiredSize;
1587 //Try to fetch the environment variable now
1588 const errno_t error = _wgetenv_s(&requiredSize, buffer, buffSize, MUTILS_WCHR(name));
1589 if(!error)
1591 if (requiredSize > 0)
1593 result = MUTILS_QSTR(buffer);
1595 break; /*done*/
1597 else if (error != ERANGE)
1599 break; /*somethging else went wrong!*/
1603 if (buffer)
1605 _freea(buffer);
1606 buffSize = 0;
1607 buffer = NULL;
1610 return result;
1613 bool MUtils::OS::set_envvar(const QString &name, const QString &value)
1615 if (!_wputenv_s(MUTILS_WCHR(name), MUTILS_WCHR(value)))
1617 return true;
1619 return false;
1622 ///////////////////////////////////////////////////////////////////////////////
1623 // DEBUGGER CHECK
1624 ///////////////////////////////////////////////////////////////////////////////
1626 #if (!(MUTILS_DEBUG))
1627 static __forceinline bool is_debugger_present(void)
1629 __try
1631 CloseHandle((HANDLE)((DWORD_PTR)-3));
1633 __except(1)
1635 return true;
1638 BOOL bHaveDebugger = FALSE;
1639 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
1641 if(bHaveDebugger) return true;
1644 return IsDebuggerPresent();
1646 static __forceinline bool check_debugger_helper(void)
1648 if(is_debugger_present())
1650 MUtils::OS::fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1651 return true;
1653 return false;
1655 #else
1656 #define check_debugger_helper() (false)
1657 #endif
1659 void MUtils::OS::check_debugger(void)
1661 check_debugger_helper();
1664 static volatile bool g_debug_check = check_debugger_helper();
1666 ///////////////////////////////////////////////////////////////////////////////
1667 // FATAL EXIT
1668 ///////////////////////////////////////////////////////////////////////////////
1670 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
1671 static volatile bool g_fatal_exit_flag = true;
1673 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
1675 MUtils::OS::system_message_err(L"GURU MEDITATION", (LPWSTR) lpParameter);
1676 return 0;
1679 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
1681 g_fatal_exit_lock.enter();
1683 if(!g_fatal_exit_flag)
1685 return; /*prevent recursive invocation*/
1688 g_fatal_exit_flag = false;
1690 if(g_main_thread_id != GetCurrentThreadId())
1692 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
1694 SuspendThread(hThreadMain); /*stop main thread*/
1698 if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL))
1700 WaitForSingleObject(hThread, INFINITE);
1703 for(;;)
1705 TerminateProcess(GetCurrentProcess(), 666);
1709 ///////////////////////////////////////////////////////////////////////////////