void AFSTagInitialLogEntry() { LARGE_INTEGER liTime, liLocalTime; TIME_FIELDS timeFields; KeQuerySystemTime( &liTime); ExSystemTimeToLocalTime( &liTime, &liLocalTime); RtlTimeToTimeFields( &liLocalTime, &timeFields); AFSDbgLogMsg( 0, 0, "AFS Log Initialized %d-%d-%d %d:%d Level %d Subsystems %08lX\n", timeFields.Month, timeFields.Day, timeFields.Year, timeFields.Hour, timeFields.Minute, AFSTraceLevel, AFSTraceComponent); return; }
// function like FileTimeToDosDateTime BOOLEAN FsdSystemTimeToDosDateTime (PDEVICE_EXTENSION DeviceExt, PLARGE_INTEGER SystemTime, USHORT *pDosDate, USHORT *pDosTime) { PDOSTIME pdtime = (PDOSTIME) pDosTime; PDOSDATE pddate = (PDOSDATE) pDosDate; TIME_FIELDS TimeFields; LARGE_INTEGER LocalTime; if (SystemTime == NULL) return FALSE; ExSystemTimeToLocalTime (SystemTime, &LocalTime); RtlTimeToTimeFields (&LocalTime, &TimeFields); if (pdtime) { pdtime->Second = TimeFields.Second / 2; pdtime->Minute = TimeFields.Minute; pdtime->Hour = TimeFields.Hour; } if (pddate) { pddate->Day = TimeFields.Day; pddate->Month = TimeFields.Month; pddate->Year = (USHORT) (TimeFields.Year - DeviceExt->BaseDateYear); } return TRUE; }
/* Process Callback that is called every time a process event occurs. Creates a kernel event which can be used to notify userspace processes. */ VOID ProcessCallback( IN HANDLE hParentId, IN HANDLE hProcessId, IN BOOLEAN bCreate ) { NTSTATUS status; LARGE_INTEGER currentSystemTime; LARGE_INTEGER currentLocalTime; TIME_FIELDS timeFields; UNICODE_STRING processImagePath; PCAPTURE_PROCESS_MANAGER pProcessManager; /* Get the current time */ KeQuerySystemTime(¤tSystemTime); ExSystemTimeToLocalTime(¤tSystemTime,¤tLocalTime); RtlTimeToTimeFields(¤tLocalTime,&timeFields); /* Get the process manager from the device extension */ pProcessManager = gpDeviceObject->DeviceExtension; pProcessManager->pCurrentProcessEvent = ExAllocatePoolWithTag(NonPagedPool, sizeof(PROCESS_EVENT), PROCESS_POOL_TAG); if(pProcessManager->pCurrentProcessEvent == NULL) { return; } RtlCopyMemory(&pProcessManager->pCurrentProcessEvent->time, &timeFields, sizeof(TIME_FIELDS)); processImagePath.Length = 0; processImagePath.MaximumLength = 0; status = GetProcessImageName(hProcessId, &processImagePath); if(status == STATUS_BUFFER_OVERFLOW) { processImagePath.Buffer = ExAllocatePoolWithTag(NonPagedPool, processImagePath.MaximumLength, PROCESS_POOL_TAG); if(processImagePath.Buffer != NULL) { status = GetProcessImageName(hProcessId, &processImagePath); if(NT_SUCCESS(status)) { DbgPrint("CaptureProcessMonitor: %i %i=>%i:%wZ\n", bCreate, hParentId, hProcessId, &processImagePath); RtlStringCbCopyUnicodeString(pProcessManager->pCurrentProcessEvent->processPath, 1024, &processImagePath); } ExFreePoolWithTag(processImagePath.Buffer,PROCESS_POOL_TAG); } } pProcessManager->pCurrentProcessEvent->hParentProcessId = hParentId; pProcessManager->pCurrentProcessEvent->hProcessId = hProcessId; pProcessManager->pCurrentProcessEvent->bCreated = bCreate; KeSetEvent(pProcessManager->eNewProcessEvent, 0, FALSE); KeClearEvent(pProcessManager->eNewProcessEvent); }
FAT_TIME_STAMP FatGetCurrentFatTime ( IN PIRP_CONTEXT IrpContext ) /*++ Routine Description: This routine returns the current system time in Fat time Arguments: Return Value: FAT_TIME_STAMP - Receives the current system time --*/ { LARGE_INTEGER Time; TIME_FIELDS TimeFields; FAT_TIME_STAMP FatTime; // // Get the current system time, and map it into a time field record. // KeQuerySystemTime( &Time ); ExSystemTimeToLocalTime( &Time, &Time ); // // Always add almost two seconds to round up to the nearest double second. // Time.QuadPart = Time.QuadPart + AlmostTwoSeconds; (VOID)RtlTimeToTimeFields( &Time, &TimeFields ); // // Now simply copy over the information // FatTime.Time.DoubleSeconds = (USHORT)(TimeFields.Second / 2); FatTime.Time.Minute = (USHORT)(TimeFields.Minute); FatTime.Time.Hour = (USHORT)(TimeFields.Hour); FatTime.Date.Year = (USHORT)(TimeFields.Year - 1980); FatTime.Date.Month = (USHORT)(TimeFields.Month); FatTime.Date.Day = (USHORT)(TimeFields.Day); UNREFERENCED_PARAMETER( IrpContext ); return FatTime; }
int main() { wcscpy(path+4,GetModulePath()); LPWSTR p=path; while (*p) p++; while (*p!=L'\\') p--; p--; while (*p!=L'\\') p--; p++; wcscpy(p,L"version.h"); UNICODE_STRING us; RtlInitUnicodeString(&us,path); OBJECT_ATTRIBUTES oa={sizeof(oa),0,&us,OBJ_CASE_INSENSITIVE,0,0}; HANDLE hFile; IO_STATUS_BLOCK isb; if (!NT_SUCCESS(NtCreateFile(&hFile, FILE_SHARE_READ|FILE_WRITE_DATA|FILE_READ_ATTRIBUTES|SYNCHRONIZE ,&oa,&isb,0,0,FILE_SHARE_READ,FILE_OPEN_IF, FILE_SYNCHRONOUS_IO_NONALERT|FILE_NON_DIRECTORY_FILE,0,0))) return 1; FILE_BASIC_INFORMATION basic; NtQueryInformationFile(hFile,&isb,&basic,sizeof(basic),FileBasicInformation); int l=strlen(buffer); char* ptr; ptr=buffer+l; LARGE_INTEGER current_time; TIME_FIELDS tf,ctf; NtQuerySystemTime(¤t_time); current_time.QuadPart-=GetTimeBias()->QuadPart; RtlTimeToTimeFields(¤t_time,&tf); RtlTimeToTimeFields(&basic.LastWriteTime,&ctf); if (ctf.wDay!=tf.wDay||ctf.wMonth!=tf.wMonth||ctf.wYear!=tf.wYear){ l+=sprintf(ptr,"%.4d.%.2d.%.2d)\\r\\n\";",tf.wYear,tf.wMonth,tf.wDay); NtWriteFile(hFile,0,0,0,&isb,buffer,l,0,0); } NtClose(hFile); return 0; //IthCloseSystemService(); }
/** * 获取当前系统时间 * @return TIME_FIELDS 返回当前系统的时间。 */ TIME_FIELDS GetLocalTime() { LARGE_INTEGER current_stime; KeQuerySystemTime(¤t_stime); LARGE_INTEGER current_ltime; ExSystemTimeToLocalTime(¤t_stime,¤t_ltime); TIME_FIELDS current_tinfo; RtlTimeToTimeFields(¤t_ltime,¤t_tinfo); return current_tinfo; }
//---------------------------------------------------------------------------- void FormatTimestamp(__in char *buffer, __in const size_t size) { LARGE_INTEGER localTime; LARGE_INTEGER systemTime; TIME_FIELDS timeFields; KeQuerySystemTime(&systemTime); ExSystemTimeToLocalTime(&systemTime, &localTime); RtlTimeToTimeFields(&localTime, &timeFields); RtlStringCbPrintfA(buffer, size, "%04d-%02d-%02d %02d:%02d:%02d.%03d", timeFields.Year, timeFields.Month, timeFields.Day, timeFields.Hour, timeFields.Minute, timeFields.Second, timeFields.Milliseconds); }
VOID SrvReportCorruptSlmStatus ( IN PUNICODE_STRING StatusFile, IN NTSTATUS Status, IN ULONG Offset, IN ULONG Operation, IN PSESSION Session ) { NTSTATUS status; ANSI_STRING ansiStatusFile; TIME time; TIME_FIELDS timeFields; status = RtlUnicodeStringToAnsiString( &ansiStatusFile, StatusFile, TRUE ); ASSERT( NT_SUCCESS(status) ); KeQuerySystemTime( &time ); RtlTimeToTimeFields( &time, &timeFields ); // // Send a broadcast message. // SrvSendSecondClassMailslot( ansiStatusFile.Buffer, StatusFile->Length + 1, "NTSLMCORRUPT", "SlmCheck" ); SrvPrint4( "\n*** CORRUPT STATUS FILE DETECTED ***\n" " File: %Z\n" " Status: 0x%lx, Offset: 0x%lx, detected on %s\n", &ansiStatusFile, Status, Offset, Operation == SLMDBG_CLOSE ? "close" : "rename" ); SrvPrint3( " Workstation: %wZ, User: %wZ, OS: %wZ\n", &Session->Connection->ClientMachineNameString, &Session->UserName, &SrvClientTypes[Session->Connection->SmbDialect] ); SrvPrint3( " Current time: %d-%d-%d ", timeFields.Month, timeFields.Day, timeFields.Year ); SrvPrint3( "%d:%d:%d\n", timeFields.Hour, timeFields.Minute, timeFields.Second ); RtlFreeAnsiString( &ansiStatusFile ); return; } // SrvReportCorruptSlmStatus
/* * @implemented */ BOOLEAN NTAPI HalQueryRealTimeClock(IN PTIME_FIELDS Time) { LARGE_INTEGER LargeTime; ULONG Seconds; /* Query the RTC value */ Seconds = READ_REGISTER_ULONG(RTC_DATA); /* Convert to time */ RtlSecondsSince1970ToTime(Seconds, &LargeTime); /* Convert to time-fields */ RtlTimeToTimeFields(&LargeTime, Time); return TRUE; }
static ULONG CalcVolumeSerialNumber(VOID) { LARGE_INTEGER SystemTime; TIME_FIELDS TimeFields; ULONG Serial; PUCHAR Buffer; NtQuerySystemTime (&SystemTime); RtlTimeToTimeFields (&SystemTime, &TimeFields); Buffer = (PUCHAR)&Serial; Buffer[0] = (UCHAR)(TimeFields.Year & 0xFF) + (UCHAR)(TimeFields.Hour & 0xFF); Buffer[1] = (UCHAR)(TimeFields.Year >> 8) + (UCHAR)(TimeFields.Minute & 0xFF); Buffer[2] = (UCHAR)(TimeFields.Month & 0xFF) + (UCHAR)(TimeFields.Second & 0xFF); Buffer[3] = (UCHAR)(TimeFields.Day & 0xFF) + (UCHAR)(TimeFields.Milliseconds & 0xFF); return Serial; }
/********************************************************************* * FileTimeToSystemTime (KERNEL32.@) */ BOOL WINAPI FileTimeToSystemTime( const FILETIME *ft, LPSYSTEMTIME syst ) { TIME_FIELDS tf; LARGE_INTEGER t; t.u.LowPart = ft->dwLowDateTime; t.u.HighPart = ft->dwHighDateTime; RtlTimeToTimeFields(&t, &tf); syst->wYear = tf.Year; syst->wMonth = tf.Month; syst->wDay = tf.Day; syst->wHour = tf.Hour; syst->wMinute = tf.Minute; syst->wSecond = tf.Second; syst->wMilliseconds = tf.Milliseconds; syst->wDayOfWeek = tf.Weekday; return TRUE; }
BOOL WINAPI FileTimeToSystemTime( const FILETIME *ft, SYSTEMTIME * syst ) { TIME_FIELDS tf; LARGE_INTEGER t; TRACEN((printf("FileTimeToSystemTime\n"))) t.QuadPart = ft->dwHighDateTime; t.QuadPart = (t.QuadPart << 32) | ft->dwLowDateTime; RtlTimeToTimeFields(&t, &tf); syst->wYear = tf.Year; syst->wMonth = tf.Month; syst->wDay = tf.Day; syst->wHour = tf.Hour; syst->wMinute = tf.Minute; syst->wSecond = tf.Second; syst->wMilliseconds = tf.Milliseconds; syst->wDayOfWeek = tf.Weekday; return TRUE; }
VOID PrintTime ( IN ULONG DebugLevel, IN PTIME Time ) { TIME_FIELDS TimeFields; UNREFERENCED_PARAMETER(DebugLevel); RtlTimeToTimeFields( Time, &TimeFields ); SPY_LOG_PRINT( DebugLevel, ( "%02u-%02u-%02u %02u:%02u:%02u \n", TimeFields.Month, TimeFields.Day, TimeFields.Year % 100, TimeFields.Hour, TimeFields.Minute, TimeFields.Second )); return; }
void DebugPrintMsg(char* Msg) { LARGE_INTEGER Now; TIME_FIELDS NowTF; USHORT MsgLen; ULONG EventDataLen, len; PDEBUGPRINT_EVENT pEvent; if( !DebugPrintStarted || DriverName==NULL) return; // Get current time KeQuerySystemTime(&Now); // LARGE_INTEGER NowLocal; // ExSystemTimeToLocalTime( &Now, &NowLocal); // NT only // RtlTimeToTimeFields( &NowLocal, &NowTF); RtlTimeToTimeFields( &Now, &NowTF); // Get size of Msg and complete event MsgLen = ANSIstrlen(Msg)+1; EventDataLen = sizeof(TIME_FIELDS) + DriverNameLen + MsgLen; len = sizeof(LIST_ENTRY)+sizeof(ULONG)+EventDataLen; // Allocate event buffer pEvent = (PDEBUGPRINT_EVENT)ExAllocatePool(NonPagedPool,len); if( pEvent!=NULL) { PUCHAR buffer = (PUCHAR)pEvent->EventData; // Copy event info to buffer RtlCopyMemory( buffer, &NowTF, sizeof(TIME_FIELDS)); buffer += sizeof(TIME_FIELDS); RtlCopyMemory( buffer, DriverName, DriverNameLen); buffer += DriverNameLen; RtlCopyMemory( buffer, Msg, MsgLen); // Insert event into event list for processing by system thread pEvent->Len = EventDataLen; ExInterlockedInsertTailList(&EventList,&pEvent->ListEntry,&EventListLock); } }
void natvLogSession( IN const char * prefixStr, IN TRACED_CONNECTION* pItem, IN ULONG prevState, IN const char * sufixStr ) { TIME_FIELDS TimeFields; char timeStr[30]; LARGE_INTEGER time; char dstIpAddrStr[30]; char srcIpAddrStr[30]; KeQuerySystemTime(&time); ExSystemTimeToLocalTime(&time, &time); RtlTimeToTimeFields(&time, &TimeFields); RtlStringCbPrintfA(timeStr, sizeof(timeStr), "%02d:%02d:%02d.%03d ", TimeFields.Hour, TimeFields.Minute, TimeFields.Second, TimeFields.Milliseconds); PRINT_IP(dstIpAddrStr, &pItem->dstIpAddrOrg); PRINT_IP(srcIpAddrStr, &pItem->srcIpAddrOrg); DbgPrint("%s %s session %s %s: %s:%u->%s:%u. State %s->%s\n", timeStr, prefixStr, pItem->out ? "OUT" : "IN ", sufixStr, srcIpAddrStr, RtlUshortByteSwap(pItem->srcPortOrg), dstIpAddrStr, RtlUshortByteSwap(pItem->dstPortOrg), natsState2Name(prevState), natsState2Name(pItem->state) ); }
VOID PrintFtlPkt( IN char *strPrefix, IN FLT_PKT* pFltPkt, IN ULONG uNewIp, IN BOOLEAN bOut ) { TIME_FIELDS TimeFields; char Message[255]; char MessagePart[30]; LARGE_INTEGER time; KeQuerySystemTime(&time); ExSystemTimeToLocalTime(&time, &time); RtlTimeToTimeFields(&time, &TimeFields); RtlStringCbPrintfA(Message, sizeof(Message), "%02d:%02d:%02d.%03d ", TimeFields.Hour, TimeFields.Minute, TimeFields.Second, TimeFields.Milliseconds); if (!bOut) { RtlStringCbCatA(Message, sizeof(Message), "IN "); } else { RtlStringCbCatA(Message, sizeof(Message), "OUT "); } RtlStringCbCatA(Message, sizeof(Message), strPrefix); RtlStringCbCatA(Message, sizeof(Message), " "); if (NULL == pFltPkt->pEth) { goto out; } RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), "%02x-%02x-%02x-%02x-%02x-%02x", pFltPkt->pEth->ether_src[0], pFltPkt->pEth->ether_src[1], pFltPkt->pEth->ether_src[2], pFltPkt->pEth->ether_src[3], pFltPkt->pEth->ether_src[4], pFltPkt->pEth->ether_src[5]); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbCatA(Message, sizeof(Message), "->"); RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), "%02x-%02x-%02x-%02x-%02x-%02x", pFltPkt->pEth->ether_dst[0], pFltPkt->pEth->ether_dst[1], pFltPkt->pEth->ether_dst[2], pFltPkt->pEth->ether_dst[3], pFltPkt->pEth->ether_dst[4], pFltPkt->pEth->ether_dst[5]); RtlStringCbCatA(Message, sizeof(Message), MessagePart); switch (pFltPkt->pEth->ether_type) { case ETHERNET_TYPE_ARP_NET: RtlStringCbCatA(Message, sizeof(Message), " ARP "); if (NULL == pFltPkt->pArp) goto out; if (ARP_REQUEST_CODE == pFltPkt->pArp->ea_hdr.ar_op) { RtlStringCbCatA(Message, sizeof(Message), "Request "); } else if (pFltPkt->pArp->ea_hdr.ar_op == ARP_REPLY_CODE) { RtlStringCbCatA(Message, sizeof(Message), "Reply "); } RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), "%d.%d.%d.%d", pFltPkt->pArp->arp_spa[0], pFltPkt->pArp->arp_spa[1], pFltPkt->pArp->arp_spa[2], pFltPkt->pArp->arp_spa[3]); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbCatA(Message, sizeof(Message), "->"); PRINT_IP(MessagePart, pFltPkt->pArp->arp_tpa); RtlStringCbCatA(Message, sizeof(Message), MessagePart); break; case ETHERNET_TYPE_IP_NET: RtlStringCbCatA(Message, sizeof(Message), " IP "); if (NULL == pFltPkt->pIp) goto out; RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), "ID %04x ", RtlUshortByteSwap(pFltPkt->pIp->ip_id)); RtlStringCbCatA(Message, sizeof(Message), MessagePart); PRINT_IP(MessagePart, &pFltPkt->pIp->ip_src); RtlStringCbCatA(Message, sizeof(Message), MessagePart); if (uNewIp && bOut) { RtlStringCbCatA(Message, sizeof(Message), "["); PRINT_IP(MessagePart, &uNewIp); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbCatA(Message, sizeof(Message), "]"); } RtlStringCbCatA(Message, sizeof(Message), "->"); PRINT_IP(MessagePart, &pFltPkt->pIp->ip_dst); RtlStringCbCatA(Message, sizeof(Message), MessagePart); if (uNewIp && !bOut) { RtlStringCbCatA(Message, sizeof(Message), "["); PRINT_IP(MessagePart, &uNewIp); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbCatA(Message, sizeof(Message), "]"); } switch (pFltPkt->pIp->ip_proto) { case IPPROTO_TCP: RtlStringCbCatA(Message, sizeof(Message), " TCP"); break; case IPPROTO_ICMP: RtlStringCbCatA(Message, sizeof(Message), " ICMP"); break; case IPPROTO_UDP: RtlStringCbCatA(Message, sizeof(Message), " UDP"); break; default: RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " proto=%04x", pFltPkt->pIp->ip_proto); RtlStringCbCatA(Message, sizeof(Message), MessagePart); break; } if (pFltPkt->pTcp) { RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " %d->%d ", RtlUshortByteSwap(pFltPkt->pTcp->th_sport), RtlUshortByteSwap(pFltPkt->pTcp->th_dport)); if (pFltPkt->pTcp->th_flags & TCP_FIN_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "F"); if (pFltPkt->pTcp->th_flags & TCP_SYN_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "S"); if (pFltPkt->pTcp->th_flags & TCP_RST_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "R"); if (pFltPkt->pTcp->th_flags & TCP_PSH_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "P"); if (pFltPkt->pTcp->th_flags & TCP_URG_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "U"); if (pFltPkt->pTcp->th_flags & TCP_ACK_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "A"); // https://tools.ietf.org/html/rfc3168 if (pFltPkt->pTcp->th_flags & TCP_ECE_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "E"); if (pFltPkt->pTcp->th_flags & TCP_CWR_FLAG) RtlStringCbCatA(MessagePart, sizeof(MessagePart), "C"); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " SEQ:%u", RtlUlongByteSwap(pFltPkt->pTcp->th_seq)); RtlStringCbCatA(Message, sizeof(Message), MessagePart); RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " ACK:%u", RtlUlongByteSwap(pFltPkt->pTcp->th_ack)); } else if (pFltPkt->pUdp) { RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " %d->%d", RtlUshortByteSwap(pFltPkt->pUdp->uh_sport), RtlUshortByteSwap(pFltPkt->pUdp->uh_dport)); } else if (pFltPkt->pIcmp) { RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " %d", RtlUshortByteSwap(pFltPkt->pIcmp->icmp_hun.idseq.id)); } else { MessagePart[0] = 0; } RtlStringCbCatA(Message, sizeof(Message), MessagePart); break; default: RtlStringCbPrintfA(MessagePart, sizeof(MessagePart), " UNK %04x", RtlUshortByteSwap(pFltPkt->pEth->ether_type)); RtlStringCbCatA(Message, sizeof(Message), MessagePart); break; } out: RtlStringCbCatA(Message, sizeof(Message), "\n"); DbgPrint(Message); return; }
BOOLEAN FatNtTimeToFatTime ( IN PIRP_CONTEXT IrpContext, IN PLARGE_INTEGER NtTime, IN BOOLEAN Rounding, OUT PFAT_TIME_STAMP FatTime, OUT OPTIONAL PCHAR TenMsecs ) /*++ Routine Description: This routine converts an NtTime value to its corresponding Fat time value. Arguments: NtTime - Supplies the Nt GMT Time value to convert from Rounding - Indicates whether the NT time should be rounded up to a FAT boundary. This should only be done *once* in the lifetime of a timestamp (important for tunneling, which will cause a timestamp to pass through at least twice). If true, rounded up. If false, rounded down to 10ms boundary. This obeys the rules for non-creation time and creation times (respectively). FatTime - Receives the equivalent Fat time value TenMsecs - Optionally receive the number of tens of milliseconds the NtTime, after any rounding, is greater than the FatTime Return Value: BOOLEAN - TRUE if the Nt time value is within the range of Fat's time range, and FALSE otherwise --*/ { TIME_FIELDS TimeFields; // // Convert the input to the a time field record. // if (Rounding) { // // Add almost two seconds to round up to the nearest double second. // NtTime->QuadPart = NtTime->QuadPart + AlmostTwoSeconds; } ExSystemTimeToLocalTime( NtTime, NtTime ); RtlTimeToTimeFields( NtTime, &TimeFields ); // // Check the range of the date found in the time field record // if ((TimeFields.Year < 1980) || (TimeFields.Year > (1980 + 127))) { ExLocalTimeToSystemTime( NtTime, NtTime ); return FALSE; } // // The year will fit in Fat so simply copy over the information // FatTime->Time.DoubleSeconds = (USHORT)(TimeFields.Second / 2); FatTime->Time.Minute = (USHORT)(TimeFields.Minute); FatTime->Time.Hour = (USHORT)(TimeFields.Hour); FatTime->Date.Year = (USHORT)(TimeFields.Year - 1980); FatTime->Date.Month = (USHORT)(TimeFields.Month); FatTime->Date.Day = (USHORT)(TimeFields.Day); if (TenMsecs) { if (!Rounding) { // // If the number of seconds was not divisible by two, then there // is another second of time (1 sec, 3 sec, etc.) Note we round down // the number of milleconds onto tens of milleseconds boundaries. // *TenMsecs = (TimeFields.Milliseconds / 10) + ((TimeFields.Second % 2) * 100); } else { // // If we rounded up, we have in effect changed the NT time. Therefore, // it does not differ from the FAT time. // *TenMsecs = 0; } } if (Rounding) { // // Slice off non-FAT boundary time and convert back to 64bit form // TimeFields.Milliseconds = 0; TimeFields.Second -= TimeFields.Second % 2; } else { // // Round down to 10ms boundary // TimeFields.Milliseconds -= TimeFields.Milliseconds % 10; } // // Convert back to NT time // (VOID) RtlTimeFieldsToTime(&TimeFields, NtTime); ExLocalTimeToSystemTime( NtTime, NtTime ); UNREFERENCED_PARAMETER( IrpContext ); return TRUE; }
// Concatenates meta information such as the current time and a process ID to // user given log message. EXTERN_C static NTSTATUS LogpMakePrefix(_In_ ULONG Level, _In_ const char *FunctionName, _In_ const char *LogMessage, _Out_ char *LogBuffer, _In_ size_t LogBufferLength) { char const *levelString = nullptr; switch (Level) { case LOGP_LEVEL_DEBUG: levelString = "DBG"; break; case LOGP_LEVEL_INFO: levelString = "INF"; break; case LOGP_LEVEL_WARN: levelString = "WRN"; break; case LOGP_LEVEL_ERROR: levelString = "ERR"; break; default: return STATUS_INVALID_PARAMETER; } auto status = STATUS_SUCCESS; char timeBuffer[20] = {}; if ((g_LogpDebugFlag & LOG_OPT_DISABLE_TIME) == 0) { // Want the current time. TIME_FIELDS timeFields; LARGE_INTEGER systemTime, localTime; KeQuerySystemTime(&systemTime); ExSystemTimeToLocalTime(&systemTime, &localTime); RtlTimeToTimeFields(&localTime, &timeFields); status = RtlStringCchPrintfA(timeBuffer, RTL_NUMBER_OF(timeBuffer), "%02u:%02u:%02u.%03u\t", timeFields.Hour, timeFields.Minute, timeFields.Second, timeFields.Milliseconds); if (!NT_SUCCESS(status)) { return status; } } char functionNameBuffer[50] = {}; if ((g_LogpDebugFlag & LOG_OPT_DISABLE_FUNCTION_NAME) == 0) { // Want the function name const auto baseFunctionName = LogpFindBaseFunctionName(FunctionName); status = RtlStringCchPrintfA(functionNameBuffer, RTL_NUMBER_OF(functionNameBuffer), "%-40s\t", baseFunctionName); if (!NT_SUCCESS(status)) { return status; } } // // It uses PsGetProcessId(PsGetCurrentProcess()) instead of // PsGetCurrentThreadProcessId() because the later sometimes returns // unwanted value, for example: // PID == 4 but its image name != ntoskrnl.exe // The author is guessing that it is related to attaching processes but // not quite sure. The former way works as expected. // status = RtlStringCchPrintfA( LogBuffer, LogBufferLength, "%s%s\t%5lu\t%5lu\t%-15s\t%s%s\r\n", timeBuffer, levelString, reinterpret_cast<ULONG_PTR>(PsGetProcessId(PsGetCurrentProcess())), reinterpret_cast<ULONG_PTR>(PsGetCurrentThreadId()), PsGetProcessImageFileName(PsGetCurrentProcess()), functionNameBuffer, LogMessage); return status; }
//生成链表节点 void DebugPrintMsg(PEVENT event) { ULONG TimeLen; ULONG EventDataLen; ULONG ProcessIdLen; ULONG ProcessNameLen; ULONG addr1Len; ULONG addr2Len; ULONG addr3Len; ULONG addr4Len; ULONG OperationLen; ULONG PortLen; ULONG ResultLen; ULONG len; LARGE_INTEGER Now,NowLocal; TIME_FIELDS NowTF; PDEBUGPRINT_EVENT pEvent; PUCHAR buffer; if(DebugPrintStarted==FALSE || ExitNow==TRUE) return; if(event==NULL)return; KeQuerySystemTime(&Now); RtlTimeToTimeFields(&Now,&NowTF); //得到事件总体长度 TimeLen=sizeof(TIME_FIELDS); ProcessIdLen=ANSIstrlen(event->ProcessID)+1; ProcessNameLen=ANSIstrlen(event->ProcessName)+1; addr1Len=ANSIstrlen(event->addr1)+1; addr2Len=ANSIstrlen(event->addr2)+1; addr3Len=ANSIstrlen(event->addr3)+1; addr4Len=ANSIstrlen(event->addr4)+1; OperationLen=ANSIstrlen(event->Operation)+1; PortLen=ANSIstrlen(event->port)+1; ResultLen=ANSIstrlen(event->SuccOrFail)+1; EventDataLen=TimeLen+ProcessIdLen+ProcessNameLen+addr1Len+addr2Len+addr3Len+addr4Len+OperationLen+PortLen+ResultLen; len=sizeof(LIST_ENTRY)+sizeof(ULONG)+EventDataLen; //分配事件缓冲区 pEvent=(PDEBUGPRINT_EVENT)ExAllocatePool(NonPagedPool,len); if(pEvent!=NULL) { buffer=(PUCHAR)pEvent->EventData; RtlCopyMemory(buffer,&NowTF,TimeLen); buffer+=TimeLen; RtlCopyMemory(buffer,event->ProcessID,ProcessIdLen); buffer+=ProcessIdLen; RtlCopyMemory(buffer,event->ProcessName,ProcessNameLen); buffer+=ProcessNameLen; RtlCopyMemory(buffer,event->addr1,addr1Len); buffer+=addr1Len; RtlCopyMemory(buffer,event->addr2,addr2Len); buffer+=addr2Len; RtlCopyMemory(buffer,event->addr3,addr3Len); buffer+=addr3Len; RtlCopyMemory(buffer,event->addr4,addr4Len); buffer+=addr4Len; RtlCopyMemory(buffer,event->Operation,OperationLen); buffer+=OperationLen; RtlCopyMemory(buffer,event->port,PortLen); buffer+=PortLen; RtlCopyMemory(buffer,event->SuccOrFail,ResultLen); pEvent->Len=EventDataLen; ExInterlockedInsertTailList(&EventList,&pEvent->ListEntry,&EventListLock); } }
NTSTATUS RegistryCallback( _In_ PVOID CallbackContext, _In_opt_ PVOID Argument1, _In_opt_ PVOID Argument2 ) { NTSTATUS status = STATUS_SUCCESS; ULONG ulCallbackCtx; REG_NOTIFY_CLASS ulType = (REG_NOTIFY_CLASS)(ULONG_PTR)Argument1; UNICODE_STRING usRegistryPath = { 0 }; BOOLEAN bSuccess = FALSE; LARGE_INTEGER unCurrentSystemTime; LARGE_INTEGER unCurrentLocalTime; PVOID pData = NULL; ULONG ulDataSize = 0; ULONG ulKeyValueType = REG_NONE; WCHAR wzProcessPath[MAX_STRING_LENGTH] = { 0 }; // 时间 KeQuerySystemTime(&unCurrentSystemTime); ExSystemTimeToLocalTime(&unCurrentSystemTime, &unCurrentLocalTime); ulCallbackCtx = (ULONG)(ULONG_PTR)CallbackContext; usRegistryPath.Length = 0; usRegistryPath.MaximumLength = 2048 * sizeof(WCHAR); usRegistryPath.Buffer = ExAllocatePoolWithTag(NonPagedPool, usRegistryPath.MaximumLength, MEM_TAG); if (NULL == usRegistryPath.Buffer) { KdPrint(("[RegistryCallback] Failed to call ExAllocPollWithTag.\r\n")); return status; } switch (ulType) { case RegNtPreCreateKeyEx: { PREG_CREATE_KEY_INFORMATION_V1 pCreateInfo = (PREG_CREATE_KEY_INFORMATION_V1)Argument2; UNICODE_STRING usFilter = { 0 }; BOOLEAN bEqual = FALSE; WCHAR *wzFilters[] = { L"\\REGISTRY\\MACHINE\\SYSTEM\\ControlSet001\\Control\\DeviceClasses", L"\\Registry\\Machine\\System\\CurrentControlSet\\Control\\DeviceClasses", L"\\REGISTRY\\MACHINE\\SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters", L"\\REGISTRY\\MACHINE\\System\\CurrentControlSet\\Services\\Tcpip\\Parameters" }; bSuccess = GetRegistryObjectCompleteName( &usRegistryPath, pCreateInfo->CompleteName, pCreateInfo->RootObject); if (bSuccess) { for (size_t nCount = 0; nCount < sizeof(wzFilters) / sizeof(ULONG_PTR); nCount++) { RtlInitUnicodeString(&usFilter, wzFilters[nCount]); if (RtlEqualUnicodeString(&usRegistryPath, &usFilter, TRUE)) { bEqual = TRUE; } } if (!bEqual) { //WCHAR wzProcessPath[MAX_STRING_LENGTH] = { 0 }; //GetProcessPathBySectionObject(PsGetCurrentProcessId(), wzProcessPath); //KdPrint(("[RegNtPreCreateKeyEx] [%ws] %wZ\r\n", wzProcessPath, &usRegistryPath)); } else { usRegistryPath.Length = 0; } } } break; case RegNtPreDeleteKey: { PREG_DELETE_KEY_INFORMATION pDeleteKey = (PREG_DELETE_KEY_INFORMATION)Argument2; bSuccess = GetRegistryObjectCompleteName( &usRegistryPath, NULL, pDeleteKey->Object); if (bSuccess) { // KdPrint(("[RegNtPreDeleteKey]: %wZ\r\n", &usRegistryPath)); } } break; case RegNtPreSetValueKey: { PREG_SET_VALUE_KEY_INFORMATION pSetKeyValue = (PREG_SET_VALUE_KEY_INFORMATION)Argument2; bSuccess = GetRegistryObjectCompleteName( &usRegistryPath, NULL, pSetKeyValue->Object); if (bSuccess && pSetKeyValue->ValueName->Length > 0 && (REG_SZ == pSetKeyValue->Type || REG_DWORD == pSetKeyValue->Type || REG_QWORD == pSetKeyValue->Type)) { RtlUnicodeStringCatString(&usRegistryPath, L"\\"); RtlUnicodeStringCat(&usRegistryPath, pSetKeyValue->ValueName); ulKeyValueType = pSetKeyValue->Type; ulDataSize = pSetKeyValue->DataSize; pData = pSetKeyValue->Data; } else { usRegistryPath.Length = 0; } } break; case RegNtPreDeleteValueKey: { PREG_DELETE_VALUE_KEY_INFORMATION pDeleteValueKey = (PREG_DELETE_VALUE_KEY_INFORMATION)Argument2; bSuccess = GetRegistryObjectCompleteName(&usRegistryPath, NULL, pDeleteValueKey->Object); if (bSuccess && (pDeleteValueKey->ValueName->Length > 0)) { RtlUnicodeStringCatString(&usRegistryPath, L"\\"); RtlUnicodeStringCat(&usRegistryPath, pDeleteValueKey->ValueName); } } break; default: break; } // 创建数据链表 if (usRegistryPath.Length != 0) { PEVENT_DATA_NODE pNode = InitListNode(); HANDLE hProcessId = NULL; hProcessId = PsGetCurrentProcessId(); GetProcessPathBySectionObject(hProcessId, wzProcessPath); ULONG ulProcessPathLength = (ULONG)(wcslen(wzProcessPath) * sizeof(WCHAR) + sizeof(WCHAR)); // 进程的长度 ULONG ulRegistryPathLength = usRegistryPath.Length + sizeof(WCHAR); // 注册表路径的长度 SIZE_T ulNumberOfBytes = sizeof(REGISTRY_EVENT) + ulProcessPathLength + ulRegistryPathLength + ulDataSize; // 总长度=进程+注册表+数据 // 进程路径 pNode->pstRegistryEvent = ExAllocatePoolWithTag(NonPagedPool, ulNumberOfBytes, MEM_TAG); // 给各节点数据赋值 pNode->pstRegistryEvent->hProcessId = hProcessId; pNode->pstRegistryEvent->enRegistryNotifyClass = ulType; pNode->pstRegistryEvent->ulDataLength = ulDataSize; pNode->pstRegistryEvent->ulProcessPathLength = ulProcessPathLength; pNode->pstRegistryEvent->ulRegistryPathLength = ulRegistryPathLength; pNode->pstRegistryEvent->ulKeyValueType = ulKeyValueType; RtlTimeToTimeFields(&unCurrentLocalTime, &pNode->pstRegistryEvent->time); // 时间信息 RtlCopyBytes(pNode->pstRegistryEvent->uData, wzProcessPath, ulProcessPathLength); // 拷贝进程信息 RtlCopyBytes(pNode->pstRegistryEvent->uData + ulProcessPathLength, usRegistryPath.Buffer, usRegistryPath.Length); // 追加注册表路径信息 pNode->pstRegistryEvent->uData[ulProcessPathLength + usRegistryPath.Length + 0] = '\0'; // 给注册表路径后面添加 \0 结束符 pNode->pstRegistryEvent->uData[ulProcessPathLength + usRegistryPath.Length + 1] = '\0'; RtlCopyBytes(pNode->pstRegistryEvent->uData + ulProcessPathLength + ulRegistryPathLength, pData, ulDataSize); // 追加修改的数据信息(如果不是修改值,这里可能为空) ExInterlockedInsertTailList(&g_ListHead, (PLIST_ENTRY)pNode, &g_Lock); KeSetEvent(&g_Event, 0, FALSE); KdPrint(("hProcessId = %ld", hProcessId)); } if (NULL != usRegistryPath.Buffer) { ExFreePoolWithTag(usRegistryPath.Buffer, MEM_TAG); } return status; }
VOID BowserTrace( PCHAR FormatString, ... ) #define LAST_NAMED_ARGUMENT FormatString { CHAR OutputString[1024]; IO_STATUS_BLOCK IoStatus; BOOLEAN ProcessAttached = FALSE; va_list ParmPtr; // Pointer to stack parms. NTSTATUS Status; PAGED_CODE(); if (IoGetCurrentProcess() != BowserFspProcess) { KeAttachProcess(BowserFspProcess); ProcessAttached = TRUE; } if (BrowserTraceLogHandle == NULL) { if (!NT_SUCCESS(BowserOpenTraceLogFile(L"\\SystemRoot\\Bowser.Log"))) { BrowserTraceLogHandle = (HANDLE)0xffffffff; if (ProcessAttached) { KeDetachProcess(); } return; } } else if (BrowserTraceLogHandle == (HANDLE)0xffffffff) { if (ProcessAttached) { KeDetachProcess(); } return; } ExAcquireResourceExclusive(&BrowserTraceLock, TRUE); if (BrowserTraceLogHandle == NULL) { ExReleaseResource(&BrowserTraceLock); if (ProcessAttached) { KeDetachProcess(); } return; } try { LARGE_INTEGER EndOfFile; EndOfFile.HighPart = 0xffffffff; EndOfFile.LowPart = FILE_WRITE_TO_END_OF_FILE; if (LastCharacter == '\n') { LARGE_INTEGER SystemTime; TIME_FIELDS TimeFields; KeQuerySystemTime(&SystemTime); ExSystemTimeToLocalTime(&SystemTime, &SystemTime); RtlTimeToTimeFields(&SystemTime, &TimeFields); // // The last character written was a newline character. We should // timestamp this record in the file. // /**** sprintf(OutputString, "%2.2d/%2.2d/%4.4d %2.2d:%2.2d:%2.2d.%3.3d: ", TimeFields.Month, TimeFields.Day, TimeFields.Year, TimeFields.Hour, TimeFields.Minute, TimeFields.Second, TimeFields.Milliseconds); ****/ if (!NT_SUCCESS(Status = ZwWriteFile(BrowserTraceLogHandle, NULL, NULL, NULL, &IoStatus, OutputString, strlen(OutputString), &EndOfFile, NULL))) { KdPrint(("Error writing time to Browser log file: %lX\n", Status)); return; } if (!NT_SUCCESS(IoStatus.Status)) { KdPrint(("Error writing time to Browser log file: %lX\n", IoStatus.Status)); return; } if (IoStatus.Information != strlen(OutputString)) { KdPrint(("Error writing time to Browser log file: %lX\n", IoStatus.Status)); return; } } va_start(ParmPtr, LAST_NAMED_ARGUMENT); // // Format the parameters to the string. // vsprintf(OutputString, FormatString, ParmPtr); if (!NT_SUCCESS(Status = ZwWriteFile(BrowserTraceLogHandle, NULL, NULL, NULL, &IoStatus, OutputString, strlen(OutputString), &EndOfFile, NULL))) { KdPrint(("Error writing string to Browser log file: %ld\n", Status)); return; } if (!NT_SUCCESS(IoStatus.Status)) { KdPrint(("Error writing string to Browser log file: %lX\n", IoStatus.Status)); return; } if (IoStatus.Information != strlen(OutputString)) { KdPrint(("Error writing string to Browser log file: %ld\n", IoStatus.Status)); return; } // // Remember the last character output to the log. // LastCharacter = OutputString[strlen(OutputString)-1]; } finally { ExReleaseResource(&BrowserTraceLock); if (ProcessAttached) { KeDetachProcess(); } } }
/* * propBasicQueryKey * * Purpose: * * Set information values for Key object type * * If ExtendedInfoAvailable is FALSE then it calls propSetDefaultInfo to set Basic page properties * */ VOID propBasicQueryKey( _In_ PROP_OBJECT_INFO *Context, _In_ HWND hwndDlg, _In_ BOOL ExtendedInfoAvailable ) { NTSTATUS status; ULONG bytesNeeded; HANDLE hObject; TIME_FIELDS SystemTime; WCHAR szBuffer[MAX_PATH]; KEY_FULL_INFORMATION kfi; SetDlgItemText(hwndDlg, ID_KEYSUBKEYS, T_CannotQuery); SetDlgItemText(hwndDlg, ID_KEYVALUES, T_CannotQuery); SetDlgItemText(hwndDlg, ID_KEYLASTWRITE, T_CannotQuery); if (Context == NULL) { return; } // // Open Key object. // hObject = NULL; if (!propOpenCurrentObject(Context, &hObject, KEY_QUERY_VALUE)) { return; } RtlSecureZeroMemory(&kfi, sizeof(KEY_FULL_INFORMATION)); status = NtQueryKey(hObject, KeyFullInformation, &kfi, sizeof(KEY_FULL_INFORMATION), &bytesNeeded); if (NT_SUCCESS(status)) { //Subkeys count RtlSecureZeroMemory(szBuffer, sizeof(szBuffer)); ultostr(kfi.SubKeys, _strend(szBuffer)); SetDlgItemText(hwndDlg, ID_KEYSUBKEYS, szBuffer); //Values count RtlSecureZeroMemory(szBuffer, sizeof(szBuffer)); ultostr(kfi.Values, _strend(szBuffer)); SetDlgItemText(hwndDlg, ID_KEYVALUES, szBuffer); //LastWrite time RtlSecureZeroMemory(&SystemTime, sizeof(SystemTime)); FileTimeToLocalFileTime((PFILETIME)&kfi.LastWriteTime, (PFILETIME)&kfi.LastWriteTime); RtlTimeToTimeFields((PLARGE_INTEGER)&kfi.LastWriteTime, (PTIME_FIELDS)&SystemTime); //Month starts from 0 index if (SystemTime.Month - 1 < 0) SystemTime.Month = 1; if (SystemTime.Month > 12) SystemTime.Month = 12; RtlSecureZeroMemory(&szBuffer, sizeof(szBuffer)); wsprintf(szBuffer, FORMATTED_TIME_DATE_VALUE, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.Day, Months[SystemTime.Month - 1], SystemTime.Year); SetDlgItemText(hwndDlg, ID_KEYLASTWRITE, szBuffer); } // // Query object basic and type info if needed. // if (ExtendedInfoAvailable == FALSE) { propSetDefaultInfo(Context, hwndDlg, hObject); } NtClose(hObject); }
/* * propBasicQuerySymlink * * Purpose: * * Set information values for SymbolicLink object type * * If ExtendedInfoAvailable is FALSE then it calls propSetDefaultInfo to set Basic page properties * */ VOID propBasicQuerySymlink( _In_ PROP_OBJECT_INFO *Context, _In_ HWND hwndDlg, _In_ BOOL ExtendedInfoAvailable ) { NTSTATUS status; ULONG bytesNeeded; HANDLE hObject; LPWSTR lpLinkTarget; TIME_FIELDS SystemTime; WCHAR szBuffer[MAX_PATH]; OBJECT_BASIC_INFORMATION obi; SetDlgItemText(hwndDlg, ID_OBJECT_SYMLINK_TARGET, T_CannotQuery); SetDlgItemText(hwndDlg, ID_OBJECT_SYMLINK_CREATION, T_CannotQuery); if (Context == NULL) { return; } // // Open SymbolicLink object. // hObject = NULL; if (!propOpenCurrentObject(Context, &hObject, SYMBOLIC_LINK_QUERY)) { return; } // // Copy link target from main object list for performance reasons. // So we don't need to query same data again. // lpLinkTarget = Context->lpDescription; if (lpLinkTarget) { SetDlgItemText(hwndDlg, ID_OBJECT_SYMLINK_TARGET, lpLinkTarget); } //Query Link Creation Time RtlSecureZeroMemory(&obi, sizeof(OBJECT_BASIC_INFORMATION)); status = NtQueryObject(hObject, ObjectBasicInformation, &obi, sizeof(OBJECT_BASIC_INFORMATION), &bytesNeeded); if (NT_SUCCESS(status)) { FileTimeToLocalFileTime((PFILETIME)&obi.CreationTime, (PFILETIME)&obi.CreationTime); RtlSecureZeroMemory(&SystemTime, sizeof(SystemTime)); RtlTimeToTimeFields((PLARGE_INTEGER)&obi.CreationTime, (PTIME_FIELDS)&SystemTime); //Month starts from 0 index if (SystemTime.Month - 1 < 0) SystemTime.Month = 1; if (SystemTime.Month > 12) SystemTime.Month = 12; RtlSecureZeroMemory(&szBuffer, sizeof(szBuffer)); wsprintf(szBuffer, FORMATTED_TIME_DATE_VALUE, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.Day, Months[SystemTime.Month - 1], SystemTime.Year); SetDlgItemText(hwndDlg, ID_OBJECT_SYMLINK_CREATION, szBuffer); } // // Query object basic and type info if needed. // if (ExtendedInfoAvailable == FALSE) { propSetDefaultInfo(Context, hwndDlg, hObject); } NtClose(hObject); }
/* * propBasicQueryJob * * Purpose: * * Set information values for Job object type * * If ExtendedInfoAvailable is FALSE then it calls propSetDefaultInfo to set Basic page properties * */ VOID propBasicQueryJob( _In_ PROP_OBJECT_INFO *Context, _In_ HWND hwndDlg, _In_ BOOL ExtendedInfoAvailable ) { BOOL cond = FALSE; DWORD i; HWND hwndCB; HANDLE hObject; NTSTATUS status; ULONG bytesNeeded; ULONG_PTR ProcessId; PVOID ProcessList; WCHAR szProcessName[MAX_PATH + 1]; WCHAR szBuffer[MAX_PATH * 2]; TIME_FIELDS SystemTime; JOBOBJECT_BASIC_ACCOUNTING_INFORMATION jbai; PJOBOBJECT_BASIC_PROCESS_ID_LIST pJobProcList; SetDlgItemText(hwndDlg, ID_JOBTOTALPROCS, T_CannotQuery); SetDlgItemText(hwndDlg, ID_JOBACTIVEPROCS, T_CannotQuery); SetDlgItemText(hwndDlg, ID_JOBTERMINATEDPROCS, T_CannotQuery); SetDlgItemText(hwndDlg, ID_JOBTOTALUMTIME, T_CannotQuery); SetDlgItemText(hwndDlg, ID_JOBTOTALKMTIME, T_CannotQuery); SetDlgItemText(hwndDlg, ID_JOBTOTALPF, T_CannotQuery); if (Context == NULL) { return; } // // Open Job object. // hObject = NULL; if (!propOpenCurrentObject(Context, &hObject, JOB_OBJECT_QUERY)) { return; } //query basic information RtlSecureZeroMemory(&jbai, sizeof(JOBOBJECT_BASIC_ACCOUNTING_INFORMATION)); status = NtQueryInformationJobObject(hObject, JobObjectBasicAccountingInformation, &jbai, sizeof(JOBOBJECT_BASIC_ACCOUNTING_INFORMATION), &bytesNeeded); if (NT_SUCCESS(status)) { //Total processes RtlSecureZeroMemory(&szBuffer, sizeof(szBuffer)); ultostr(jbai.TotalProcesses, szBuffer); SetDlgItemText(hwndDlg, ID_JOBTOTALPROCS, szBuffer); //Active processes RtlSecureZeroMemory(&szBuffer, sizeof(szBuffer)); ultostr(jbai.ActiveProcesses, szBuffer); SetDlgItemText(hwndDlg, ID_JOBACTIVEPROCS, szBuffer); //Terminated processes RtlSecureZeroMemory(&szBuffer, sizeof(szBuffer)); ultostr(jbai.TotalTerminatedProcesses, szBuffer); SetDlgItemText(hwndDlg, ID_JOBTERMINATEDPROCS, szBuffer); //Total user time RtlSecureZeroMemory(&szBuffer, sizeof(szBuffer)); RtlSecureZeroMemory(&SystemTime, sizeof(SystemTime)); RtlTimeToTimeFields(&jbai.TotalUserTime, &SystemTime); wsprintf(szBuffer, FORMATTED_TIME_VALUE_MS, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.Milliseconds); SetDlgItemText(hwndDlg, ID_JOBTOTALUMTIME, szBuffer); //Total kernel time RtlSecureZeroMemory(&szBuffer, sizeof(szBuffer)); RtlTimeToTimeFields(&jbai.TotalKernelTime, &SystemTime); wsprintf(szBuffer, FORMATTED_TIME_VALUE_MS, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.Milliseconds); SetDlgItemText(hwndDlg, ID_JOBTOTALKMTIME, szBuffer); //Page faults RtlSecureZeroMemory(&szBuffer, sizeof(szBuffer)); ultostr(jbai.TotalPageFaultCount, szBuffer); SetDlgItemText(hwndDlg, ID_JOBTOTALPF, szBuffer); //Job process list pJobProcList = NULL; do { hwndCB = GetDlgItem(hwndDlg, IDC_JOB_PLIST); if (hwndCB == NULL) break; //allocate default size bytesNeeded = sizeof(JOBOBJECT_BASIC_PROCESS_ID_LIST); pJobProcList = supVirtualAlloc(bytesNeeded); if (pJobProcList == NULL) break; //if buffer is not enough, reallocate it status = NtQueryInformationJobObject(hObject, JobObjectBasicProcessIdList, pJobProcList, bytesNeeded, &bytesNeeded); if (status == STATUS_BUFFER_TOO_SMALL) { supVirtualFree(pJobProcList); pJobProcList = supVirtualAlloc(bytesNeeded); if (pJobProcList == NULL) break; status = NtQueryInformationJobObject(hObject, JobObjectBasicProcessIdList, pJobProcList, bytesNeeded, &bytesNeeded); if (!NT_SUCCESS(status)) break; } EnableWindow(hwndCB, (pJobProcList->NumberOfProcessIdsInList > 0) ? TRUE : FALSE); SendMessage(hwndCB, CB_RESETCONTENT, (WPARAM)0, (LPARAM)0); // // If any present then output processes in the list. // if (pJobProcList->NumberOfProcessIdsInList > 0) { ProcessList = supGetSystemInfo(SystemProcessInformation); if (ProcessList) { for (i = 0; i < pJobProcList->NumberOfProcessIdsInList; i++) { ProcessId = pJobProcList->ProcessIdList[i]; RtlSecureZeroMemory(&szProcessName, sizeof(szProcessName)); // // Query process name. // if (!supQueryProcessName(ProcessId, ProcessList, szProcessName, MAX_PATH)) { _strcpy(szProcessName, TEXT("UnknownProcess")); } wsprintf(szBuffer, TEXT("[0x%I64X:%I64u] %ws"), ProcessId, ProcessId, szProcessName); SendMessage(hwndCB, CB_ADDSTRING, (WPARAM)0, (LPARAM)&szBuffer); } SendMessage(hwndCB, CB_SETCURSEL, (WPARAM)0, (LPARAM)0); supHeapFree(ProcessList); } } } while (cond); if (pJobProcList != NULL) { supVirtualFree(pJobProcList); } } // // Query object basic and type info if needed. // if (ExtendedInfoAvailable == FALSE) { propSetDefaultInfo(Context, hwndDlg, hObject); } NtClose(hObject); }
int main( int argc, char *argv[] ) { ULONG i; // // We're starting the test // DbgPrint("Start Time Test\n"); // // Start by initializing some constants and making sure they // are correct // Zero.QuadPart = 0; OneSecond.QuadPart = 10000000; OneMinute.QuadPart = OneSecond.QuadPart * 60; OneHour.QuadPart = OneMinute.QuadPart * 60; OneDay.QuadPart = OneHour.QuadPart * 24; OneWeek.QuadPart = OneDay.QuadPart * 7; OneNormalYear.QuadPart = OneDay.QuadPart * 365; OneLeapYear.QuadPart = OneDay.QuadPart * 366; OneCentury.QuadPart = (OneNormalYear.QuadPart * 76) + (OneLeapYear.QuadPart * 24); TwoCenturies.QuadPart = OneCentury.QuadPart * 2; ThreeCenturies.QuadPart = OneCentury.QuadPart * 3; FourCenturies.QuadPart = (OneCentury.QuadPart * 4) + OneDay.QuadPart; Sum.QuadPart = Zero.QuadPart + OneSecond.QuadPart + OneMinute.QuadPart + OneHour.QuadPart + OneDay.QuadPart + OneWeek.QuadPart + OneNormalYear.QuadPart + ThreeCenturies.QuadPart; RtlTimeToTimeFields( (PLARGE_INTEGER)&Zero, &TimeFields ); DbgPrint("StartOf1601 = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to Zero\n"); } if ((Time.LowPart != Zero.LowPart) || (Time.HighPart != Zero.HighPart)) { DbgPrint("****ERROR Time != Zero\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&OneSecond, &TimeFields ); DbgPrint(" + 1 Second = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to OneSecond\n"); } if ((Time.LowPart != OneSecond.LowPart) || (Time.HighPart != OneSecond.HighPart)) { DbgPrint("****ERROR Time != OneSecond\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&OneMinute, &TimeFields ); DbgPrint(" + 1 Minute = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to OneMinute\n"); } if ((Time.LowPart != OneMinute.LowPart) || (Time.HighPart != OneMinute.HighPart)) { DbgPrint("****ERROR Time != OneMinute\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&OneHour, &TimeFields ); DbgPrint(" + 1 Hour = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to OneHour\n"); } if ((Time.LowPart != OneHour.LowPart) || (Time.HighPart != OneHour.HighPart)) { DbgPrint("****ERROR Time != OneHour\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&OneDay, &TimeFields ); DbgPrint(" + 1 Day = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to OneDay\n"); } if ((Time.LowPart != OneDay.LowPart) || (Time.HighPart != OneDay.HighPart)) { DbgPrint("****ERROR Time != OneDay\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&OneWeek, &TimeFields ); DbgPrint(" + 1 Week = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to OneWeek\n"); } if ((Time.LowPart != OneWeek.LowPart) || (Time.HighPart != OneWeek.HighPart)) { DbgPrint("****ERROR Time != OneWeek\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&OneNormalYear, &TimeFields ); DbgPrint(" + 1 NormalYear = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to OneNormalYear\n"); } if ((Time.LowPart != OneNormalYear.LowPart) || (Time.HighPart != OneNormalYear.HighPart)) { DbgPrint("****ERROR Time != OneNormalYear\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&OneLeapYear, &TimeFields ); DbgPrint(" + 1 LeapYear = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to OneLeapYear\n"); } if ((Time.LowPart != OneLeapYear.LowPart) || (Time.HighPart != OneLeapYear.HighPart)) { DbgPrint("****ERROR Time != OneLeapYear\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&OneCentury, &TimeFields ); DbgPrint(" + 1 Century = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to OneCentury\n"); } if ((Time.LowPart != OneCentury.LowPart) || (Time.HighPart != OneCentury.HighPart)) { DbgPrint("****ERROR Time != OneCentury\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&TwoCenturies, &TimeFields ); DbgPrint(" + 2 Centuries = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to TwoCenturies\n"); } if ((Time.LowPart != TwoCenturies.LowPart) || (Time.HighPart != TwoCenturies.HighPart)) { DbgPrint("****ERROR Time != TwoCenturies\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&ThreeCenturies, &TimeFields ); DbgPrint(" + 3 Centuries = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to ThreeCenturies\n"); } if ((Time.LowPart != ThreeCenturies.LowPart) || (Time.HighPart != ThreeCenturies.HighPart)) { DbgPrint("****ERROR Time != ThreeCenturies\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&FourCenturies, &TimeFields ); DbgPrint(" + 4 Centuries = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to FourCenturies\n"); } if ((Time.LowPart != FourCenturies.LowPart) || (Time.HighPart != FourCenturies.HighPart)) { DbgPrint("****ERROR Time != FourCenturies\n"); } RtlTimeToTimeFields( (PLARGE_INTEGER)&Sum, &TimeFields ); DbgPrint(" + sum = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to Sum\n"); } if ((Time.LowPart != Sum.LowPart) || (Time.HighPart != Sum.HighPart)) { DbgPrint("****ERROR Time != Sum\n"); } DbgPrint("\n"); // // Setup and test the start 1970 time // RtlSecondsSince1970ToTime( 0, &StartOf1970 ); RtlTimeToTimeFields( &StartOf1970, &TimeFields ); DbgPrint(" Start of 1970 = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to start of 1970\n"); } if ((Time.LowPart != StartOf1970.LowPart) || (Time.HighPart != StartOf1970.HighPart)) { DbgPrint("****ERROR Time != StartOf1970\n"); } if (!RtlTimeToSecondsSince1970( &StartOf1970, &i )) { DbgPrint("****ERROR converting time to seconds since 1970\n"); } if (i != 0) { DbgPrint("****ERROR seconds since 1970 != 0\n"); } // // Setup and test the start 1980 time // RtlSecondsSince1980ToTime( 0, &StartOf1980 ); RtlTimeToTimeFields( &StartOf1980, &TimeFields ); DbgPrint(" Start of 1980 = "); PrintTimeFields( &TimeFields ); DbgPrint("\n"); if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields back to start of 1980\n"); } if ((Time.LowPart != StartOf1980.LowPart) || (Time.HighPart != StartOf1980.HighPart)) { DbgPrint("****ERROR Time != StartOf1980\n"); } if (!RtlTimeToSecondsSince1980( &StartOf1980, &i )) { DbgPrint("****ERROR converting time to seconds since 1980\n"); } if (i != 0) { DbgPrint("****ERROR seconds since 1980 != 0\n"); } // // Lets try to print the Christmas when Santa arrives for 1901 to 2001 // every 10 years // TimeFields.Month = 12; TimeFields.Day = 25; TimeFields.Hour = 3; TimeFields.Minute = 30; TimeFields.Second = 15; TimeFields.Milliseconds = 250; for (i = 1901; i < 2002; i += 10) { TimeFields.Year = i; if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields to Christmas %4d\n", TimeFields.Year); } RtlTimeToTimeFields( &Time, &TimeFields ); DbgPrint(" Christmas %4d = ", i); PrintTimeFields( &TimeFields ); DbgPrint("\n"); } // // Let's see how old I really am, when I turn 10, 20, 30, ... // TimeFields.Month = 12; TimeFields.Day = 5; TimeFields.Hour = 3; TimeFields.Minute = 14; TimeFields.Second = 0; TimeFields.Milliseconds = 0; for (i = 1956; i <= 1956+60; i += 10) { TimeFields.Year = i; if (!RtlTimeFieldsToTime( &TimeFields, &Time )) { DbgPrint("****ERROR converting TimeFields to DOB %4d\n", TimeFields.Year); } RtlTimeToTimeFields( &Time, &TimeFields ); DbgPrint(" DOB + %4d = ", i-1956); PrintTimeFields( &TimeFields ); DbgPrint("\n"); } DbgPrint("End Time Test\n"); return TRUE; }
void AFSDumpTraceFiles() { NTSTATUS ntStatus = STATUS_SUCCESS; HANDLE hDirectory = NULL; OBJECT_ATTRIBUTES stObjectAttribs; IO_STATUS_BLOCK stIoStatus; LARGE_INTEGER liTime, liLocalTime; TIME_FIELDS timeFields; ULONG ulBytesWritten = 0; HANDLE hDumpFile = NULL; ULONG ulBytesProcessed, ulCopyLength; LARGE_INTEGER liOffset; ULONG ulDumpLength = 0; BOOLEAN bSetEvent = FALSE; __Enter { AFSAcquireShared( &AFSDbgLogLock, TRUE); ulDumpLength = AFSDbgBufferLength - AFSDbgLogRemainingLength; AFSReleaseResource( &AFSDbgLogLock); if( AFSDumpFileLocation.Length == 0 || AFSDumpFileLocation.Buffer == NULL || AFSDbgBufferLength == 0 || ulDumpLength == 0 || AFSDumpFileName.MaximumLength == 0 || AFSDumpFileName.Buffer == NULL || AFSDumpBuffer == NULL) { try_return( ntStatus); } // // Go open the cache file // InitializeObjectAttributes( &stObjectAttribs, &AFSDumpFileLocation, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL); ntStatus = ZwCreateFile( &hDirectory, GENERIC_READ | GENERIC_WRITE, &stObjectAttribs, &stIoStatus, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_OPEN, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if( !NT_SUCCESS( ntStatus)) { try_return( ntStatus); } ntStatus = KeWaitForSingleObject( &AFSDumpFileEvent, Executive, KernelMode, FALSE, NULL); if( !NT_SUCCESS( ntStatus)) { try_return( ntStatus); } bSetEvent = TRUE; AFSDumpFileName.Length = 0; RtlZeroMemory( AFSDumpFileName.Buffer, AFSDumpFileName.MaximumLength); KeQuerySystemTime( &liTime); ExSystemTimeToLocalTime( &liTime, &liLocalTime); RtlTimeToTimeFields( &liLocalTime, &timeFields); ntStatus = RtlStringCchPrintfW( AFSDumpFileName.Buffer, AFSDumpFileName.MaximumLength/sizeof( WCHAR), L"AFSDumpFile %d.%d.%d %d.%d.%d.log", timeFields.Month, timeFields.Day, timeFields.Year, timeFields.Hour, timeFields.Minute, timeFields.Second); if( !NT_SUCCESS( ntStatus)) { try_return( ntStatus); } RtlStringCbLengthW( AFSDumpFileName.Buffer, AFSDumpFileName.MaximumLength, (size_t *)&ulBytesWritten); AFSDumpFileName.Length = (USHORT)ulBytesWritten; InitializeObjectAttributes( &stObjectAttribs, &AFSDumpFileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, hDirectory, NULL); ntStatus = ZwCreateFile( &hDumpFile, GENERIC_READ | GENERIC_WRITE, &stObjectAttribs, &stIoStatus, NULL, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, FILE_CREATE, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0); if( !NT_SUCCESS( ntStatus)) { try_return( ntStatus); } // // Write out the trace buffer // liOffset.QuadPart = 0; ulBytesProcessed = 0; while( ulBytesProcessed < ulDumpLength) { ulCopyLength = AFSDumpBufferLength; if( ulCopyLength > ulDumpLength - ulBytesProcessed) { ulCopyLength = ulDumpLength - ulBytesProcessed; } RtlCopyMemory( AFSDumpBuffer, (void *)((char *)AFSDbgBuffer + ulBytesProcessed), ulCopyLength); ntStatus = ZwWriteFile( hDumpFile, NULL, NULL, NULL, &stIoStatus, AFSDumpBuffer, ulCopyLength, &liOffset, NULL); if( !NT_SUCCESS( ntStatus)) { break; } liOffset.QuadPart += ulCopyLength; ulBytesProcessed += ulCopyLength; } try_exit: if( hDumpFile != NULL) { ZwClose( hDumpFile); } if( hDirectory != NULL) { ZwClose( hDirectory); } if( bSetEvent) { KeSetEvent( &AFSDumpFileEvent, 0, FALSE); } } return; }
void InitializeMessage( _Inout_ CLAIMSMAN_MESSAGE *message, _In_ PUNICODE_STRING sid, _In_ PUNICODE_STRING name, _In_ BOOLEAN ReadAccess, _In_ BOOLEAN WriteAccess, _In_ BOOLEAN DeleteAccess, _In_ LONGLONG size, _In_ LONGLONG modified, _In_ NTSTATUS status ) /* ... */ { PAGED_CODE(); PT_DBG_PRINT(PTDBG_TRACE_ROUTINES, ("claimsman!claimsmanInitializeMessage: Entered\n")); // SID USHORT len = (sid->Length < ((CLAIMSMAN_MESSAGE_SID_SIZE - 1) * sizeof(WCHAR))) ? sid->Length : (CLAIMSMAN_MESSAGE_SID_SIZE - 1) * sizeof(WCHAR); RtlCopyMemory(message->Sid, sid->Buffer, len); message->Sid[(len / sizeof(WCHAR)) + (len % sizeof(WCHAR))] = 0; // FileName len = (name->Length < ((CLAIMSMAN_MESSAGE_FILENAME_SIZE - 1) * sizeof(WCHAR))) ? name->Length : (CLAIMSMAN_MESSAGE_FILENAME_SIZE - 1) * sizeof(WCHAR); RtlCopyMemory(message->FileName, name->Buffer, len); message->FileName[(len / sizeof(WCHAR)) + (len % sizeof(WCHAR))] = 0; // Access info message->ReadAccess = ReadAccess; message->WriteAccess = WriteAccess; message->DeleteAccess = DeleteAccess; // Size message->size = size; // Last modified TIME_FIELDS tf; message->UnixLastModified = modified; LONGLONG tstmp = (modified * 10000) + DIFF_TO_UNIX_EPOCH; RtlTimeToTimeFields(&tstmp, &tf); RtlStringCchPrintfW((NTSTRSAFE_PWSTR)message->LastModified, CLAIMSMAN_MESSAGE_TIMESTAMP_SIZE - 1, L"%04u-%02u-%02uT%02u:%02u:%02u.%03uZ", tf.Year, tf.Month, tf.Day, tf.Hour, tf.Minute, tf.Second, tf.Milliseconds); // Iostatus message->Status = status; // Event timestamp LARGE_INTEGER st; KeQuerySystemTime(&st); // Store as timestamp (Unix epoch + 3 decimals for milliseconds) message->UnixTimeStamp = (st.QuadPart - DIFF_TO_UNIX_EPOCH) / 10000; //PT_DBG_PRINT(PTDBG_TRACE_ROUTINES, // ("claimsman!claimsmanInitializeMessage: message->UnixTimeStamp: %I64u\n", message->UnixTimeStamp)); // And as ISO-8601... RtlTimeToTimeFields(&st, &tf); RtlStringCchPrintfW((NTSTRSAFE_PWSTR)message->TimeStamp, CLAIMSMAN_MESSAGE_TIMESTAMP_SIZE - 1, L"%04u-%02u-%02uT%02u:%02u:%02u.%03uZ", tf.Year, tf.Month, tf.Day, tf.Hour, tf.Minute, tf.Second, tf.Milliseconds); //PT_DBG_PRINT(PTDBG_TRACE_ROUTINES, // ("claimsman!claimsmanInitializeMessage: message->TimeStamp: %ws\n", message->TimeStamp)); }
VOID ExGetNextWakeTime ( OUT PULONGLONG DueTime, OUT PTIME_FIELDS TimeFields, OUT PVOID *TimerObject ) { PLIST_ENTRY Link; PETIMER ExTimer; PETIMER BestTimer; KIRQL OldIrql; ULONGLONG TimerDueTime; ULONGLONG BestDueTime; ULONGLONG InterruptTime; LARGE_INTEGER SystemTime; LARGE_INTEGER CmosTime; ExAcquireSpinLock(&ExpWakeTimerListLock, &OldIrql); BestDueTime = 0; BestTimer = NULL; Link = ExpWakeTimerList.Flink; while (Link != &ExpWakeTimerList) { ExTimer = CONTAINING_RECORD(Link, ETIMER, WakeTimerListEntry); Link = Link->Flink; if (ExTimer->WakeTimer) { TimerDueTime = KeQueryTimerDueTime(&ExTimer->KeTimer); TimerDueTime = 0 - TimerDueTime; // // Is this timers due time closer? // if (TimerDueTime > BestDueTime) { BestDueTime = TimerDueTime; BestTimer = ExTimer; } } else { // // Timer is not an active wake timer, remove it // RemoveEntryList(&ExTimer->WakeTimerListEntry); ExTimer->WakeTimerListEntry.Flink = NULL; } } ExReleaseSpinLock(&ExpWakeTimerListLock, OldIrql); if (BestDueTime) { // // Convert time to timefields // KeQuerySystemTime (&SystemTime); InterruptTime = KeQueryInterruptTime (); BestDueTime = 0 - BestDueTime; SystemTime.QuadPart += BestDueTime - InterruptTime; // // Many system alarms are only good to 1 second resolution. // Add one sceond to the target time so that the timer is really // elasped if this is the wake event. // SystemTime.QuadPart += 10000000; ExSystemTimeToLocalTime(&SystemTime,&CmosTime); RtlTimeToTimeFields(&CmosTime, TimeFields); } *DueTime = BestDueTime; *TimerObject = BestTimer; }
/*++ * @name RtlCliDumpFileInfo * * The RtlCliDumpFileInfo routine FILLMEIN * * @param DirInfo * FILLMEIN * * @return None. * * @remarks Documentation for this routine needs to be completed. * *--*/ VOID RtlCliDumpFileInfo(PFILE_BOTH_DIR_INFORMATION DirInfo) { PWCHAR Null; WCHAR Save; TIME_FIELDS Time; CHAR SizeString[16]; WCHAR ShortString[12+1]; WCHAR FileString[MAX_PATH+1]; WCHAR FileStringSize[100]; WCHAR ShortStringSize[100]; UINT file_size = 0; UINT short_size = 0; // // The filename isn't null-terminated, and the next structure follows // right after it. So, we save the next char (which ends up being the // NextEntryOffset of the next structure), then temporarly clear it so // that the RtlCliDisplayString can treat it as a null-terminated string // Null = (PWCHAR)((PBYTE)DirInfo->FileName + DirInfo->FileNameLength); Save = *Null; *Null = 0; // // Get the last access time // RtlSystemTimeToLocalTime(&DirInfo->CreationTime, &DirInfo->CreationTime); RtlTimeToTimeFields(&DirInfo->CreationTime, &Time); // // Don't display sizes for directories // if (!(DirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { sprintf(SizeString, "%d", DirInfo->AllocationSize.LowPart); } else { sprintf(SizeString, " ", DirInfo->AllocationSize.LowPart); } // // Display this entry // // 75 symbols. file_size = DirInfo->FileNameLength / sizeof(WCHAR); short_size = DirInfo->ShortNameLength / sizeof(WCHAR); swprintf(ShortStringSize, L"%d", short_size); swprintf(FileStringSize, L"%d", file_size); if (DirInfo->ShortNameLength) { memset(ShortString, 0x00, (12+1)*sizeof(WCHAR)); wcsncpy(ShortString, DirInfo->ShortName, short_size); } else { swprintf(ShortString, L" "); } if (DirInfo->FileNameLength) { memset(FileString, 0x00, (MAX_PATH+1)*sizeof(WCHAR)); wcsncpy(FileString, DirInfo->FileName, file_size); } else { swprintf(FileString, L" "); } RtlCliDisplayString("%02d.%02d.%04d %02d:%02d %s %9s %-28S %12S\n", Time.Day, Time.Month, Time.Year, Time.Hour, Time.Minute, DirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ? "<DIR>" : " ", SizeString, FileString, ShortString); // // Restore the character that was here before // *Null = Save; }
EXTERN_C NTSTATUS EnumDirectory( char *lpDirName ) { NTSTATUS status, fStatus; ULONG dwBytesReturned; OBJECT_ATTRIBUTES objectAttributes; PDEVICE_OBJECT lpDeviceObject; IO_STACK_LOCATION iost; PIO_STACK_LOCATION lpsp; IO_STATUS_BLOCK IoStatus; HANDLE hFile = NULL; PFILE_DIRECTORY_INFORMATION lpInformation; PDIRECTORY_INFO lpDirInfo = NULL, lpPreDirInfo = NULL; PFILE_OBJECT lpFileObject = NULL; UNICODE_STRING unFileName; ANSI_STRING anFileName; HANDLE eventHandle = NULL; CHAR buffer[1024]; PUCHAR lpNext; dwBytesReturned = 0; status = STATUS_UNSUCCESSFUL; RtlZeroMemory(buffer,1024); strcpy(buffer,"\\DosDevices\\"); strcat(buffer,lpDirName); RtlInitAnsiString(&anFileName,buffer); RtlAnsiStringToUnicodeString(&unFileName,&anFileName,TRUE); InitializeObjectAttributes(&objectAttributes,&unFileName,OBJ_CASE_INSENSITIVE + OBJ_KERNEL_HANDLE,NULL,NULL); __try { //打开文件 fStatus = ZwOpenFile(&hFile,\ FILE_LIST_DIRECTORY | SYNCHRONIZE | FILE_ANY_ACCESS,\ &objectAttributes,\ &IoStatus,\ FILE_SHARE_READ | FILE_SHARE_WRITE| FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT); ObReferenceObjectByHandle(hFile, FILE_LIST_DIRECTORY | SYNCHRONIZE, 0, KernelMode, (PVOID *)&lpFileObject, NULL); status = ZwCreateEvent(&eventHandle, GENERIC_ALL, 0, NotificationEvent, FALSE); lpInformation = (PFILE_DIRECTORY_INFORMATION)ExAllocatePool(PagedPool, 655350); status = ZwQueryDirectoryFile(hFile, eventHandle,0, 0, &IoStatus, lpInformation, 655350, FileDirectoryInformation, FALSE, NULL, FALSE ); if (!NT_SUCCESS(status) && status != STATUS_PENDING) { goto LeaveBefore; } if (status == STATUS_PENDING) { KeWaitForSingleObject(eventHandle, Executive, KernelMode, TRUE, 0); } FreePagedLookasideListForDirectory(); g_pPageListDirectory = (PPAGED_LOOKASIDE_LIST)ExAllocatePool(PagedPool, sizeof(PAGED_LOOKASIDE_LIST)); ExInitializePagedLookasideList(g_pPageListDirectory, NULL, NULL, 0, sizeof(DIRECTORY_INFO), NULL, 0); while(1) { lpDirInfo = (PDIRECTORY_INFO)ExAllocateFromPagedLookasideList(g_pPageListDirectory); RtlZeroMemory(lpDirInfo, sizeof(DIRECTORY_INFO)); RtlCopyMemory(lpDirInfo->FileName, lpInformation->FileName, lpInformation->FileNameLength); lpDirInfo->AllocationSize = lpInformation->AllocationSize; lpDirInfo->FileAttributes = lpInformation->FileAttributes; RtlTimeToTimeFields(&(lpInformation->CreationTime), &(lpDirInfo->CreationTime)); RtlTimeToTimeFields(&(lpInformation->LastAccessTime), &(lpDirInfo->LastAccessTime)); RtlTimeToTimeFields(&(lpInformation->LastWriteTime), &(lpDirInfo->LastWriteTime)); RtlTimeToTimeFields(&(lpInformation->ChangeTime), &(lpDirInfo->ChangeTime)); lpDirInfo->next = NULL; if (NULL == g_pDirectoryInfo) { g_pDirectoryInfo = lpDirInfo; lpPreDirInfo = lpDirInfo; } else { lpPreDirInfo->next = lpDirInfo; lpPreDirInfo = lpDirInfo; } if(!lpInformation->NextEntryOffset) { break; } lpInformation = (PFILE_DIRECTORY_INFORMATION)((PUCHAR)lpInformation + lpInformation->NextEntryOffset); } LeaveBefore: ; } __finally { if (NT_SUCCESS(fStatus)) { ZwClose(hFile); } if (NULL != lpFileObject) { ObDereferenceObject(lpFileObject); lpFileObject = NULL; } if (NULL != eventHandle) { ZwClose(eventHandle); eventHandle = NULL; } } return status; }