X-Git-Url: http://git.osdn.net/view?a=blobdiff_plain;f=src%2FOSSupport_Win32.cpp;h=bef14baf101b1a5492e4a49ea2b6c6a039616455;hb=6c7371b941640d6d0aab4db43ba12e83f7c247eb;hp=3df1dba5e11ee3ec30dd4adf5288d056e95a48d3;hpb=3ac2f782e39a3ec15d36dcf99adb958a880b7386;p=mutilities%2FMUtilities.git diff --git a/src/OSSupport_Win32.cpp b/src/OSSupport_Win32.cpp index 3df1dba..bef14ba 100644 --- a/src/OSSupport_Win32.cpp +++ b/src/OSSupport_Win32.cpp @@ -1,6 +1,6 @@ /////////////////////////////////////////////////////////////////////////////// // MuldeR's Utilities for Qt -// Copyright (C) 2004-2014 LoRd_MuldeR +// Copyright (C) 2004-2018 LoRd_MuldeR // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public @@ -19,31 +19,37 @@ // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// -#pragma once - //Win32 API #define WIN32_LEAN_AND_MEAN 1 #include -#include #include #include #include #include #include +#include +#pragma warning(push) +#pragma warning(disable:4091) //for MSVC2015 +#include +#pragma warning(pop) + +//CRT +#include //Internal #include #include #include #include "CriticalSection_Win32.h" +#include "Utils_Win32.h" //Qt #include #include -#include #include #include #include +#include //Main thread ID static const DWORD g_main_thread_id = GetCurrentThreadId(); @@ -73,10 +79,32 @@ void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *c // FETCH CLI ARGUMENTS /////////////////////////////////////////////////////////////////////////////// -static QReadWriteLock g_arguments_lock; -static QScopedPointer g_arguments_list; +static QReadWriteLock g_arguments_lock; +static QScopedPointer g_arguments_list; + +const QStringList MUtils::OS::crack_command_line(const QString &command_line) +{ + int nArgs = 0; + LPWSTR *szArglist = CommandLineToArgvW(command_line.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line), &nArgs); + + QStringList command_line_tokens; + if(NULL != szArglist) + { + for(int i = 0; i < nArgs; i++) + { + const QString argStr = MUTILS_QSTR(szArglist[i]).trimmed(); + if(!argStr.isEmpty()) + { + command_line_tokens << argStr; + } + } + LocalFree(szArglist); + } + + return command_line_tokens; +} -const QStringList &MUtils::OS::arguments(void) +const MUtils::OS::ArgumentMap &MUtils::OS::arguments(void) { QReadLocker readLock(&g_arguments_lock); @@ -95,19 +123,43 @@ const QStringList &MUtils::OS::arguments(void) return (*(g_arguments_list.data())); } - g_arguments_list.reset(new QStringList); - int nArgs = 0; - LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); + g_arguments_list.reset(new ArgumentMap()); + const QStringList argList = crack_command_line(); - if(NULL != szArglist) + if(!argList.isEmpty()) { - for(int i = 0; i < nArgs; i++) + const QString argPrefix = QLatin1String("--"); + const QChar separator = QLatin1Char('='); + + bool firstToken = true; + for(QStringList::ConstIterator iter = argList.constBegin(); iter != argList.constEnd(); iter++) { - *(g_arguments_list.data()) << MUTILS_QSTR(szArglist[i]); + if(firstToken) + { + firstToken = false; + continue; /*skip executable file name*/ + } + if(iter->startsWith(argPrefix)) + { + const QString argData = iter->mid(2).trimmed(); + if(argData.length() > 0) + { + const int separatorIndex = argData.indexOf(separator); + if(separatorIndex > 0) + { + const QString argKey = argData.left(separatorIndex).trimmed(); + const QString argVal = argData.mid(separatorIndex + 1).trimmed(); + g_arguments_list->insertMulti(argKey.toLower(), argVal); + } + else + { + g_arguments_list->insertMulti(argData.toLower(), QString()); + } + } + } } - LocalFree(szArglist); } - else + else if(argList.empty()) { qWarning("CommandLineToArgvW() has failed !!!"); } @@ -116,6 +168,102 @@ const QStringList &MUtils::OS::arguments(void) } /////////////////////////////////////////////////////////////////////////////// +// COPY FILE +/////////////////////////////////////////////////////////////////////////////// + +typedef struct _progress_callback_data_t +{ + MUtils::OS::progress_callback_t callback_function; + void *user_data; +} +progress_callback_data_t; + +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) +{ + if(const progress_callback_data_t *data = (progress_callback_data_t*) lpData) + { + const double progress = qBound(0.0, double(TotalBytesTransferred.QuadPart) / double(TotalFileSize.QuadPart), 1.0); + return data->callback_function(progress, data->user_data) ? PROGRESS_CONTINUE : PROGRESS_CANCEL; + } + return PROGRESS_CONTINUE; +} + +MUTILS_API bool MUtils::OS::copy_file(const QString &sourcePath, const QString &outputPath, const bool &overwrite, const progress_callback_t callback, void *const userData) +{ + progress_callback_data_t callback_data = { callback, userData }; + BOOL cancel = FALSE; + 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)); + + if(result == FALSE) + { + const DWORD errorCode = GetLastError(); + if(errorCode != ERROR_REQUEST_ABORTED) + { + qWarning("CopyFile() failed with error code 0x%08X!", errorCode); + } + else + { + qWarning("CopyFile() operation was abroted by user!"); + } + } + + return (result != FALSE); +} + +/////////////////////////////////////////////////////////////////////////////// +// GET FILE VERSION +/////////////////////////////////////////////////////////////////////////////// + +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) +{ + if(!GetFileVersionInfo(MUTILS_WCHR(fileName), 0, size, buffer)) + { + qWarning("GetFileVersionInfo() has failed, file version cannot be determined!"); + return false; + } + + VS_FIXEDFILEINFO *verInfo; + UINT verInfoLen; + if(!VerQueryValue(buffer, L"\\", (LPVOID*)(&verInfo), &verInfoLen)) + { + qWarning("VerQueryValue() has failed, file version cannot be determined!"); + return false; + } + + if(major) *major = quint16((verInfo->dwFileVersionMS >> 16) & 0x0000FFFF); + if(minor) *minor = quint16((verInfo->dwFileVersionMS) & 0x0000FFFF); + if(patch) *patch = quint16((verInfo->dwFileVersionLS >> 16) & 0x0000FFFF); + if(build) *build = quint16((verInfo->dwFileVersionLS) & 0x0000FFFF); + + return true; +} + +bool MUtils::OS::get_file_version(const QString fileName, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build) +{ + if(major) *major = 0U; if(minor) *minor = 0U; + if(patch) *patch = 0U; if(build) *build = 0U; + + const DWORD size = GetFileVersionInfoSize(MUTILS_WCHR(fileName), NULL); + if(size < 1) + { + qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!"); + return false; + } + + PVOID buffer = _malloca(size); + if(!buffer) + { + qWarning("Memory allocation has failed!"); + return false; + } + + const bool success = get_file_version_helper(fileName, buffer, size, major, minor, patch, build); + + _freea(buffer); + return success; +} + +/////////////////////////////////////////////////////////////////////////////// // OS VERSION DETECTION /////////////////////////////////////////////////////////////////////////////// @@ -138,18 +286,108 @@ g_os_version_lut[] = { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2" }, //7 { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012" }, //8 { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2" }, //8.1 - { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2014 (Preview)" }, //10 + { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2016" }, //10 { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" } }; +//OS version data dtructures +namespace MUtils +{ + namespace OS + { + namespace Version + { + //Comparision operators for os_version_t + bool os_version_t::operator== (const os_version_t &rhs) const { return (type == rhs.type) && (versionMajor == rhs.versionMajor) && ((versionMinor == rhs.versionMinor)); } + bool os_version_t::operator!= (const os_version_t &rhs) const { return (type != rhs.type) || (versionMajor != rhs.versionMajor) || ((versionMinor != rhs.versionMinor)); } + bool os_version_t::operator> (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor > rhs.versionMinor))); } + bool os_version_t::operator>= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >= rhs.versionMinor))); } + bool os_version_t::operator< (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor < rhs.versionMinor))); } + bool os_version_t::operator<= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <= rhs.versionMinor))); } + + //Known Windows NT versions + const os_version_t WINDOWS_WIN2K = { OS_WINDOWS, 5, 0, 2195, 0 }; // 2000 + const os_version_t WINDOWS_WINXP = { OS_WINDOWS, 5, 1, 2600, 0 }; // XP + const os_version_t WINDOWS_XPX64 = { OS_WINDOWS, 5, 2, 3790, 0 }; // XP_x64 + const os_version_t WINDOWS_VISTA = { OS_WINDOWS, 6, 0, 6000, 0 }; // Vista + const os_version_t WINDOWS_WIN70 = { OS_WINDOWS, 6, 1, 7600, 0 }; // 7 + const os_version_t WINDOWS_WIN80 = { OS_WINDOWS, 6, 2, 9200, 0 }; // 8 + const os_version_t WINDOWS_WIN81 = { OS_WINDOWS, 6, 3, 9600, 0 }; // 8.1 + const os_version_t WINDOWS_WN100 = { OS_WINDOWS, 10, 0, 10240, 0 }; // 10 + + //Unknown OS + const os_version_t UNKNOWN_OPSYS = { OS_UNKNOWN, 0, 0, 0, 0 }; // N/A + } + } +} + +static inline DWORD SAFE_ADD(const DWORD &a, const DWORD &b, const DWORD &limit = MAXDWORD) +{ + return ((a >= limit) || (b >= limit) || ((limit - a) <= b)) ? limit : (a + b); +} + + +static void initialize_os_version(OSVERSIONINFOEXW *const osInfo) +{ + memset(osInfo, 0, sizeof(OSVERSIONINFOEXW)); + osInfo->dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); +} + +static inline DWORD initialize_step_size(const DWORD &limit) +{ + DWORD result = 1; + while (result < limit) + { + result = SAFE_ADD(result, result); + } + return result; +} + +static bool rtl_get_version(OSVERSIONINFOEXW *const osInfo) +{ + typedef LONG(__stdcall *RtlGetVersion)(LPOSVERSIONINFOEXW); + if (const HMODULE ntdll = GetModuleHandleW(L"ntdll")) + { + if (const RtlGetVersion pRtlGetVersion = (RtlGetVersion)GetProcAddress(ntdll, "RtlGetVersion")) + { + initialize_os_version(osInfo); + if (pRtlGetVersion(osInfo) == 0) + { + return true; + } + } + } + + //Fallback + initialize_os_version(osInfo); + return (GetVersionExW((LPOSVERSIONINFOW)osInfo) != FALSE); +} + +static bool rtl_verify_version(OSVERSIONINFOEXW *const osInfo, const ULONG typeMask, const ULONGLONG condMask) +{ + typedef LONG(__stdcall *RtlVerifyVersionInfo)(LPOSVERSIONINFOEXW, ULONG, ULONGLONG); + if (const HMODULE ntdll = GetModuleHandleW(L"ntdll")) + { + if (const RtlVerifyVersionInfo pRtlVerifyVersionInfo = (RtlVerifyVersionInfo)GetProcAddress(ntdll, "RtlVerifyVersionInfo")) + { + if (pRtlVerifyVersionInfo(osInfo, typeMask, condMask) == 0) + { + return true; + } + } + } + + //Fallback + return (VerifyVersionInfoW(osInfo, typeMask, condMask) != FALSE); +} + static bool verify_os_version(const DWORD major, const DWORD minor) { OSVERSIONINFOEXW osvi; DWORDLONG dwlConditionMask = 0; + initialize_os_version(&osvi); //Initialize the OSVERSIONINFOEX structure - memset(&osvi, 0, sizeof(OSVERSIONINFOEXW)); - osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); osvi.dwMajorVersion = major; osvi.dwMinorVersion = minor; osvi.dwPlatformId = VER_PLATFORM_WIN32_NT; @@ -157,10 +395,10 @@ static bool verify_os_version(const DWORD major, const DWORD minor) //Initialize the condition mask VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL); VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL); - VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL); + VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL); // Perform the test - const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask); + const BOOL ret = rtl_verify_version(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask); //Error checking if(!ret) @@ -174,9 +412,71 @@ static bool verify_os_version(const DWORD major, const DWORD minor) return (ret != FALSE); } -static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride) +static bool verify_os_build(const DWORD build) +{ + OSVERSIONINFOEXW osvi; + DWORDLONG dwlConditionMask = 0; + initialize_os_version(&osvi); + + //Initialize the OSVERSIONINFOEX structure + osvi.dwBuildNumber = build; + osvi.dwPlatformId = VER_PLATFORM_WIN32_NT; + + //Initialize the condition mask + VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL); + VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL); + + // Perform the test + const BOOL ret = rtl_verify_version(&osvi, VER_BUILDNUMBER | VER_PLATFORMID, dwlConditionMask); + + //Error checking + if (!ret) + { + if (GetLastError() != ERROR_OLD_WIN_VERSION) + { + qWarning("VerifyVersionInfo() system call has failed!"); + } + } + + return (ret != FALSE); +} + +static bool verify_os_spack(const WORD spack) +{ + OSVERSIONINFOEXW osvi; + DWORDLONG dwlConditionMask = 0; + initialize_os_version(&osvi); + + //Initialize the OSVERSIONINFOEX structure + osvi.wServicePackMajor = spack; + osvi.dwPlatformId = VER_PLATFORM_WIN32_NT; + + //Initialize the condition mask + VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); + VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL); + + // Perform the test + const BOOL ret = rtl_verify_version(&osvi, VER_SERVICEPACKMAJOR | VER_PLATFORMID, dwlConditionMask); + + //Error checking + if (!ret) + { + if (GetLastError() != ERROR_OLD_WIN_VERSION) + { + qWarning("VerifyVersionInfo() system call has failed!"); + } + } + + return (ret != FALSE); +} + +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) { - *major = *minor = 0; + static const DWORD MAX_VERSION = MAXWORD; + static const DWORD MAX_BUILDNO = MAXINT; + static const DWORD MAX_SRVCPCK = MAXWORD; + + *major = *minor = *build = *spack = 0U; *pbOverride = false; //Initialize local variables @@ -185,7 +485,7 @@ static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool * osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW); //Try GetVersionEx() first - if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE) + if(rtl_get_version(&osvi) == FALSE) { qWarning("GetVersionEx() has failed, cannot detect Windows version!"); return false; @@ -196,40 +496,91 @@ static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool * { *major = osvi.dwMajorVersion; *minor = osvi.dwMinorVersion; + *build = osvi.dwBuildNumber; + *spack = osvi.wServicePackMajor; } else { - qWarning("Not running on Windows NT, unsupported operating system!"); - return false; + if (verify_os_version(4, 0)) + { + *major = 4; + *build = 1381; + *pbOverride = true; + } + else + { + qWarning("Not running on Windows NT, unsupported operating system!"); + return false; + } } - //Determine the real *major* version first - forever + //Major Version + for (DWORD nextMajor = (*major) + 1; nextMajor <= MAX_VERSION; nextMajor++) { - const DWORD nextMajor = (*major) + 1; - if(verify_os_version(nextMajor, 0)) + if (verify_os_version(nextMajor, 0)) { - *pbOverride = true; *major = nextMajor; *minor = 0; + *pbOverride = true; continue; } break; } - //Now also determine the real *minor* version - forever + //Minor Version + for (DWORD nextMinor = (*minor) + 1; nextMinor <= MAX_VERSION; nextMinor++) { - const DWORD nextMinor = (*minor) + 1; - if(verify_os_version((*major), nextMinor)) + if (verify_os_version((*major), nextMinor)) { - *pbOverride = true; *minor = nextMinor; + *pbOverride = true; continue; } break; } + //Build Version + if (verify_os_build(SAFE_ADD((*build), 1, MAX_BUILDNO))) + { + DWORD stepSize = initialize_step_size(MAX_BUILDNO); + for (DWORD nextBuildNo = SAFE_ADD((*build), stepSize, MAX_BUILDNO); (*build) < MAX_BUILDNO; nextBuildNo = SAFE_ADD((*build), stepSize, MAX_BUILDNO)) + { + if (verify_os_build(nextBuildNo)) + { + *build = nextBuildNo; + *pbOverride = true; + continue; + } + if (stepSize > 1) + { + stepSize = stepSize / 2; + continue; + } + break; + } + } + + //Service Pack + if (verify_os_spack(SAFE_ADD((*spack), 1, MAX_SRVCPCK))) + { + DWORD stepSize = initialize_step_size(MAX_SRVCPCK); + for (DWORD nextSPackNo = SAFE_ADD((*spack), stepSize, MAX_SRVCPCK); (*spack) < MAX_SRVCPCK; nextSPackNo = SAFE_ADD((*spack), stepSize, MAX_SRVCPCK)) + { + if (verify_os_spack(nextSPackNo)) + { + *build = nextSPackNo; + *pbOverride = true; + continue; + } + if (stepSize > 1) + { + stepSize = stepSize / 2; + continue; + } + break; + } + } + return true; } @@ -253,17 +604,19 @@ const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void) } //Detect OS version - unsigned int major, minor; bool overrideFlg; - if(get_real_os_version(&major, &minor, &overrideFlg)) + unsigned int major, minor, build, spack; bool overrideFlg; + if(get_real_os_version(&major, &minor, &build, &spack, &overrideFlg)) { g_os_version_info.type = Version::OS_WINDOWS; g_os_version_info.versionMajor = major; g_os_version_info.versionMinor = minor; + g_os_version_info.versionBuild = build; + g_os_version_info.versionSPack = spack; g_os_version_info.overrideFlag = overrideFlg; } else { - qWarning("Failed to determin the operating system version!"); + qWarning("Failed to determine the operating system version!"); } //Completed @@ -294,17 +647,8 @@ static QReadWriteLock g_wine_lock; static const bool detect_wine(void) { - bool is_wine = false; - - QLibrary ntdll("ntdll.dll"); - if(ntdll.load()) - { - if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) is_wine = true; - if(ntdll.resolve("wine_get_version") != NULL) is_wine = true; - ntdll.unload(); - } - - return is_wine; + void *const ptr = MUtils::Win32Utils::resolve(QLatin1String("ntdll"), QLatin1String("wine_get_version")); + return (ptr != NULL); } const bool &MUtils::OS::running_on_wine(void) @@ -339,16 +683,13 @@ const bool &MUtils::OS::running_on_wine(void) typedef QMap KFMap; typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath); -typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath); +typedef HRESULT (WINAPI *SHGetFolderPath_t) (HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath); static QScopedPointer g_known_folders_map; -static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath; -static SHGetFolderPath_t g_known_folders_fpGetFolderPath; static QReadWriteLock g_known_folders_lock; const QString &MUtils::OS::known_folder(known_folder_t folder_id) { - static const int CSIDL_FLAG_CREATE = 0x8000; typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t; struct @@ -407,22 +748,16 @@ const QString &MUtils::OS::known_folder(known_folder_t folder_id) //Initialize on first call if(g_known_folders_map.isNull()) { - QLibrary shell32("shell32.dll"); - if(shell32.load()) - { - g_known_folders_fpGetFolderPath = (SHGetFolderPath_t) shell32.resolve("SHGetFolderPathW"); - g_known_folders_fpGetKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath"); - } g_known_folders_map.reset(new QMap()); } QString folderPath; //Now try to get the folder path! - if(g_known_folders_fpGetKnownFolderPath) + if(const SHGetKnownFolderPath_t known_folders_fpGetKnownFolderPath = MUtils::Win32Utils::resolve(QLatin1String("shell32"), QLatin1String("SHGetKnownFolderPath"))) { WCHAR *path = NULL; - if(g_known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK) + if(known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK) { //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST); QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path))); @@ -433,10 +768,10 @@ const QString &MUtils::OS::known_folder(known_folder_t folder_id) CoTaskMemFree(path); } } - else if(g_known_folders_fpGetFolderPath) + else if(const SHGetFolderPath_t known_folders_fpGetFolderPath = MUtils::Win32Utils::resolve(QLatin1String("shell32"), QLatin1String("SHGetFolderPathW"))) { QScopedArrayPointer path(new WCHAR[4096]); - if(g_known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK) + if(known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK) { //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST); QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data()))); @@ -525,6 +860,117 @@ quint64 MUtils::OS::current_file_time(void) } /////////////////////////////////////////////////////////////////////////////// +// FILE PATH FROM FD +/////////////////////////////////////////////////////////////////////////////// + +typedef DWORD(_stdcall *GetPathNameByHandleFun)(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags); + +static QString get_file_path_drive_list(void) +{ + QString list; + const DWORD len = GetLogicalDriveStringsW(0, NULL); + if (len > 0) + { + if (wchar_t *const buffer = (wchar_t*) _malloca(sizeof(wchar_t) * len)) + { + const DWORD ret = GetLogicalDriveStringsW(len, buffer); + if ((ret > 0) && (ret < len)) + { + const wchar_t *ptr = buffer; + while (const size_t current_len = wcslen(ptr)) + { + list.append(QChar(*reinterpret_cast(ptr))); + ptr += (current_len + 1); + } + } + _freea(buffer); + } + } + return list; +} + +static void get_file_path_translate(QString &path) +{ + static const DWORD BUFSIZE = 2048; + wchar_t buffer[BUFSIZE], drive[3]; + + const QString driveList = get_file_path_drive_list(); + wcscpy_s(drive, 3, L"?:"); + for (const wchar_t *current = MUTILS_WCHR(driveList); *current; current++) + { + drive[0] = (*current); + if (QueryDosDeviceW(drive, buffer, MAX_PATH)) + { + const QString prefix = MUTILS_QSTR(buffer); + if (path.startsWith(prefix, Qt::CaseInsensitive)) + { + path.remove(0, prefix.length()).prepend(QLatin1Char(':')).prepend(QChar(*reinterpret_cast(current))); + break; + } + } + } +} + +static QString get_file_path_fallback(const HANDLE &hFile) +{ + QString filePath; + + const HANDLE hFileMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 1, NULL); + if (hFileMap) + { + void *const pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1); + if (pMem) + { + static const size_t BUFFSIZE = 2048; + wchar_t buffer[BUFFSIZE]; + if (GetMappedFileNameW(GetCurrentProcess(), pMem, buffer, BUFFSIZE) > 0) + { + filePath = MUTILS_QSTR(buffer); + } + UnmapViewOfFile(pMem); + } + CloseHandle(hFileMap); + } + + if (!filePath.isEmpty()) + { + get_file_path_translate(filePath); + } + + return filePath; +} + +QString MUtils::OS::get_file_path(const int &fd) +{ + if (fd >= 0) + { + const GetPathNameByHandleFun getPathNameByHandleFun = MUtils::Win32Utils::resolve(QLatin1String("kernel32"), QLatin1String("GetFinalPathNameByHandleW")); + if (!getPathNameByHandleFun) + { + return get_file_path_fallback((HANDLE)_get_osfhandle(fd)); + } + + const HANDLE handle = (HANDLE) _get_osfhandle(fd); + const DWORD len = getPathNameByHandleFun(handle, NULL, 0, FILE_NAME_OPENED); + if (len > 0) + { + if (wchar_t *const buffer = (wchar_t*)_malloca(sizeof(wchar_t) * len)) + { + const DWORD ret = getPathNameByHandleFun(handle, buffer, len, FILE_NAME_OPENED); + if ((ret > 0) && (ret < len)) + { + const QString path(MUTILS_QSTR(buffer)); + return path.startsWith(QLatin1String("\\\\?\\")) ? path.mid(4) : path; + } + _freea(buffer); + } + } + } + + return QString(); +} + +/////////////////////////////////////////////////////////////////////////////// // PROCESS ELEVATION /////////////////////////////////////////////////////////////////////////////// @@ -715,15 +1161,61 @@ void MUtils::OS::sleep_ms(const size_t &duration) // EXECUTABLE CHECK /////////////////////////////////////////////////////////////////////////////// +static int g_library_as_image_resource_supported = -1; +static QReadWriteLock g_library_as_image_resource_supported_lock; + +static bool library_as_image_resource_supported() +{ + QReadLocker readLocker(&g_library_as_image_resource_supported_lock); + if (g_library_as_image_resource_supported >= 0) + { + return (g_library_as_image_resource_supported > 0); + } + + readLocker.unlock(); + QWriteLocker writeLocker(&g_library_as_image_resource_supported_lock); + + if (g_library_as_image_resource_supported < 0) + { + g_library_as_image_resource_supported = 0; + OSVERSIONINFOEXW osvi; + if (rtl_get_version(&osvi)) + { + if ((osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osvi.dwMajorVersion >= 6U)) + { + g_library_as_image_resource_supported = 1; + } + } + } + + return (g_library_as_image_resource_supported > 0); +} + bool MUtils::OS::is_executable_file(const QString &path) { - bool bIsExecutable = false; DWORD binaryType; if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType)) { - bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY); + return ((binaryType == SCS_32BIT_BINARY) || (binaryType == SCS_64BIT_BINARY)); + } + + const DWORD errorCode = GetLastError(); + qWarning("GetBinaryType() failed with error: 0x%08X", errorCode); + return false; +} + +bool MUtils::OS::is_library_file(const QString &path) +{ + 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); + if (const HMODULE hMod = LoadLibraryEx(MUTILS_WCHR(QDir::toNativeSeparators(path)), NULL, flags)) + { + FreeLibrary(hMod); + return true; } - return bIsExecutable; + + const DWORD errorCode = GetLastError(); + qWarning("LoadLibraryEx() failed with error: 0x%08X", errorCode); + return false; } /////////////////////////////////////////////////////////////////////////////// @@ -794,12 +1286,127 @@ bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace) } /////////////////////////////////////////////////////////////////////////////// +// DRIVE TYPE +/////////////////////////////////////////////////////////////////////////////// + +static wchar_t get_drive_letter(const QString &path) +{ + QString nativePath = QDir::toNativeSeparators(path); + while (nativePath.startsWith("\\\\?\\") || nativePath.startsWith("\\\\.\\")) + { + nativePath = QDir::toNativeSeparators(nativePath.mid(4)); + } + if ((path.length() > 1) && (path[1] == QLatin1Char(':'))) + { + const wchar_t letter = static_cast(path[0].unicode()); + if (((letter >= 'A') && (letter <= 'Z')) || ((letter >= 'a') && (letter <= 'z'))) + { + return towupper(letter); + } + } + return L'\0'; /*invalid path spec*/ +} + +static QSet get_physical_drive_ids(const wchar_t drive_letter) +{ + QSet physical_drives; + wchar_t driveName[8]; + _snwprintf_s(driveName, 8, _TRUNCATE, L"\\\\.\\%c:", drive_letter); + const HANDLE hDrive = CreateFileW(driveName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + if (hDrive && (hDrive != INVALID_HANDLE_VALUE)) + { + const size_t BUFF_SIZE = sizeof(VOLUME_DISK_EXTENTS) + (32U * sizeof(DISK_EXTENT)); + VOLUME_DISK_EXTENTS *const diskExtents = (VOLUME_DISK_EXTENTS*)_malloca(BUFF_SIZE); + DWORD dwSize; + if (DeviceIoControl(hDrive, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, (LPVOID)diskExtents, (DWORD)BUFF_SIZE, (LPDWORD)&dwSize, NULL)) + { + for (DWORD index = 0U; index < diskExtents->NumberOfDiskExtents; ++index) + { + physical_drives.insert(diskExtents->Extents[index].DiskNumber); + } + } + _freea(diskExtents); + CloseHandle(hDrive); + } + return physical_drives; +} + +static bool incurs_seek_penalty(const DWORD device_id) +{ + wchar_t driveName[24]; + _snwprintf_s(driveName, 24, _TRUNCATE, L"\\\\?\\PhysicalDrive%u", device_id); + const HANDLE hDevice = CreateFileW(driveName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); + bool seeking_penalty = true; + if (hDevice && (hDevice != INVALID_HANDLE_VALUE)) + { + STORAGE_PROPERTY_QUERY spq; + DEVICE_SEEK_PENALTY_DESCRIPTOR dspd; + memset(&spq, 0, sizeof(STORAGE_PROPERTY_QUERY)); + spq.PropertyId = (STORAGE_PROPERTY_ID)StorageDeviceSeekPenaltyProperty; + spq.QueryType = PropertyStandardQuery; + DWORD dwSize; + if (DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY, (LPVOID)&spq, (DWORD)sizeof(spq), (LPVOID)&dspd, (DWORD)sizeof(dspd), (LPDWORD)&dwSize, NULL)) + { + seeking_penalty = dspd.IncursSeekPenalty; + } + CloseHandle(hDevice); + } + return seeking_penalty; +} + +static bool is_fast_seeking_drive(const wchar_t drive_letter) +{ + bool fast_seeking = false; + const QSet physical_drive_ids = get_physical_drive_ids(drive_letter); + if (!physical_drive_ids.empty()) + { + fast_seeking = true; + for (QSet::const_iterator iter = physical_drive_ids.constBegin(); iter != physical_drive_ids.constEnd(); ++iter) + { + fast_seeking = fast_seeking && (!incurs_seek_penalty(*iter)); + } + } + return fast_seeking; +} + +MUtils::OS::drive_type_t MUtils::OS::get_drive_type(const QString &path, bool *fast_seeking) +{ + drive_type_t driveType = DRIVE_TYPE_ERR; + const wchar_t driveLetter = get_drive_letter(path); + if (driveLetter) + { + wchar_t driveName[8]; + _snwprintf_s(driveName, 8, _TRUNCATE, L"\\\\.\\%c:\\", driveLetter); + switch (GetDriveTypeW(driveName)) + { + case DRIVE_REMOVABLE: driveType = DRIVE_TYPE_FDD; break; + case DRIVE_FIXED: driveType = DRIVE_TYPE_HDD; break; + case DRIVE_REMOTE: driveType = DRIVE_TYPE_NET; break; + case DRIVE_CDROM: driveType = DRIVE_TYPE_OPT; break; + case DRIVE_RAMDISK: driveType = DRIVE_TYPE_RAM; break; + } + } + if (fast_seeking) + { + if (driveType == DRIVE_TYPE_HDD) + { + *fast_seeking = is_fast_seeking_drive(driveLetter); + } + else + { + *fast_seeking = (driveType == DRIVE_TYPE_RAM); + } + } + return driveType; +} + +/////////////////////////////////////////////////////////////////////////////// // SHELL OPEN /////////////////////////////////////////////////////////////////////////////// bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString ¶meters, const QString &directory, const bool explore) { - 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; + return ((int) ShellExecuteW((parent ? reinterpret_cast(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; } bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore) @@ -928,10 +1535,49 @@ bool MUtils::OS::change_process_priority(const QProcess *proc, const int priorit // PROCESS ID /////////////////////////////////////////////////////////////////////////////// -quint32 MUtils::OS::process_id(const QProcess *proc) +quint32 MUtils::OS::process_id(void) +{ + return GetCurrentProcessId(); +} + +quint32 MUtils::OS::process_id(const QProcess *const proc) { PROCESS_INFORMATION *procInf = proc->pid(); - return (procInf) ? procInf->dwProcessId : NULL; + return (procInf) ? procInf->dwProcessId : 0; +} + +quint32 MUtils::OS::thread_id(void) +{ + return GetCurrentThreadId(); +} + +quint32 MUtils::OS::thread_id(const QProcess *const proc) +{ + PROCESS_INFORMATION *procInf = proc->pid(); + return (procInf) ? procInf->dwThreadId : 0; +} + +/////////////////////////////////////////////////////////////////////////////// +// PROCESS SUSPEND/RESUME +/////////////////////////////////////////////////////////////////////////////// + +bool MUtils::OS::suspend_process(const QProcess *proc, const bool suspend) +{ + if(Q_PID pid = proc->pid()) + { + if(suspend) + { + return (SuspendThread(pid->hThread) != ((DWORD) -1)); + } + else + { + return (ResumeThread(pid->hThread) != ((DWORD) -1)); + } + } + else + { + return false; + } } /////////////////////////////////////////////////////////////////////////////// @@ -949,6 +1595,201 @@ bool MUtils::OS::reset_timer_resolution(const quint32 &interval) } /////////////////////////////////////////////////////////////////////////////// +// SET FILE TIME +/////////////////////////////////////////////////////////////////////////////// + +static QScopedPointer s_epoch; +static QReadWriteLock s_epochLock; + +static const QDateTime *get_epoch(void) +{ + QReadLocker rdLock(&s_epochLock); + + if (s_epoch.isNull()) + { + rdLock.unlock(); + QWriteLocker wrLock(&s_epochLock); + if (s_epoch.isNull()) + { + s_epoch.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC)); + } + wrLock.unlock(); + rdLock.relock(); + } + + return s_epoch.data(); +} + +static FILETIME *qt_time_to_file_time(FILETIME *const fileTime, const QDateTime &dateTime) +{ + memset(fileTime, 0, sizeof(FILETIME)); + + if (const QDateTime *const epoch = get_epoch()) + { + const qint64 msecs = epoch->msecsTo(dateTime); + if (msecs > 0) + { + const quint64 ticks = 10000U * quint64(msecs); + fileTime->dwHighDateTime = ((ticks >> 32) & 0xFFFFFFFF); + fileTime->dwLowDateTime = (ticks & 0xFFFFFFFF); + return fileTime; + } + } + + return NULL; +} + +static bool set_file_time(const HANDLE hFile, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc) +{ + FILETIME ftCreated, ftLastMod, ftLastAcc; + + FILETIME *const pCreated = created.isValid() ? qt_time_to_file_time(&ftCreated, created) : NULL; + FILETIME *const pLastMod = lastMod.isValid() ? qt_time_to_file_time(&ftLastMod, lastMod) : NULL; + FILETIME *const pLastAcc = lastAcc.isValid() ? qt_time_to_file_time(&ftLastAcc, lastAcc) : NULL; + + if (pCreated || pLastMod || pLastAcc) + { + return (SetFileTime(hFile, pCreated, pLastAcc, pLastMod) != FALSE); + } + + return false; +} + +bool MUtils::OS::set_file_time(const QFile &file, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc) +{ + const int fd = file.handle(); + if (fd >= 0) + { + return set_file_time((HANDLE)_get_osfhandle(fd), created, lastMod, lastAcc); + } + return false; +} + +bool MUtils::OS::set_file_time(const QString &path, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc) +{ + const HANDLE hFile = CreateFileW(MUTILS_WCHR(path), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); + bool okay = false; + if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE)) + { + okay = set_file_time(hFile, created, lastMod, lastAcc); + CloseHandle(hFile); + } + return okay; +} + +/////////////////////////////////////////////////////////////////////////////// +// CHECK KEY STATE +/////////////////////////////////////////////////////////////////////////////// + +bool MUtils::OS::check_key_state_esc(void) +{ + return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0; +} + +/////////////////////////////////////////////////////////////////////////////// +// SHELL CHANGE NOTIFICATION +/////////////////////////////////////////////////////////////////////////////// + +void MUtils::OS::shell_change_notification(void) +{ + SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL); +} + +/////////////////////////////////////////////////////////////////////////////// +// WOW64 REDIRECTION +/////////////////////////////////////////////////////////////////////////////// + +typedef BOOL (_stdcall *Wow64DisableWow64FsRedirectionFun)(void *OldValue); +typedef BOOL (_stdcall *Wow64RevertWow64FsRedirectionFun )(void *OldValue); + +bool MUtils::OS::wow64fsredir_disable(void *oldValue) +{ + const Wow64DisableWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve(QLatin1String("kernel32"), QLatin1String("Wow64DisableWow64FsRedirection")); + if(wow64redir_disable) + { + if (wow64redir_disable(oldValue)) + { + return true; + } + } + return false; +} + +bool MUtils::OS::wow64fsredir_revert(void *oldValue) +{ + const Wow64RevertWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve(QLatin1String("kernel32"), QLatin1String("Wow64RevertWow64FsRedirection")); + if (wow64redir_disable) + { + if (wow64redir_disable(oldValue)) + { + return true; + } + } + return false; +} + +/////////////////////////////////////////////////////////////////////////////// +// DEBUGGER CHECK +/////////////////////////////////////////////////////////////////////////////// + +QString MUtils::OS::get_envvar(const QString &name) +{ + wchar_t *buffer = NULL; + size_t requiredSize = 0, buffSize = 0; + QString result; + + forever + { + //Adjust the buffer size as required first! + if (buffSize < requiredSize) + { + if (buffer) + { + _freea(buffer); + } + if (!(buffer = (wchar_t*)_malloca(sizeof(wchar_t) * requiredSize))) + { + break; /*out of memory error!*/ + } + buffSize = requiredSize; + } + + //Try to fetch the environment variable now + const errno_t error = _wgetenv_s(&requiredSize, buffer, buffSize, MUTILS_WCHR(name)); + if(!error) + { + if (requiredSize > 0) + { + result = MUTILS_QSTR(buffer); + } + break; /*done*/ + } + else if (error != ERANGE) + { + break; /*somethging else went wrong!*/ + } + } + + if (buffer) + { + _freea(buffer); + buffSize = 0; + buffer = NULL; + } + + return result; +} + +bool MUtils::OS::set_envvar(const QString &name, const QString &value) +{ + if (!_wputenv_s(MUTILS_WCHR(name), MUTILS_WCHR(value))) + { + return true; + } + return false; +} + +/////////////////////////////////////////////////////////////////////////////// // DEBUGGER CHECK /////////////////////////////////////////////////////////////////////////////// @@ -997,7 +1838,7 @@ static volatile bool g_debug_check = check_debugger_helper(); /////////////////////////////////////////////////////////////////////////////// static MUtils::Internal::CriticalSection g_fatal_exit_lock; -static volatile bool g_fatal_exit_flag = true; +static QAtomicInt g_fatal_exit_flag; static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter) { @@ -1009,13 +1850,11 @@ void MUtils::OS::fatal_exit(const wchar_t* const errorMessage) { g_fatal_exit_lock.enter(); - if(!g_fatal_exit_flag) + if(!g_fatal_exit_flag.testAndSetOrdered(0, 1)) { return; /*prevent recursive invocation*/ } - g_fatal_exit_flag = false; - if(g_main_thread_id != GetCurrentThreadId()) { if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id)) @@ -1024,10 +1863,14 @@ void MUtils::OS::fatal_exit(const wchar_t* const errorMessage) } } - if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL)) + if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID)errorMessage, 0, NULL)) { WaitForSingleObject(hThread, INFINITE); } + else + { + fatal_exit_helper((LPVOID)errorMessage); + } for(;;) {