static void NTPTimeToHostTime(const NTPTIME *pnt, HOSTTIME *pht) { ULARGE_INTEGER uli; uli.QuadPart = UInt32x32To64(ntohl(pnt->fractions), HOSTTIME_TICK); *pht = UInt32x32To64(ntohl(pnt->seconds), HOSTTIME_TICK) + uli.HighPart + ORG_DIFF; }
static PPH_STRING NetworkAdapterQueryLinkSpeed( _In_ HANDLE DeviceHandle ) { NDIS_OID opcode; IO_STATUS_BLOCK isb; NDIS_CO_LINK_SPEED result; // https://msdn.microsoft.com/en-us/library/windows/hardware/ff569593.aspx opcode = OID_GEN_LINK_SPEED; // OID_GEN_CO_LINK_SPEED memset(&result, 0, sizeof(NDIS_CO_LINK_SPEED)); if (NT_SUCCESS(NtDeviceIoControlFile( DeviceHandle, NULL, NULL, NULL, &isb, IOCTL_NDIS_QUERY_GLOBAL_STATS, &opcode, sizeof(NDIS_OID), &result, sizeof(result) ))) { return PhFormatSize(UInt32x32To64(result.Outbound, NDIS_UNIT_OF_MEASUREMENT) / BITS_IN_ONE_BYTE, -1); } return PhReferenceEmptyString(); }
void cnv_tar2win_time(time_t tartime, FILETIME *ftm) { #ifdef HAS_LIBC_CAL_FUNCS FILETIME ftLocal; SYSTEMTIME st; struct tm localt; localt = *localtime(&tartime); st.wYear = (WORD)localt.tm_year+1900; st.wMonth = (WORD)localt.tm_mon+1; /* 1 based, not 0 based */ st.wDayOfWeek = (WORD)localt.tm_wday; st.wDay = (WORD)localt.tm_mday; st.wHour = (WORD)localt.tm_hour; st.wMinute = (WORD)localt.tm_min; st.wSecond = (WORD)localt.tm_sec; st.wMilliseconds = 0; SystemTimeToFileTime(&st,&ftLocal); LocalFileTimeToFileTime(&ftLocal,ftm); #else // avoid casts further below LONGLONG *t = (LONGLONG *)ftm; // tartime == number of seconds since midnight Jan 1 1970 (00:00:00) // convert to equivalent 100 nanosecond intervals *t = UInt32x32To64(tartime, 10000000UL); // now base on 1601, add number of 100 nansecond intervals between 1601 & 1970 *t += HUNDREDSECINTERVAL; /* 116444736000000000i64; */ #endif }
//为一个系统时间增加指定的秒数 BOOL AddSeconds(CONST LPSYSTEMTIME lpSrcTime, LPSYSTEMTIME lpDestTime, int seconds) { UNION_FILETIME uFileTime; if(! SystemTimeToFileTime(lpSrcTime, (LPFILETIME)&uFileTime)) return FALSE; //在文件时间上加上指定的分钟(转化为。。) 文件时间的单位0.0000001 sec, (10^(-7) sec) //判断分钟的符号 if(seconds > 0) uFileTime.uint64 += UInt32x32To64(seconds, 10000000); else uFileTime.uint64 -= UInt32x32To64(-seconds, 10000000); return FileTimeToSystemTime((FILETIME*)&uFileTime, lpDestTime); }
/* If creation is false, the LastAccessTime will be set according to times->actime. Otherwise, CreationTime will be set. LastWriteTime is always set according to times->modtime. */ static int win_utime_creation(const char *path, const struct utimbuf *times, int creation) { wchar_t *winpath; int ret = 0; HANDLE h; ULARGE_INTEGER fti; FILETIME xtime, mtime; if (!strcmp("/", path)) { /* Emulate root */ errno = EROFS; return -1; } winpath = intpath2winpath(path); if (!winpath) { errno = EINVAL; return -1; } /* Unfortunately, we cannot use utime(), since it doesn't support directories. */ fti.QuadPart = UInt32x32To64(times->actime + FT70SEC, 10000000); xtime.dwHighDateTime = fti.HighPart; xtime.dwLowDateTime = fti.LowPart; fti.QuadPart = UInt32x32To64(times->modtime + FT70SEC, 10000000); mtime.dwHighDateTime = fti.HighPart; mtime.dwLowDateTime = fti.LowPart; h = CreateFileW(winpath, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL); if (!SetFileTime (h, creation ? &xtime : NULL, creation ? NULL : &xtime, &mtime)) { errno = EACCES; ret = -1; } CloseHandle(h); free(winpath); return ret; }
void PosixEpochToFileTime( unsigned long epochTime, FILETIME *fileTime ) { ULONGLONG timeNs = UInt32x32To64(epochTime, 10000000) + 116444736000000000; fileTime->dwLowDateTime = (DWORD)timeNs; fileTime->dwHighDateTime = (DWORD)(timeNs >> 32); }
BOOL APIENTRY SetMailslotInfo( IN HANDLE hMailslot, IN DWORD lReadTimeout ) /*++ Routine Description: This function will set the read timeout for the specified mailslot. Arguments: hMailslot - A handle to the mailslot. lReadTimeout - The new read timeout, in milliseconds. Return Value: TRUE - The operation was successful. FALSE/NULL - The operation failed. Extended error status is available using GetLastError. --*/ { NTSTATUS status; IO_STATUS_BLOCK ioStatusBlock; FILE_MAILSLOT_SET_INFORMATION mailslotInfo; LARGE_INTEGER timeout; if ( lReadTimeout == MAILSLOT_WAIT_FOREVER ) { timeout.HighPart = 0x7FFFFFFF; timeout.LowPart = 0xFFFFFFFF; } else { timeout.QuadPart = - (LONGLONG)UInt32x32To64( lReadTimeout, 10 * 1000 ); } mailslotInfo.ReadTimeout = &timeout; status = NtSetInformationFile( hMailslot, &ioStatusBlock, &mailslotInfo, sizeof( mailslotInfo ), FileMailslotSetInformation ); if ( !NT_SUCCESS( status ) ) { BaseSetLastNTError( status ); return ( FALSE ); } return TRUE; }
void DBWriteTimeTS(DWORD t, MCONTACT hcontact) { SYSTEMTIME st; FILETIME ft; ULONGLONG ll = UInt32x32To64(TimeZone_ToLocal(t), 10000000) + NUM100NANOSEC; ft.dwLowDateTime = (DWORD)ll; ft.dwHighDateTime = (DWORD)(ll >> 32); FileTimeToSystemTime(&ft, &st); db_set_dw(hcontact, S_MOD, "seenTS", t); _DBWriteTime(&st, hcontact); }
/*++ EpochToFileTime Convert a POSIX epoch time to a FILETIME structure. Arguments: epochTime - POSIX epoch time. fileTime - Pointer to a FILETIME structure. Return Value: None. --*/ void EpochToFileTime( long epochTime, FILETIME *fileTime ) { ULONGLONG timeNs; assert(fileTime != NULL); timeNs = UInt32x32To64(epochTime, 10000000) + 116444736000000000; fileTime->dwLowDateTime = (DWORD)timeNs; fileTime->dwHighDateTime = (DWORD)(timeNs >> 32); }
static NTSTATUS PhpWfmoThreadStart( _In_ PVOID Parameter ) { HANDLE eventHandle; LARGE_INTEGER timeout; eventHandle = Parameter; timeout.QuadPart = -(LONGLONG)UInt32x32To64(5, PH_TIMEOUT_SEC); NtWaitForMultipleObjects(1, &eventHandle, WaitAll, FALSE, &timeout); return STATUS_SUCCESS; }
ULONGLONG APIENTRY EngGetTickCount(VOID) { ULONG Multiplier; LARGE_INTEGER TickCount; /* Get the multiplier and current tick count */ KeQueryTickCount(&TickCount); Multiplier = SharedUserData->TickCountMultiplier; /* Convert to milliseconds and return */ return (Int64ShrlMod32(UInt32x32To64(Multiplier, TickCount.LowPart), 24) + (Multiplier * (TickCount.HighPart << 8))); }
BOOL CNktEvent::Wait(__in DWORD dwTimeout) { NTSTATUS nNtStatus; LARGE_INTEGER sLI, *lpLI; if (hEvent == NULL) return TRUE; if (dwTimeout != INFINITE) { sLI.QuadPart = UInt32x32To64(dwTimeout, -10000); lpLI = &sLI; } else { lpLI = NULL; } nNtStatus = NktNtWaitForSingleObject(hEvent, FALSE, lpLI); return (nNtStatus == WAIT_OBJECT_0) ? TRUE : FALSE; }
/* * @implemented */ ULONGLONG WINAPI GetTickCount64(VOID) { ULARGE_INTEGER TickCount; while (TRUE) { TickCount.HighPart = (ULONG)SharedUserData->TickCount.High1Time; TickCount.LowPart = SharedUserData->TickCount.LowPart; if (TickCount.HighPart == (ULONG)SharedUserData->TickCount.High2Time) break; YieldProcessor(); } return (UInt32x32To64(TickCount.LowPart, SharedUserData->TickCountMultiplier) >> 24) + (UInt32x32To64(TickCount.HighPart, SharedUserData->TickCountMultiplier) << 8); }
DWORD isSeen(MCONTACT hcontact, SYSTEMTIME *st) { FILETIME ft; ULONGLONG ll; DWORD res = db_get_dw(hcontact, S_MOD, "seenTS", 0); if (res) { if (st) { ll = UInt32x32To64(TimeZone_ToLocal(res), 10000000) + NUM100NANOSEC; ft.dwLowDateTime = (DWORD)ll; ft.dwHighDateTime = (DWORD)(ll >> 32); FileTimeToSystemTime(&ft, st); } return res; } SYSTEMTIME lst; memset(&lst, 0, sizeof(lst)); if (lst.wYear = db_get_w(hcontact, S_MOD, "Year", 0)) { if (lst.wMonth = db_get_w(hcontact, S_MOD, "Month", 0)) { if (lst.wDay = db_get_w(hcontact, S_MOD, "Day", 0)) { lst.wDayOfWeek = db_get_w(hcontact, S_MOD, "WeekDay", 0); lst.wHour = db_get_w(hcontact, S_MOD, "Hours", 0); lst.wMinute = db_get_w(hcontact, S_MOD, "Minutes", 0); lst.wSecond = db_get_w(hcontact, S_MOD, "Seconds", 0); if (SystemTimeToFileTime(&lst, &ft)) { ll = ((LONGLONG)ft.dwHighDateTime << 32) | ((LONGLONG)ft.dwLowDateTime); ll -= NUM100NANOSEC; ll /= 10000000; //perform LOCALTOTIMESTAMP res = (DWORD)ll - TimeZone_ToLocal(0); //nevel look for Year/Month/Day/Hour/Minute/Second again db_set_dw(hcontact, S_MOD, "seenTS", res); } } } } if (st) memcpy(st, &lst, sizeof(SYSTEMTIME)); return res; }
NTSTATUS SetWriteTimeout(PC0C_IO_PORT pIoPort, PIRP pIrp) { SERIAL_TIMEOUTS timeouts; BOOLEAN setTotal; ULONG multiplier; ULONG constant; KeCancelTimer(&pIoPort->timerWriteTotal); timeouts = pIoPort->timeouts; setTotal = FALSE; multiplier = 0; constant = 0; if (timeouts.WriteTotalTimeoutMultiplier || timeouts.WriteTotalTimeoutConstant) { setTotal = TRUE; multiplier = timeouts.WriteTotalTimeoutMultiplier; constant = timeouts.WriteTotalTimeoutConstant; } if (setTotal) { LARGE_INTEGER total; ULONG length; length = GetWriteLength(pIrp); total.QuadPart = ((LONGLONG)(UInt32x32To64(length, multiplier) + constant)) * -10000; KeSetTimer( &pIoPort->timerWriteTotal, total, &pIoPort->timerWriteTotalDpc); } return STATUS_PENDING; }
static NTSTATUS vol_get_drive_geometry(PDEVICE_OBJECT DeviceObject, PIRP Irp) { volume_device_extension* vde = DeviceObject->DeviceExtension; pdo_device_extension* pdode = vde->pdode; PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation(Irp); DISK_GEOMETRY* geom; UINT64 length; LIST_ENTRY* le; if (IrpSp->Parameters.DeviceIoControl.OutputBufferLength < sizeof(DISK_GEOMETRY)) return STATUS_BUFFER_TOO_SMALL; length = 0; ExAcquireResourceSharedLite(&pdode->child_lock, TRUE); le = pdode->children.Flink; while (le != &pdode->children) { volume_child* vc = CONTAINING_RECORD(le, volume_child, list_entry); length += vc->size; le = le->Flink; } ExReleaseResourceLite(&pdode->child_lock); geom = (DISK_GEOMETRY*)Irp->AssociatedIrp.SystemBuffer; geom->BytesPerSector = DeviceObject->SectorSize == 0 ? 0x200 : DeviceObject->SectorSize; geom->SectorsPerTrack = 0x3f; geom->TracksPerCylinder = 0xff; geom->Cylinders.QuadPart = length / (UInt32x32To64(geom->TracksPerCylinder, geom->SectorsPerTrack) * geom->BytesPerSector); geom->MediaType = DeviceObject->Characteristics & FILE_REMOVABLE_MEDIA ? RemovableMedia : FixedMedia; Irp->IoStatus.Information = sizeof(DISK_GEOMETRY); return STATUS_SUCCESS; }
// KB167296 void UnixTimeToFileTime(mir_time ts, LPFILETIME pft) { unsigned __int64 ll = UInt32x32To64(ts, 10000000) + 116444736000000000i64; pft->dwLowDateTime = (DWORD)ll; pft->dwHighDateTime = ll >> 32; }
/* Compute (a * b + d) / c */ LONGLONG WINAPI llMulDiv(LONGLONG a, LONGLONG b, LONGLONG c, LONGLONG d) { /* Compute the absolute values to avoid signed arithmetic problems */ ULARGE_INTEGER ua, ub; DWORDLONG uc; ua.QuadPart = (DWORDLONG)(a >= 0 ? a : -a); ub.QuadPart = (DWORDLONG)(b >= 0 ? b : -b); uc = (DWORDLONG)(c >= 0 ? c : -c); BOOL bSign = (a < 0) ^ (b < 0); /* Do long multiplication */ ULARGE_INTEGER p[2]; p[0].QuadPart = UInt32x32To64(ua.LowPart, ub.LowPart); /* This next computation cannot overflow into p[1].HighPart because the max number we can compute here is: (2 ** 32 - 1) * (2 ** 32 - 1) + // ua.LowPart * ub.LowPart (2 ** 32) * (2 ** 31) * (2 ** 32 - 1) * 2 // x.LowPart * y.HighPart * 2 == 2 ** 96 - 2 ** 64 + (2 ** 64 - 2 ** 33 + 1) == 2 ** 96 - 2 ** 33 + 1 < 2 ** 96 */ ULARGE_INTEGER x; x.QuadPart = UInt32x32To64(ua.LowPart, ub.HighPart) + UInt32x32To64(ua.HighPart, ub.LowPart) + p[0].HighPart; p[0].HighPart = x.LowPart; p[1].QuadPart = UInt32x32To64(ua.HighPart, ub.HighPart) + x.HighPart; if (d != 0) { ULARGE_INTEGER ud[2]; if (bSign) { ud[0].QuadPart = (DWORDLONG)(-d); if (d > 0) { /* -d < 0 */ ud[1].QuadPart = (DWORDLONG)(LONGLONG)-1; } else { ud[1].QuadPart = (DWORDLONG)0; } } else { ud[0].QuadPart = (DWORDLONG)d; if (d < 0) { ud[1].QuadPart = (DWORDLONG)(LONGLONG)-1; } else { ud[1].QuadPart = (DWORDLONG)0; } } /* Now do extended addition */ ULARGE_INTEGER uliTotal; /* Add ls DWORDs */ uliTotal.QuadPart = (DWORDLONG)ud[0].LowPart + p[0].LowPart; p[0].LowPart = uliTotal.LowPart; /* Propagate carry */ uliTotal.LowPart = uliTotal.HighPart; uliTotal.HighPart = 0; /* Add 2nd most ls DWORDs */ uliTotal.QuadPart += (DWORDLONG)ud[0].HighPart + p[0].HighPart; p[0].HighPart = uliTotal.LowPart; /* Propagate carry */ uliTotal.LowPart = uliTotal.HighPart; uliTotal.HighPart = 0; /* Add MS DWORDLONGs - no carry expected */ p[1].QuadPart += ud[1].QuadPart + uliTotal.QuadPart; /* Now see if we got a sign change from the addition */ if ((LONG)p[1].HighPart < 0) { bSign = !bSign; /* Negate the current value (ugh!) */ p[0].QuadPart = ~p[0].QuadPart; p[1].QuadPart = ~p[1].QuadPart; p[0].QuadPart += 1; p[1].QuadPart += (p[0].QuadPart == 0); } } /* Now for the division */ if (c < 0) { bSign = !bSign; } /* This will catch c == 0 and overflow */ if (uc <= p[1].QuadPart) { return bSign ? (LONGLONG)0x8000000000000000 : (LONGLONG)0x7FFFFFFFFFFFFFFF; } DWORDLONG ullResult; /* Do the division */ /* If the dividend is a DWORD_LONG use the compiler */ if (p[1].QuadPart == 0) { ullResult = p[0].QuadPart / uc; return bSign ? -(LONGLONG)ullResult : (LONGLONG)ullResult; } /* If the divisor is a DWORD then its simpler */ ULARGE_INTEGER ulic; ulic.QuadPart = uc; if (ulic.HighPart == 0) { ULARGE_INTEGER uliDividend; ULARGE_INTEGER uliResult; DWORD dwDivisor = (DWORD)uc; // ASSERT(p[1].HighPart == 0 && p[1].LowPart < dwDivisor); uliDividend.HighPart = p[1].LowPart; uliDividend.LowPart = p[0].HighPart; #ifndef USE_LARGEINT uliResult.HighPart = (DWORD)(uliDividend.QuadPart / dwDivisor); p[0].HighPart = (DWORD)(uliDividend.QuadPart % dwDivisor); uliResult.LowPart = 0; uliResult.QuadPart = p[0].QuadPart / dwDivisor + uliResult.QuadPart; #else /* NOTE - this routine will take exceptions if the result does not fit in a DWORD */ if (uliDividend.QuadPart >= (DWORDLONG)dwDivisor) { uliResult.HighPart = EnlargedUnsignedDivide( uliDividend, dwDivisor, &p[0].HighPart); } else { uliResult.HighPart = 0; } uliResult.LowPart = EnlargedUnsignedDivide( p[0], dwDivisor, NULL); #endif return bSign ? -(LONGLONG)uliResult.QuadPart : (LONGLONG)uliResult.QuadPart; } ullResult = 0; /* OK - do long division */ for (int i = 0; i < 64; i++) { ullResult <<= 1; /* Shift 128 bit p left 1 */ p[1].QuadPart <<= 1; if ((p[0].HighPart & 0x80000000) != 0) { p[1].LowPart++; } p[0].QuadPart <<= 1; /* Compare */ if (uc <= p[1].QuadPart) { p[1].QuadPart -= uc; ullResult += 1; } } return bSign ? - (LONGLONG)ullResult : (LONGLONG)ullResult; }
LONGLONG WINAPI Int64x32Div32(LONGLONG a, LONG b, LONG c, LONG d) { ULARGE_INTEGER ua; DWORD ub; DWORD uc; /* Compute the absolute values to avoid signed arithmetic problems */ ua.QuadPart = (DWORDLONG)(a >= 0 ? a : -a); ub = (DWORD)(b >= 0 ? b : -b); uc = (DWORD)(c >= 0 ? c : -c); BOOL bSign = (a < 0) ^ (b < 0); /* Do long multiplication */ ULARGE_INTEGER p0; DWORD p1; p0.QuadPart = UInt32x32To64(ua.LowPart, ub); if (ua.HighPart != 0) { ULARGE_INTEGER x; x.QuadPart = UInt32x32To64(ua.HighPart, ub) + p0.HighPart; p0.HighPart = x.LowPart; p1 = x.HighPart; } else { p1 = 0; } if (d != 0) { ULARGE_INTEGER ud0; DWORD ud1; if (bSign) { // // Cast d to LONGLONG first otherwise -0x80000000 sign extends // incorrectly // ud0.QuadPart = (DWORDLONG)(-(LONGLONG)d); if (d > 0) { /* -d < 0 */ ud1 = (DWORD)-1; } else { ud1 = (DWORD)0; } } else { ud0.QuadPart = (DWORDLONG)d; if (d < 0) { ud1 = (DWORD)-1; } else { ud1 = (DWORD)0; } } /* Now do extended addition */ ULARGE_INTEGER uliTotal; /* Add ls DWORDs */ uliTotal.QuadPart = (DWORDLONG)ud0.LowPart + p0.LowPart; p0.LowPart = uliTotal.LowPart; /* Propagate carry */ uliTotal.LowPart = uliTotal.HighPart; uliTotal.HighPart = 0; /* Add 2nd most ls DWORDs */ uliTotal.QuadPart += (DWORDLONG)ud0.HighPart + p0.HighPart; p0.HighPart = uliTotal.LowPart; /* Add MS DWORDLONGs - no carry expected */ p1 += ud1 + uliTotal.HighPart; /* Now see if we got a sign change from the addition */ if ((LONG)p1 < 0) { bSign = !bSign; /* Negate the current value (ugh!) */ p0.QuadPart = ~p0.QuadPart; p1 = ~p1; p0.QuadPart += 1; p1 += (p0.QuadPart == 0); } } /* Now for the division */ if (c < 0) { bSign = !bSign; } /* This will catch c == 0 and overflow */ if (uc <= p1) { return bSign ? (LONGLONG)0x8000000000000000 : (LONGLONG)0x7FFFFFFFFFFFFFFF; } /* Do the division */ /* If the divisor is a DWORD then its simpler */ ULARGE_INTEGER uliDividend; ULARGE_INTEGER uliResult; DWORD dwDivisor = uc; uliDividend.HighPart = p1; uliDividend.LowPart = p0.HighPart; /* NOTE - this routine will take exceptions if the result does not fit in a DWORD */ if (uliDividend.QuadPart >= (DWORDLONG)dwDivisor) { uliResult.HighPart = EnlargedUnsignedDivide( uliDividend, dwDivisor, &p0.HighPart); } else { uliResult.HighPart = 0; } uliResult.LowPart = EnlargedUnsignedDivide( p0, dwDivisor, NULL); return bSign ? -(LONGLONG)uliResult.QuadPart : (LONGLONG)uliResult.QuadPart; }
INT_PTR CALLBACK BtrfsDeviceResize::DeviceResizeDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { try { switch (uMsg) { case WM_INITDIALOG: { win_handle h; WCHAR s[255]; wstring t, u; EnableThemeDialogTexture(hwndDlg, ETDT_ENABLETAB); GetDlgItemTextW(hwndDlg, IDC_RESIZE_DEVICE_ID, s, sizeof(s) / sizeof(WCHAR)); wstring_sprintf(t, s, dev_id); SetDlgItemTextW(hwndDlg, IDC_RESIZE_DEVICE_ID, t.c_str()); h = CreateFileW(fn.c_str(), FILE_TRAVERSE | FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); if (h != INVALID_HANDLE_VALUE) { NTSTATUS Status; IO_STATUS_BLOCK iosb; btrfs_device *devices, *bd; ULONG devsize; bool found = false; HWND slider; devsize = 1024; devices = (btrfs_device*)malloc(devsize); while (true) { Status = NtFsControlFile(h, nullptr, nullptr, nullptr, &iosb, FSCTL_BTRFS_GET_DEVICES, nullptr, 0, devices, devsize); if (Status == STATUS_BUFFER_OVERFLOW) { devsize += 1024; free(devices); devices = (btrfs_device*)malloc(devsize); } else break; } if (!NT_SUCCESS(Status)) { free(devices); return false; } bd = devices; while (true) { if (bd->dev_id == dev_id) { memcpy(&dev_info, bd, sizeof(btrfs_device)); found = true; break; } if (bd->next_entry > 0) bd = (btrfs_device*)((uint8_t*)bd + bd->next_entry); else break; } if (!found) { free(devices); return false; } free(devices); GetDlgItemTextW(hwndDlg, IDC_RESIZE_CURSIZE, s, sizeof(s) / sizeof(WCHAR)); format_size(dev_info.size, u, true); wstring_sprintf(t, s, u.c_str()); SetDlgItemTextW(hwndDlg, IDC_RESIZE_CURSIZE, t.c_str()); new_size = dev_info.size; GetDlgItemTextW(hwndDlg, IDC_RESIZE_NEWSIZE, new_size_text, sizeof(new_size_text) / sizeof(WCHAR)); wstring_sprintf(t, new_size_text, u.c_str()); SetDlgItemTextW(hwndDlg, IDC_RESIZE_NEWSIZE, t.c_str()); slider = GetDlgItem(hwndDlg, IDC_RESIZE_SLIDER); SendMessageW(slider, TBM_SETRANGEMIN, false, 0); SendMessageW(slider, TBM_SETRANGEMAX, false, (LPARAM)(dev_info.max_size / 1048576)); SendMessageW(slider, TBM_SETPOS, true, (LPARAM)(new_size / 1048576)); } else return false; break; } case WM_COMMAND: switch (HIWORD(wParam)) { case BN_CLICKED: switch (LOWORD(wParam)) { case IDOK: do_resize(hwndDlg); return true; case IDCANCEL: EndDialog(hwndDlg, 0); return true; } break; } break; case WM_HSCROLL: { wstring t, u; new_size = UInt32x32To64(SendMessageW(GetDlgItem(hwndDlg, IDC_RESIZE_SLIDER), TBM_GETPOS, 0, 0), 1048576); format_size(new_size, u, true); wstring_sprintf(t, new_size_text, u.c_str()); SetDlgItemTextW(hwndDlg, IDC_RESIZE_NEWSIZE, t.c_str()); EnableWindow(GetDlgItem(hwndDlg, IDOK), new_size > 0 ? true : false); break; } } } catch (const exception& e) { error_message(hwndDlg, e.what()); } return false; }
void GetDrives (CDriveArray &array) { array.clear (); IShellFolder *psfDesktop; SHGetDesktopFolder(&psfDesktop); if(psfDesktop == NULL) return; LPITEMIDLIST pidlMyComputer; SHGetSpecialFolderLocation(NULL, CSIDL_DRIVES, &pidlMyComputer); if(pidlMyComputer == NULL) { psfDesktop->Release(); return; } IShellFolder *psfMyComputer; psfDesktop->BindToObject(pidlMyComputer, NULL, IID_IShellFolder, (LPVOID*)&psfMyComputer); if(psfMyComputer) { IEnumIDList* pEnum; if(SUCCEEDED(psfMyComputer->EnumObjects(NULL, SHCONTF_FOLDERS|SHCONTF_INCLUDEHIDDEN, &pEnum))) { ITEMIDLIST* pidl; DWORD dwFetched = 1; TCHAR path[MAX_PATH]; while(SUCCEEDED(pEnum->Next(1, &pidl, &dwFetched)) && dwFetched) { SHFILEINFO sfi; //LPITEMIDLIST pidl_full = Pidl_Concatenate (pidlMyComputer, pidl); LPITEMIDLIST pidl_full = ILCombine (pidlMyComputer, pidl); SHGetPathFromIDList (pidl_full, path); UINT nType = GetDriveType( path); // if( DRIVE_REMOVABLE < nType && nType <= DRIVE_RAMDISK ) if( nType != DRIVE_UNKNOWN && nType != DRIVE_NO_ROOT_DIR ) if(SHGetFileInfo((LPCTSTR)pidl_full, 0, &sfi, sizeof(sfi), SHGFI_PIDL | SHGFI_DISPLAYNAME | SHGFI_TYPENAME | SHGFI_SYSICONINDEX | SHGFI_SMALLICON | SHGFI_LINKOVERLAY)) { CDriveInfo info; info.m_Name = sfi.szDisplayName; info.m_Path = path; info.m_Type = sfi.szTypeName; info.m_nImage = sfi.iIcon; info.m_nType = nType; DWORD SectorsPerCluster; // sectors per cluster DWORD BytesPerSector; // bytes per sector DWORD NumberOfFreeClusters; // free clusters DWORD TotalNumberOfClusters; // total clusters // TRACE (L"%s %s\n", sfi.szDisplayName, path); if (nType != DRIVE_REMOVABLE ) if (GetDiskFreeSpace (path, &SectorsPerCluster, &BytesPerSector, &NumberOfFreeClusters, &TotalNumberOfClusters)) { DWORD BytesPerCluster = BytesPerSector * SectorsPerCluster; info.m_FreeSpace = UInt32x32To64(NumberOfFreeClusters, BytesPerCluster); info.m_TotalSize= UInt32x32To64(TotalNumberOfClusters, BytesPerCluster); } array.push_back (info); } } pEnum->Release (); } psfMyComputer->Release(); } CoTaskMemFree(pidlMyComputer); psfDesktop->Release(); }
/* Init the clock routines, this will optionally return the resolution */ void InitHiResClock(HiResClock* res) { HiResClock resolution; use_perfc = QueryPerformanceFrequency(&perfc_freq); if (use_perfc) { BOOL success; LARGE_INTEGER now, offset; #if !defined(_WINCE) && !defined(_WIN32_WCE) struct _timeb tb; #else SYSTEMTIME st; #endif /* This is fair */ assert(perfc_freq.HighPart == 0); /* So mark, whats the plan here? * * Well, we get the Performance Counter time, which is * in arbitary units from an arbitary start time. We * also get the current time in milliseconds since the * epoch. From these two values we work out the * difference between the Epoch and the time the * Performance Counter is counting from (in arbitary * units). When we later want to calculate a time we * add the value calculated here to the value returned * by the QueryPerformanceCounter, and this gives us * the time from the epoch in arbiary units. We can * then convert that to better units by dividing by * the value obtained by the call to * QueryPerformanceFrequency. */ success = QueryPerformanceCounter(&now); assert(success); #if !defined(_WINCE) && !defined(_WIN32_WCE) _ftime(&tb); offset.QuadPart = UInt32x32To64(tb.time , perfc_freq.LowPart / 2) * 2; offset.QuadPart += MulDiv(tb.millitm, (perfc_freq.LowPart / 2), 500); #else GetLocalTime(&st); { FILETIME ft; if ( SystemTimeToFileTime(&st,&ft) ) { offset.QuadPart = ((((__int64)ft.dwHighDateTime*0x100000000) + ft.dwLowDateTime) * perfc_freq.LowPart ) / 10000000; } } #endif perfc_offset.QuadPart = offset.QuadPart - now.QuadPart; resolution.tv_sec = 0; resolution.tv_nsec = 1000000000 / perfc_freq.LowPart; } else { resolution.tv_sec = 0; resolution.tv_nsec = 1000000; } time_lib_initialised = TRUE; if (res != NULL) *res = resolution; }
HRESULT ULongMult(ULONG ulMultiplicand, ULONG ulMultiplier, ULONG* pulResult) { ULONGLONG ull64Result = UInt32x32To64(ulMultiplicand, ulMultiplier); return ULongLongToULong(ull64Result, pulResult); }
/* * @implemented */ BOOL WINAPI WaitForDebugEvent(IN LPDEBUG_EVENT lpDebugEvent, IN DWORD dwMilliseconds) { LARGE_INTEGER WaitTime; PLARGE_INTEGER Timeout; DBGUI_WAIT_STATE_CHANGE WaitStateChange; NTSTATUS Status; /* Check if this is an infinite wait */ if (dwMilliseconds == INFINITE) { /* Under NT, this means no timer argument */ Timeout = NULL; } else { /* Otherwise, convert the time to NT Format */ WaitTime.QuadPart = UInt32x32To64(-10000, dwMilliseconds); Timeout = &WaitTime; } /* Loop while we keep getting interrupted */ do { /* Call the native API */ Status = DbgUiWaitStateChange(&WaitStateChange, Timeout); } while ((Status == STATUS_ALERTED) || (Status == STATUS_USER_APC)); /* Check if the wait failed */ if (!(NT_SUCCESS(Status)) || (Status == DBG_UNABLE_TO_PROVIDE_HANDLE)) { /* Set the error code and quit */ SetLastErrorByStatus(Status); return FALSE; } /* Check if we timed out */ if (Status == STATUS_TIMEOUT) { /* Fail with a timeout error */ SetLastError(ERROR_SEM_TIMEOUT); return FALSE; } /* Convert the structure */ Status = DbgUiConvertStateChangeStructure(&WaitStateChange, lpDebugEvent); if (!NT_SUCCESS(Status)) { /* Set the error code and quit */ SetLastErrorByStatus(Status); return FALSE; } /* Check what kind of event this was */ switch (lpDebugEvent->dwDebugEventCode) { /* New thread was created */ case CREATE_THREAD_DEBUG_EVENT: /* Setup the thread data */ SaveThreadHandle(lpDebugEvent->dwProcessId, lpDebugEvent->dwThreadId, lpDebugEvent->u.CreateThread.hThread); break; /* New process was created */ case CREATE_PROCESS_DEBUG_EVENT: /* Setup the process data */ SaveProcessHandle(lpDebugEvent->dwProcessId, lpDebugEvent->u.CreateProcessInfo.hProcess); /* Setup the thread data */ SaveThreadHandle(lpDebugEvent->dwProcessId, lpDebugEvent->dwThreadId, lpDebugEvent->u.CreateThread.hThread); break; /* Process was exited */ case EXIT_PROCESS_DEBUG_EVENT: /* Mark the thread data as such */ MarkProcessHandle(lpDebugEvent->dwProcessId); break; /* Thread was exited */ case EXIT_THREAD_DEBUG_EVENT: /* Mark the thread data */ MarkThreadHandle(lpDebugEvent->dwThreadId); break; /* Nothing to do for anything else */ default: break; } /* Return success */ return TRUE; }
VOID EtpNotifySharedGraph( __in NMHDR *Header ) { switch (Header->code) { case GCN_GETDRAWINFO: { PPH_GRAPH_GETDRAWINFO getDrawInfo = (PPH_GRAPH_GETDRAWINFO)Header; PPH_GRAPH_DRAW_INFO drawInfo = getDrawInfo->DrawInfo; ULONG i; drawInfo->Flags = PH_GRAPH_USE_GRID; GpuSection->Parameters->ColorSetupFunction(drawInfo, PhGetIntegerSetting(L"ColorPhysical"), 0); PhGraphStateGetDrawInfo( &SharedGraphState, getDrawInfo, EtGpuSharedHistory.Count ); if (!SharedGraphState.Valid) { for (i = 0; i < drawInfo->LineDataCount; i++) { SharedGraphState.Data1[i] = (FLOAT)PhGetItemCircularBuffer_ULONG(&EtGpuSharedHistory, i); } if (EtGpuSharedLimit != 0) { // Scale the data. PhxfDivideSingle2U( SharedGraphState.Data1, (FLOAT)EtGpuSharedLimit / PAGE_SIZE, drawInfo->LineDataCount ); } SharedGraphState.Valid = TRUE; } } break; case GCN_GETTOOLTIPTEXT: { PPH_GRAPH_GETTOOLTIPTEXT getTooltipText = (PPH_GRAPH_GETTOOLTIPTEXT)Header; if (getTooltipText->Index < getTooltipText->TotalCount) { if (SharedGraphState.TooltipIndex != getTooltipText->Index) { ULONG usedPages; usedPages = PhGetItemCircularBuffer_ULONG(&EtGpuSharedHistory, getTooltipText->Index); PhSwapReference2(&SharedGraphState.TooltipText, PhFormatString( L"Shared Memory: %s\n%s", PhaFormatSize(UInt32x32To64(usedPages, PAGE_SIZE), -1)->Buffer, ((PPH_STRING)PHA_DEREFERENCE(PhGetStatisticsTimeString(NULL, getTooltipText->Index)))->Buffer )); } getTooltipText->Text = SharedGraphState.TooltipText->sr; } } break; } }
BOOL BuildDrivesReport( IN HWND hWnd, IN UINT iDetailLevel ) /*++ Routine Description: Formats and adds DrivesData to the report buffer. Arguments: hWnd - Main window handle iDetailLevel - summary or complete details? Return Value: BOOL - TRUE if report is build successfully, FALSE otherwise. --*/ { TCHAR LogicalDrives[ MAX_PATH ], OutputBuffer[MAX_PATH], szBuffer[MAX_PATH], szBuffer2[MAX_PATH]; LPTSTR Drive; DWORD Chars; BOOL Success; UINT OldErrorMode; DRIVE_INFO di; LARGE_INTEGER LargeInt; TCHAR szTotalBytes [ 64 ], szFreeBytes [ 64 ]; if(_fIsRemote){ return(TRUE); } AddLineToReport( 1, RFO_SKIPLINE, NULL, NULL ); AddLineToReport( 0, RFO_SINGLELINE, (LPTSTR) GetString( IDS_DRIVES_REPORT ), NULL ); AddLineToReport( 0, RFO_SEPARATOR, NULL, NULL ); // // Retrieve the logical drive strings from the system. // Chars = GetLogicalDriveStrings( sizeof( LogicalDrives ), LogicalDrives ); DbgAssert(( Chars != 0 ) && ( Chars <= sizeof( LogicalDrives ))); Drive = LogicalDrives; // // Disable pop-ups (especially if there is no media in the // removable drives.) // OldErrorMode = SetErrorMode( SEM_FAILCRITICALERRORS ); while( *Drive ) { TCHAR VolumeNameBuffer[512]; TCHAR FileSystemNameBuffer[512]; TCHAR DriveLetter[3]; TCHAR szKB[64]; DriveLetter[ 0 ] = Drive [ 0 ]; DriveLetter[ 1 ] = Drive [ 1 ]; DriveLetter[ 2 ] = TEXT( '\\'); ZeroMemory( &di, sizeof(DRIVE_INFO)); // // Skip floppies // if ((Drive[0] == 'A') || (Drive[0] == 'B')) { Drive += _tcslen( Drive ) + 1; continue; } // // GetDrive info // _tcsncpy( di.DriveLetter, Drive, 4 ); GetDriveInfo( &di ); // // Skip empty drives // if (di.Clusters == 0) { Drive += _tcslen( Drive ) + 1; continue; } // // skip unknown types // if (( di.DriveType < DRIVE_REMOVABLE) || ( di.DriveType > DRIVE_CDROM )){ Drive += _tcslen( Drive ) + 1; continue; } // // Display summary information // lstrcpy(szBuffer, GetString( IDS_DRV_BASE + di.DriveType ) ); lstrcpy(szBuffer2, GetString( IDS_TOTAL_MB ) ); // // Calculate the total and free bytes (Use LargeInteger routines for large drives ( > 4G ) // LargeInt.QuadPart = UInt32x32To64( di.FreeClusters, (di.SectorsPerCluster * di.BytesPerSector) ); LargeInt.QuadPart = Int64ShraMod32(LargeInt.QuadPart, 10); lstrcpy( szFreeBytes, FormatLargeInteger( &LargeInt, FALSE )); LargeInt.QuadPart = UInt32x32To64( di.Clusters, (di.SectorsPerCluster * di.BytesPerSector) ); LargeInt.QuadPart = Int64ShraMod32(LargeInt.QuadPart, 10); lstrcpy( szTotalBytes, FormatLargeInteger( &LargeInt, FALSE )); lstrcpy( szKB, GetString( IDS_KB ) ); if (di.DriveType == DRIVE_REMOTE) { wsprintf(OutputBuffer, L"%.2s (%s - %s) %s %s %s %s %s, %s %s %s", di.DriveLetter, szBuffer, di.FileSystemNameBuffer, di.RemoteNameBuffer, di.VolumeNameBuffer, szBuffer2, szTotalBytes, szKB, GetString( IDS_FREE_MB ), szFreeBytes, szKB); AddLineToReport(0,RFO_SINGLELINE,OutputBuffer,NULL); } else { wsprintf(OutputBuffer, L"%s (%s - %s) %s %s %s %s, %s %s %s", di.DriveLetter, szBuffer, di.FileSystemNameBuffer, di.VolumeNameBuffer, szBuffer2, szTotalBytes, szKB, GetString( IDS_FREE_MB ), szFreeBytes, szKB); AddLineToReport(0,RFO_SINGLELINE,OutputBuffer,NULL); } // // If we are making a detailed report, display additional info // if (iDetailLevel == IDC_COMPLETE_REPORT) { wsprintf( szBuffer, L"%X - %X", HIWORD( di.VolumeSerialNumber ), LOWORD( di.VolumeSerialNumber )); AddLineToReport( SINGLE_INDENT, RFO_RPTLINE, (LPTSTR) GetString( IDS_DRIVE_SERIAL_NUM ), szBuffer ); wsprintf(szBuffer, L"%d", di.BytesPerSector); AddLineToReport( SINGLE_INDENT, RFO_RPTLINE, (LPTSTR) GetString( IDS_BYTES_PER_CLUSTER ), szBuffer ); wsprintf(szBuffer, L"%d", di.SectorsPerCluster); AddLineToReport( SINGLE_INDENT, RFO_RPTLINE, (LPTSTR) GetString( IDS_SECTORS_PER_CLUSTER ), szBuffer ); wsprintf(szBuffer, L"%d", di.MaximumComponentLength); AddLineToReport( SINGLE_INDENT, RFO_RPTLINE, (LPTSTR) GetString( IDS_CHARS_IN_FILENAME ), szBuffer ); } // // Examine the next logical drive. // Drive += _tcslen( Drive ) + 1; } // // Restore error mode // SetErrorMode (OldErrorMode); return TRUE; }
BOOL GeneralDriveDetailsDlgProc( IN HWND hWnd, IN UINT message, IN WPARAM wParam, IN LPARAM lParam ) /*++ Routine Description: GeneralDriveDetailsDlgProc supports the display of the General information tab of the Drive Details Property Dialog. Arguments: Standard DLGPROC entry. Return Value: BOOL - Depending on input message and processing options. --*/ { BOOL Success; LARGE_INTEGER LargeInt; HANDLE hIcon; switch( message ) { case WM_INITDIALOG: { int i; TCHAR szBuffer[ MAX_PATH ]; LPDRIVE_INFO DriveInfo; // // Retrieve and validate the DRIVE_INFO object. // DriveInfo = (LPDRIVE_INFO) ( ( LPPROPSHEETPAGE ) lParam)->lParam ; DbgPointerAssert( DriveInfo ); DbgAssert( CheckSignature( DriveInfo )); DbgAssert( DriveInfo->ValidDetails ); if( ( DriveInfo == NULL ) || ( ! CheckSignature( DriveInfo )) || ( ! DriveInfo->ValidDetails )) { EndDialog( hWnd, 0 ); return FALSE; } // // If the drive is remote, display its connection name in the title. // if( DriveInfo->DriveType == DRIVE_REMOTE ) { SetDlgItemText( hWnd, IDC_DRIVE_NAME, DriveInfo->RemoteNameBuffer ); } // // Set the appropriate Icon // hIcon = GetIcon (GetDriveImage(DriveInfo->DriveType), 32); if ( hIcon ) { hIcon = (HICON)SendDlgItemMessage(hWnd, IDC_DRIVE_ICON, STM_SETICON, (WPARAM)hIcon, 0L); if (hIcon) DestroyIcon(hIcon); } // // Fill in drive label // SetDlgItemText( hWnd, IDC_DRIVE_LABEL, DriveInfo->VolumeNameBuffer ); // // Fill in serial number // wsprintf( szBuffer, L"%X - %X", HIWORD( DriveInfo->VolumeSerialNumber ), LOWORD( DriveInfo->VolumeSerialNumber )); SetDlgItemText( hWnd, IDC_DRIVE_SERIAL_NUMBER, szBuffer ); // // Display the space statistics. // SetDlgItemText( hWnd, IDC_SECTORS_PER_CLUSTER, FormatBigInteger( DriveInfo->SectorsPerCluster, FALSE ) ); SetDlgItemText( hWnd, IDC_BYTES_PER_SECTOR, FormatBigInteger( DriveInfo->BytesPerSector, FALSE ) ); SetDlgItemText( hWnd, IDC_FREE_CLUSTERS, FormatBigInteger( DriveInfo->FreeClusters, FALSE ) ); SetDlgItemText( hWnd, IDC_USED_CLUSTERS, FormatBigInteger( DriveInfo->Clusters - DriveInfo->FreeClusters, FALSE ) ); SetDlgItemText( hWnd, IDC_TOTAL_CLUSTERS, FormatBigInteger( DriveInfo->Clusters, FALSE ) ); // // Use LargeInteger routines for large drives ( > 4G ) // LargeInt.QuadPart = UInt32x32To64( DriveInfo->FreeClusters, (DriveInfo->SectorsPerCluster * DriveInfo->BytesPerSector) ); SetDlgItemText( hWnd, IDC_FREE_BYTES, FormatLargeInteger( &LargeInt, FALSE ) ); LargeInt.QuadPart = UInt32x32To64( (DriveInfo->Clusters - DriveInfo->FreeClusters), (DriveInfo->SectorsPerCluster * DriveInfo->BytesPerSector) ); SetDlgItemText( hWnd, IDC_USED_BYTES, FormatLargeInteger( &LargeInt, FALSE ) ); LargeInt.QuadPart = UInt32x32To64( DriveInfo->Clusters, (DriveInfo->SectorsPerCluster * DriveInfo->BytesPerSector) ); SetDlgItemText( hWnd, IDC_TOTAL_BYTES, FormatLargeInteger( &LargeInt, FALSE ) ); return TRUE; } case WM_COMMAND: { switch( LOWORD( wParam )) { case IDOK: case IDCANCEL: EndDialog( hWnd, 1 ); return TRUE; } break; } } return( FALSE ); }
ARC_STATUS LowWriteSectors( IN ULONG VolumeId, IN ULONG SectorSize, IN ULONG StartingSector, IN ULONG NumberOfSectors, IN PVOID Buffer ) /*++ Routine Description: This routine write 'NumberOfSectors' sectors starting at sector 'StartingSector' on the volume with ID 'VolumeId'. Arguments: VolumeId - Supplies the ID for the volume. SectorSize - Supplies the number of bytes per sector. StartingSector - Supplies the starting sector for the write. NumberOfSectors - Supplies the number of sectors to write. Buffer - Supplies the sectors to write. Return Value: ArcSeek, ArcWrite, EIO, ESUCCESS --*/ { ARC_STATUS r; ULONG c; LARGE_INTEGER l; ULONG i; ULONG transfer; PCHAR buf; ULONG total; l.QuadPart = UInt32x32To64(StartingSector,SectorSize); buf = (PCHAR) Buffer; r = ArcSeek(VolumeId, &l, SeekAbsolute); if (r != ESUCCESS) { return r; } total = SectorSize*NumberOfSectors; for (i = 0; i < total; i += MAX_TRANSFER) { transfer = min(MAX_TRANSFER, total - i); r = ArcWrite(VolumeId, &buf[i], transfer, &c); if (r != ESUCCESS) { return r; } if (c != transfer) { return EIO; } } return ESUCCESS; }
VOID StatusBarUpdate( _In_ BOOLEAN ResetMaxWidths ) { static ULONG64 lastTickCount = 0; ULONG count; ULONG i; HDC hdc; BOOLEAN resetMaxWidths = FALSE; PPH_STRING text[MAX_STATUSBAR_ITEMS]; ULONG widths[MAX_STATUSBAR_ITEMS]; if (ProcessesUpdatedCount < 2) return; if (ResetMaxWidths) resetMaxWidths = TRUE; if (!StatusBarItemList || StatusBarItemList->Count == 0) { // The status bar doesn't cope well with 0 parts. widths[0] = -1; SendMessage(StatusBarHandle, SB_SETPARTS, 1, (LPARAM)widths); SendMessage(StatusBarHandle, SB_SETTEXT, 0, (LPARAM)L""); return; } hdc = GetDC(StatusBarHandle); SelectObject(hdc, (HFONT)SendMessage(StatusBarHandle, WM_GETFONT, 0, 0)); // Reset max. widths for Max. CPU Process and Max. I/O Process parts once in a while. { LARGE_INTEGER tickCount; PhQuerySystemTime(&tickCount); if (tickCount.QuadPart - lastTickCount >= 10 * PH_TICKS_PER_SEC) { resetMaxWidths = TRUE; lastTickCount = tickCount.QuadPart; } } count = 0; for (i = 0; i < StatusBarItemList->Count; i++) { SIZE size; ULONG width; PSTATUSBAR_ITEM statusItem; statusItem = StatusBarItemList->Items[i]; switch (statusItem->Id) { case ID_STATUS_CPUUSAGE: { text[count] = PhFormatString( L"CPU Usage: %.2f%%", (SystemStatistics.CpuKernelUsage + SystemStatistics.CpuUserUsage) * 100 ); } break; case ID_STATUS_COMMITCHARGE: { ULONG commitUsage = SystemStatistics.Performance->CommittedPages; FLOAT commitFraction = (FLOAT)commitUsage / SystemStatistics.Performance->CommitLimit * 100; text[count] = PhFormatString( L"Commit Charge: %s (%.2f%%)", PhaFormatSize(UInt32x32To64(commitUsage, PAGE_SIZE), -1)->Buffer, commitFraction ); } break; case ID_STATUS_PHYSICALMEMORY: { ULONG physicalUsage = PhSystemBasicInformation.NumberOfPhysicalPages - SystemStatistics.Performance->AvailablePages; FLOAT physicalFraction = (FLOAT)physicalUsage / PhSystemBasicInformation.NumberOfPhysicalPages * 100; text[count] = PhFormatString( L"Physical Memory: %s (%.2f%%)", PhaFormatSize(UInt32x32To64(physicalUsage, PAGE_SIZE), -1)->Buffer, physicalFraction ); } break; case ID_STATUS_FREEMEMORY: { ULONG physicalFree = SystemStatistics.Performance->AvailablePages; FLOAT physicalFreeFraction = (FLOAT)physicalFree / PhSystemBasicInformation.NumberOfPhysicalPages * 100; text[count] = PhFormatString( L"Free Memory: %s (%.2f%%)", PhaFormatSize(UInt32x32To64(physicalFree, PAGE_SIZE), -1)->Buffer, physicalFreeFraction ); } break; case ID_STATUS_NUMBEROFPROCESSES: { text[count] = PhConcatStrings2( L"Processes: ", PhaFormatUInt64(SystemStatistics.NumberOfProcesses, TRUE)->Buffer ); } break; case ID_STATUS_NUMBEROFTHREADS: { text[count] = PhConcatStrings2( L"Threads: ", PhaFormatUInt64(SystemStatistics.NumberOfThreads, TRUE)->Buffer ); } break; case ID_STATUS_NUMBEROFHANDLES: { text[count] = PhConcatStrings2( L"Handles: ", PhaFormatUInt64(SystemStatistics.NumberOfHandles, TRUE)->Buffer ); } break; case ID_STATUS_IO_RO: { text[count] = PhConcatStrings2( L"I/O R+O: ", PhaFormatSize(SystemStatistics.IoReadDelta.Delta + SystemStatistics.IoOtherDelta.Delta, -1)->Buffer ); } break; case ID_STATUS_IO_W: { text[count] = PhConcatStrings2( L"I/O W: ", PhaFormatSize(SystemStatistics.IoWriteDelta.Delta, -1)->Buffer ); } break; case ID_STATUS_MAX_CPU_PROCESS: { PPH_PROCESS_ITEM processItem; if (SystemStatistics.MaxCpuProcessId && (processItem = PhReferenceProcessItem(SystemStatistics.MaxCpuProcessId))) { if (!PH_IS_FAKE_PROCESS_ID(processItem->ProcessId)) { text[count] = PhFormatString( L"%s (%lu): %.2f%%", processItem->ProcessName->Buffer, HandleToUlong(processItem->ProcessId), processItem->CpuUsage * 100 ); } else { text[count] = PhFormatString( L"%s: %.2f%%", processItem->ProcessName->Buffer, processItem->CpuUsage * 100 ); } PhDereferenceObject(processItem); } else { text[count] = PhCreateString(L"-"); } } break; case ID_STATUS_MAX_IO_PROCESS: { PPH_PROCESS_ITEM processItem; if (SystemStatistics.MaxIoProcessId && (processItem = PhReferenceProcessItem(SystemStatistics.MaxIoProcessId))) { if (!PH_IS_FAKE_PROCESS_ID(processItem->ProcessId)) { text[count] = PhFormatString( L"%s (%lu): %s", processItem->ProcessName->Buffer, HandleToUlong(processItem->ProcessId), PhaFormatSize(processItem->IoReadDelta.Delta + processItem->IoWriteDelta.Delta + processItem->IoOtherDelta.Delta, -1)->Buffer ); } else { text[count] = PhFormatString( L"%s: %s", processItem->ProcessName->Buffer, PhaFormatSize(processItem->IoReadDelta.Delta + processItem->IoWriteDelta.Delta + processItem->IoOtherDelta.Delta, -1)->Buffer ); } PhDereferenceObject(processItem); } else { text[count] = PhCreateString(L"-"); } } break; case ID_STATUS_NUMBEROFVISIBLEITEMS: { HWND tnHandle = NULL; tnHandle = GetCurrentTreeNewHandle(); if (tnHandle) { ULONG visibleCount = 0; visibleCount = TreeNew_GetFlatNodeCount(tnHandle); text[count] = PhFormatString( L"Visible: %lu", visibleCount ); } else { text[count] = PhCreateString( L"Visible: N/A" ); } } break; case ID_STATUS_NUMBEROFSELECTEDITEMS: { HWND tnHandle = NULL; tnHandle = GetCurrentTreeNewHandle(); if (tnHandle) { ULONG visibleCount = 0; ULONG selectedCount = 0; visibleCount = TreeNew_GetFlatNodeCount(tnHandle); for (ULONG i = 0; i < visibleCount; i++) { if (TreeNew_GetFlatNode(tnHandle, i)->Selected) selectedCount++; } text[count] = PhFormatString( L"Selected: %lu", selectedCount ); } else { text[count] = PhCreateString( L"Selected: N/A" ); } } break; case ID_STATUS_INTERVALSTATUS: { ULONG interval; interval = PhGetIntegerSetting(L"UpdateInterval"); if (UpdateAutomatically) { switch (interval) { case 500: text[count] = PhCreateString(L"Interval: Fast"); break; case 1000: text[count] = PhCreateString(L"Interval: Normal"); break; case 2000: text[count] = PhCreateString(L"Interval: Below Normal"); break; case 5000: text[count] = PhCreateString(L"Interval: Slow"); break; case 10000: text[count] = PhCreateString(L"Interval: Very Slow"); break; } } else { text[count] = PhCreateString(L"Interval: Paused"); } } break; } if (resetMaxWidths) StatusBarMaxWidths[count] = 0; if (!GetTextExtentPoint32(hdc, text[count]->Buffer, (ULONG)text[count]->Length / sizeof(WCHAR), &size)) size.cx = 200; if (count != 0) widths[count] = widths[count - 1]; else widths[count] = 0; width = size.cx + 10; if (width <= StatusBarMaxWidths[count]) { width = StatusBarMaxWidths[count]; } else { StatusBarMaxWidths[count] = width; } widths[count] += width; count++; } ReleaseDC(StatusBarHandle, hdc); SendMessage(StatusBarHandle, SB_SETPARTS, count, (LPARAM)widths); for (i = 0; i < count; i++) { SendMessage(StatusBarHandle, SB_SETTEXT, i, (LPARAM)text[i]->Buffer); PhDereferenceObject(text[i]); } }
INT_PTR CALLBACK EtpGpuPageDlgProc( _In_ HWND hwndDlg, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ) { LPPROPSHEETPAGE propSheetPage; PPH_PROCESS_PROPPAGECONTEXT propPageContext; PPH_PROCESS_ITEM processItem; PET_GPU_CONTEXT context; if (PhPropPageDlgProcHeader(hwndDlg, uMsg, lParam, &propSheetPage, &propPageContext, &processItem)) { context = propPageContext->Context; } else { return FALSE; } switch (uMsg) { case WM_INITDIALOG: { ULONG sampleCount; sampleCount = PhGetIntegerSetting(L"SampleCount"); context = PhAllocate(sizeof(ET_GPU_CONTEXT)); memset(context, 0, sizeof(ET_GPU_CONTEXT)); context->WindowHandle = hwndDlg; context->Block = EtGetProcessBlock(processItem); context->Enabled = TRUE; context->GpuGroupBox = GetDlgItem(hwndDlg, IDC_GROUPGPU); context->MemGroupBox = GetDlgItem(hwndDlg, IDC_GROUPMEM); context->SharedGroupBox = GetDlgItem(hwndDlg, IDC_GROUPSHARED); propPageContext->Context = context; PhInitializeLayoutManager(&context->LayoutManager, hwndDlg); PhInitializeGraphState(&context->GpuGraphState); PhInitializeGraphState(&context->MemoryGraphState); PhInitializeGraphState(&context->MemorySharedGraphState); PhInitializeCircularBuffer_FLOAT(&context->GpuHistory, sampleCount); PhInitializeCircularBuffer_ULONG(&context->MemoryHistory, sampleCount); PhInitializeCircularBuffer_ULONG(&context->MemorySharedHistory, sampleCount); GpuPropCreateGraphs(context); GpuPropCreatePanel(context); GpuPropUpdateInfo(context); GpuPropUpdatePanel(context); PhRegisterCallback( &PhProcessesUpdatedEvent, ProcessesUpdatedHandler, context, &context->ProcessesUpdatedRegistration ); } break; case WM_DESTROY: { PhDeleteLayoutManager(&context->LayoutManager); PhDeleteGraphState(&context->GpuGraphState); PhDeleteGraphState(&context->MemoryGraphState); PhDeleteGraphState(&context->MemorySharedGraphState); PhDeleteCircularBuffer_FLOAT(&context->GpuHistory); PhDeleteCircularBuffer_ULONG(&context->MemoryHistory); PhDeleteCircularBuffer_ULONG(&context->MemorySharedHistory); if (context->GpuGraphHandle) DestroyWindow(context->GpuGraphHandle); if (context->MemGraphHandle) DestroyWindow(context->MemGraphHandle); if (context->SharedGraphHandle) DestroyWindow(context->SharedGraphHandle); if (context->PanelHandle) DestroyWindow(context->PanelHandle); PhUnregisterCallback(&PhProcessesUpdatedEvent, &context->ProcessesUpdatedRegistration); PhFree(context); PhPropPageDlgProcDestroy(hwndDlg); } break; case WM_SHOWWINDOW: { if (PhBeginPropPageLayout(hwndDlg, propPageContext)) PhEndPropPageLayout(hwndDlg, propPageContext); } break; case WM_NOTIFY: { LPNMHDR header = (LPNMHDR)lParam; switch (header->code) { case PSN_SETACTIVE: context->Enabled = TRUE; break; case PSN_KILLACTIVE: context->Enabled = FALSE; break; case GCN_GETDRAWINFO: { PPH_GRAPH_GETDRAWINFO getDrawInfo = (PPH_GRAPH_GETDRAWINFO)header; PPH_GRAPH_DRAW_INFO drawInfo = getDrawInfo->DrawInfo; if (header->hwndFrom == context->GpuGraphHandle) { if (PhGetIntegerSetting(L"GraphShowText")) { HDC hdc; PhMoveReference(&context->GpuGraphState.Text, PhFormatString( L"%.2f%%", context->CurrentGpuUsage * 100 )); hdc = Graph_GetBufferedContext(context->GpuGraphHandle); SelectObject(hdc, PhApplicationFont); PhSetGraphText(hdc, drawInfo, &context->GpuGraphState.Text->sr, &NormalGraphTextMargin, &NormalGraphTextPadding, PH_ALIGN_TOP | PH_ALIGN_LEFT); } else { drawInfo->Text.Buffer = NULL; } drawInfo->Flags = PH_GRAPH_USE_GRID; PhSiSetColorsGraphDrawInfo(drawInfo, PhGetIntegerSetting(L"ColorCpuKernel"), 0); PhGraphStateGetDrawInfo(&context->GpuGraphState, getDrawInfo, context->GpuHistory.Count); if (!context->GpuGraphState.Valid) { PhCopyCircularBuffer_FLOAT(&context->GpuHistory, context->GpuGraphState.Data1, drawInfo->LineDataCount); context->GpuGraphState.Valid = TRUE; } } else if (header->hwndFrom == context->MemGraphHandle) { if (PhGetIntegerSetting(L"GraphShowText")) { HDC hdc; PhMoveReference(&context->MemoryGraphState.Text, PhFormatString( L"%s", PhaFormatSize(UInt32x32To64(context->CurrentMemUsage, PAGE_SIZE), -1)->Buffer )); hdc = Graph_GetBufferedContext(context->MemGraphHandle); SelectObject(hdc, PhApplicationFont); PhSetGraphText( hdc, drawInfo, &context->MemoryGraphState.Text->sr, &NormalGraphTextMargin, &NormalGraphTextPadding, PH_ALIGN_TOP | PH_ALIGN_LEFT ); } else { drawInfo->Text.Buffer = NULL; } drawInfo->Flags = PH_GRAPH_USE_GRID; PhSiSetColorsGraphDrawInfo(drawInfo, PhGetIntegerSetting(L"ColorPhysical"), 0); PhGraphStateGetDrawInfo( &context->MemoryGraphState, getDrawInfo, context->MemoryHistory.Count ); if (!context->MemoryGraphState.Valid) { ULONG i = 0; for (i = 0; i < drawInfo->LineDataCount; i++) { context->MemoryGraphState.Data1[i] = (FLOAT)PhGetItemCircularBuffer_ULONG(&context->MemoryHistory, i); } if (EtGpuDedicatedLimit != 0) { PhDivideSinglesBySingle( context->MemoryGraphState.Data1, (FLOAT)EtGpuDedicatedLimit / PAGE_SIZE, drawInfo->LineDataCount ); } context->MemoryGraphState.Valid = TRUE; } } else if (header->hwndFrom == context->SharedGraphHandle) { if (PhGetIntegerSetting(L"GraphShowText")) { HDC hdc; PhMoveReference(&context->MemorySharedGraphState.Text, PhFormatString( L"%s", PhaFormatSize(UInt32x32To64(context->CurrentMemSharedUsage, PAGE_SIZE), -1)->Buffer )); hdc = Graph_GetBufferedContext(context->SharedGraphHandle); SelectObject(hdc, PhApplicationFont); PhSetGraphText(hdc, drawInfo, &context->MemorySharedGraphState.Text->sr, &NormalGraphTextMargin, &NormalGraphTextPadding, PH_ALIGN_TOP | PH_ALIGN_LEFT); } else { drawInfo->Text.Buffer = NULL; } drawInfo->Flags = PH_GRAPH_USE_GRID; PhSiSetColorsGraphDrawInfo(drawInfo, PhGetIntegerSetting(L"ColorPrivate"), 0); PhGraphStateGetDrawInfo( &context->MemorySharedGraphState, getDrawInfo, context->MemorySharedHistory.Count ); if (!context->MemorySharedGraphState.Valid) { ULONG i = 0; for (i = 0; i < drawInfo->LineDataCount; i++) { context->MemorySharedGraphState.Data1[i] = (FLOAT)PhGetItemCircularBuffer_ULONG(&context->MemorySharedHistory, i); } if (EtGpuSharedLimit != 0) { PhDivideSinglesBySingle( context->MemorySharedGraphState.Data1, (FLOAT)EtGpuSharedLimit / PAGE_SIZE, drawInfo->LineDataCount ); } context->MemorySharedGraphState.Valid = TRUE; } } } break; case GCN_GETTOOLTIPTEXT: { PPH_GRAPH_GETTOOLTIPTEXT getTooltipText = (PPH_GRAPH_GETTOOLTIPTEXT)lParam; if (getTooltipText->Index < getTooltipText->TotalCount) { if (header->hwndFrom == context->GpuGraphHandle) { if (context->GpuGraphState.TooltipIndex != getTooltipText->Index) { FLOAT gpuUsage = PhGetItemCircularBuffer_FLOAT( &context->GpuHistory, getTooltipText->Index ); PhMoveReference(&context->GpuGraphState.TooltipText, PhFormatString( L"%.2f%%", gpuUsage * 100 )); } getTooltipText->Text = context->GpuGraphState.TooltipText->sr; } else if (header->hwndFrom == context->MemGraphHandle) { if (context->MemoryGraphState.TooltipIndex != getTooltipText->Index) { ULONG gpuMemory = PhGetItemCircularBuffer_ULONG( &context->MemoryHistory, getTooltipText->Index ); PhMoveReference(&context->MemoryGraphState.TooltipText, PhFormatSize(UInt32x32To64(gpuMemory, PAGE_SIZE), -1) ); } getTooltipText->Text = context->MemoryGraphState.TooltipText->sr; } else if (header->hwndFrom == context->SharedGraphHandle) { if (context->MemorySharedGraphState.TooltipIndex != getTooltipText->Index) { ULONG gpuSharedMemory = PhGetItemCircularBuffer_ULONG( &context->MemorySharedHistory, getTooltipText->Index ); PhMoveReference(&context->MemorySharedGraphState.TooltipText, PhFormatSize(UInt32x32To64(gpuSharedMemory, PAGE_SIZE), -1) ); } getTooltipText->Text = context->MemorySharedGraphState.TooltipText->sr; } } } break; } } break; case MSG_UPDATE: { GpuPropUpdateInfo(context); GpuPropUpdateGraphs(context); GpuPropUpdatePanel(context); } break; case WM_SIZE: { GpuPropLayoutGraphs(context); } break; } return FALSE; }