-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy pathntop.c
2001 lines (1690 loc) · 51.7 KB
/
ntop.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* NTop - an htop clone for Windows
* Copyright (c) 2019 Gian Sass
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <windows.h>
#include <psapi.h>
#include <lmcons.h>
#include <tchar.h>
#include <tlhelp32.h>
#include <assert.h>
#include <conio.h>
#include <pdh.h>
#include <stdio.h>
#include <math.h>
#include "ntop.h"
#include "util.h"
#include "vi.h"
#ifndef NTOP_VER
#define NTOP_VER "dev"
#endif
#define STRINGIZE(x) #x
#define STRINGIZE_VALUE_OF(x) STRINGIZE(x)
#define SCROLL_INTERVAL 20ULL
#define INPUT_LOOP_DELAY 30
#define CARET_INTERVAL 500
#define MAX_NAMEPARTS 10
#define MAX_NAMEPARTSIZE 255
static int Width;
static int Height;
static int OldWidth;
static int OldHeight;
static int SizeX;
static int SizeY;
static const int ProcessWindowPosY = 6;
static DWORD ProcessWindowHeight;
static DWORD VisibleProcessCount;
static WORD SavedAttributes;
HANDLE ConsoleHandle;
static HANDLE OldConsoleHandle;
static BOOL InteractiveMode = TRUE;
static CRITICAL_SECTION SyncLock;
static int ConPrintf(TCHAR *Fmt, ...)
{
TCHAR Buffer[1024];
va_list VaList;
va_start(VaList, Fmt);
int CharsWritten = _vstprintf_s(Buffer, _countof(Buffer), Fmt, VaList);
va_end(VaList);
DWORD Dummy;
WriteFile(ConsoleHandle, Buffer, CharsWritten, &Dummy, 0);
return CharsWritten;
}
static void ConPutc(TCHAR c)
{
DWORD Dummy;
WriteFile(ConsoleHandle, &c, 1, &Dummy, 0);
}
#define FOREGROUND_WHITE (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE)
#define FOREGROUND_CYAN (FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE)
#define BACKGROUND_WHITE (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE)
#define BACKGROUND_CYAN (BACKGROUND_INTENSITY | BACKGROUND_GREEN | BACKGROUND_BLUE)
typedef struct config {
WORD FGColor;
WORD BGColor;
WORD FGHighlightColor;
WORD BGHighlightColor;
WORD MenuBarColor;
WORD ProcessListHeaderColor;
WORD CPUBarColor;
WORD MemoryBarColor;
WORD PageMemoryBarColor;
WORD ErrorColor;
ULONGLONG RedrawInterval;
} config;
static config Config = {
/* Default values */
FOREGROUND_WHITE,
FOREGROUND_INTENSITY,
FOREGROUND_CYAN,
BACKGROUND_CYAN,
BACKGROUND_BLUE,
BACKGROUND_GREEN,
FOREGROUND_RED,
FOREGROUND_GREEN,
FOREGROUND_GREEN,
BACKGROUND_RED | FOREGROUND_WHITE,
1000
};
static config MonochromeConfig = {
FOREGROUND_WHITE,
FOREGROUND_INTENSITY,
FOREGROUND_INTENSITY | FOREGROUND_WHITE,
BACKGROUND_WHITE,
0,
BACKGROUND_WHITE,
FOREGROUND_WHITE,
FOREGROUND_WHITE,
FOREGROUND_WHITE,
BACKGROUND_WHITE,
1000
};
static void ParseConfigLine(char *Line)
{
const char *Delimeter = " \t\n";
char *Context;
char *Key = strtok_s(Line, Delimeter, &Context);
if(!Key)
return;
if(Key[0] == '#') /* Comment char*/
return;
char *Value = strtok_s(0, Delimeter, &Context);
if(!Value)
return;
WORD Num = (WORD)strtol(Value, 0, 0);
if(_strcmpi(Key, "FGColor") == 0) {
Config.FGColor = Num;
} else if(_strcmpi(Key, "BGColor") == 0) {
Config.BGColor = Num;
} else if(_strcmpi(Key, "FGHighlightColor") == 0) {
Config.FGHighlightColor = Num;
} else if(_strcmpi(Key, "FGHighlightColor") == 0) {
Config.BGHighlightColor = Num;
} else if(_strcmpi(Key, "MenuBarColor") == 0) {
Config.MenuBarColor = Num;
} else if(_strcmpi(Key, "ProcessListHeaderColor") == 0) {
Config.ProcessListHeaderColor = Num;
} else if(_strcmpi(Key, "CPUBarColor") == 0) {
Config.CPUBarColor = Num;
} else if(_strcmpi(Key, "MemoryBarColor") == 0) {
Config.MemoryBarColor = Num;
} else if(_strcmpi(Key, "PageMemoryBarColor") == 0) {
Config.PageMemoryBarColor = Num;
} else if(_strcmpi(Key, "ErrorColor") == 0) {
Config.ErrorColor = Num;
} else if(_strcmpi(Key, "RedrawInterval") == 0) {
Config.RedrawInterval = (ULONGLONG)Num;
}
}
#define BUF_INCREASE 256
static void ReadConfigFile(void)
{
FILE *File;
errno_t Error;
char exePath[MAX_PATH];
char configPath[MAX_PATH];
// Get executable path
if(GetModuleFileNameA(NULL, exePath, MAX_PATH) == 0)
return;
// Remove executable name to get directory
char *lastSlash = strrchr(exePath, '\\');
if(lastSlash != NULL)
*lastSlash = '\0';
// Construct config file path
snprintf(configPath, MAX_PATH, "%s\\ntop.conf", exePath);
Error = fopen_s(&File, configPath, "r");
if(Error != 0) {
OutputDebugStringA("Did not open config file!\n");
return;
}
size_t BufferSize = BUF_INCREASE;
size_t Offset = 0;
char *Buffer = xmalloc(BUF_INCREASE);
while(1) {
if(!fgets(Offset + Buffer, (int)(BufferSize - Offset), File)) {
break;
}
if(!feof(File) && !strchr(Buffer, '\n')) {
Offset = BufferSize - 1;
BufferSize += BUF_INCREASE;
Buffer = xrealloc(Buffer, BufferSize);
} else {
Offset = 0;
ParseConfigLine(Buffer);
}
}
free(Buffer);
fclose(File);
}
static WORD CurrentColor;
static WORD ColorOverride;
static void SetColor(WORD Color)
{
Color |= ColorOverride;
CurrentColor = Color;
SetConsoleTextAttribute(ConsoleHandle, Color);
}
static void SetConCursorPos(SHORT X, SHORT Y)
{
COORD Coord;
Coord.X = X;
Coord.Y = Y;
SetConsoleCursorPosition(ConsoleHandle, Coord);
}
typedef struct process {
HANDLE Handle;
DWORD ID;
TCHAR UserName[UNLEN];
DWORD BasePriority;
double PercentProcessorTime;
unsigned __int64 UsedMemory;
DWORD ThreadCount;
ULONGLONG UpTime;
TCHAR ExeName[MAX_PATH];
DWORD ParentPID;
ULONGLONG DiskOperationsPrev;
ULONGLONG DiskOperations;
DWORD DiskUsage;
DWORD TreeDepth;
struct process *Next;
struct process *Parent;
struct process *FirstChild;
} process;
#define PROCLIST_BUF_INCREASE 64
static process *ProcessList;
static process *NewProcessList;
static DWORD ProcessListSize = PROCLIST_BUF_INCREASE;
static DWORD *TaggedProcessList;
static DWORD TaggedProcessListCount;
static DWORD TaggedProcessListSize = PROCLIST_BUF_INCREASE;
static void IncreaseProcListSize(void)
{
ProcessListSize += PROCLIST_BUF_INCREASE;
NewProcessList = xrealloc(NewProcessList, ProcessListSize * sizeof *NewProcessList);
ProcessList = xrealloc(ProcessList, ProcessListSize * sizeof *ProcessList);
}
static void ToggleTaggedProcess(DWORD ID)
{
for(DWORD i = 0; i < TaggedProcessListCount; i++) {
if(TaggedProcessList[i] == ID) {
for(; i < TaggedProcessListCount-1;i++) {
TaggedProcessList[i] = TaggedProcessList[i+1];
}
TaggedProcessListCount--;
return;
}
}
TaggedProcessList[TaggedProcessListCount++] = ID;
if(TaggedProcessListCount >= TaggedProcessListSize) {
TaggedProcessListSize += PROCLIST_BUF_INCREASE;
TaggedProcessList = xrealloc(TaggedProcessList, PROCLIST_BUF_INCREASE * sizeof *TaggedProcessList);
}
}
static BOOL IsProcessTagged(DWORD ID)
{
for(DWORD i = 0; i < TaggedProcessListCount; i++) {
if(TaggedProcessList[i] == ID)
return TRUE;
}
return FALSE;
}
static DWORD ProcessCount = 0;
static DWORD RunningProcessCount = 0;
static DWORD ProcessIndex = 0;
static DWORD SelectedProcessIndex = 0;
static DWORD SelectedProcessID = 0;
static BOOL FollowProcess = FALSE;
static DWORD FollowProcessID = 0;
typedef enum sort_order {
ASCENDING,
DESCENDING
} sort_order;
static sort_order SortOrder = DESCENDING;
typedef int (*process_sort_fn_t)(const void *, const void *);
#define SORT_PROCESS_BY_INTEGER(Attribute) \
static int SortProcessBy##Attribute(const void *A, const void *B) \
{ \
int Compare = (int)(((const process *)A)->Attribute - ((const process *)B)->Attribute); \
return (SortOrder == ASCENDING) ? Compare : -Compare; \
} \
#define SORT_PROCESS_BY_UINT64(Attribute) \
static int SortProcessBy##Attribute(const void *A, const void *B) \
{ \
__int64 Compare = (__int64)(((const process *)A)->Attribute - ((const process *)B)->Attribute); \
int Result = (Compare > 1) ? 1 : -1; \
return (SortOrder == ASCENDING) ? Result : -Result; \
} \
#define SORT_PROCESS_BY_DOUBLE(Attribute) \
static int SortProcessBy##Attribute(const void *A, const void *B) \
{ \
double Diff = (((const process *)A)->Attribute - ((const process *)B)->Attribute); \
if (Diff > 0.0) return (SortOrder == ASCENDING) ? 1 : -1; \
if (Diff < 0.0) return (SortOrder == ASCENDING) ? -1 : 1; \
return 0; \
} \
#define SORT_PROCESS_BY_STRING(Attribute, MaxLength) \
static int SortProcessBy##Attribute(const void *A, const void *B) \
{ \
int Compare = _tcsncicmp(((const process *)A)->Attribute, ((const process *)B)->Attribute, MaxLength); \
return (SortOrder == ASCENDING) ? Compare : -Compare; \
} \
SORT_PROCESS_BY_INTEGER(ID);
SORT_PROCESS_BY_DOUBLE(PercentProcessorTime);
SORT_PROCESS_BY_UINT64(UsedMemory);
SORT_PROCESS_BY_INTEGER(UpTime);
SORT_PROCESS_BY_INTEGER(BasePriority);
SORT_PROCESS_BY_INTEGER(ThreadCount);
SORT_PROCESS_BY_INTEGER(ParentPID);
SORT_PROCESS_BY_INTEGER(DiskUsage);
SORT_PROCESS_BY_STRING(ExeName, MAX_PATH);
SORT_PROCESS_BY_STRING(UserName, UNLEN);
static process_sort_type ProcessSortType = SORT_BY_ID;
static TCHAR OSName[256];
static DWORD CPUCoreCount;
static double CPUUsage;
static ULONGLONG SubtractTimes(const FILETIME *A, const FILETIME *B)
{
LARGE_INTEGER lA, lB;
lA.LowPart = A->dwLowDateTime;
lA.HighPart = A->dwHighDateTime;
lB.LowPart = B->dwLowDateTime;
lB.HighPart = B->dwHighDateTime;
return lA.QuadPart - lB.QuadPart;
}
void AddChildProcess(process *ParentProcess, process *Process)
{
if(ParentProcess == Process) return;
if (ParentProcess->FirstChild == NULL) {
ParentProcess->FirstChild = Process;
} else {
process *ChildProcess = ParentProcess->FirstChild;
while (ChildProcess->Next != NULL) {
ChildProcess = ChildProcess->Next;
if(ChildProcess == Process) return;
}
ChildProcess->Next = Process;
}
Process->Parent = ParentProcess;
}
/* The "root" process which does not actually exist, acts as process tree root */
static process RootProcess;
/* Finds and assigns parent and child processes */
void FindParentChildProcesses(void)
{
memset(&RootProcess, 0, sizeof(RootProcess));
/* Find and assign parent and child processes that have ParentPID=0 */
for (DWORD i = 0; i < ProcessCount; i++)
{
ProcessList[i].TreeDepth = 0;
ProcessList[i].Next = 0;
ProcessList[i].Parent = 0;
ProcessList[i].FirstChild = 0;
// if (ProcessList[i].ParentPID == 0)
// {
// AddChildProcess(&RootProcess, &ProcessList[i]);
// }
}
/* Find and assign parent and child processes */
for (DWORD i = 0; i < ProcessCount; i++)
{
for (DWORD j = 0; j < ProcessCount; j++)
{
if (i == j)
continue;
if (ProcessList[j].ParentPID == ProcessList[i].ID && ProcessList[j].ParentPID != 0 && ProcessList[i].ID != ProcessList[j].ID && ProcessList[j].Next == NULL)
{
/* i is a parent of j */
AddChildProcess(&ProcessList[i], &ProcessList[j]);
ProcessList[j].TreeDepth = ProcessList[i].TreeDepth + 1;
}
}
}
/* Add processes with PIDs that couldn't be found to RootProcess or else
* they won't be shown */
for (DWORD i = 0; i < ProcessCount; i++)
{
process *Process = &ProcessList[i];
if (Process->Parent == NULL)
{
AddChildProcess(&RootProcess, Process);
}
}
}
void ProcessTreeToList(process *Process, process *Dest, int *Index)
{
process *ProcessNode = Process->FirstChild;
if(ProcessNode == NULL) return;
while(ProcessNode != NULL) {
Dest[*Index] = *ProcessNode;
*Index = *Index + 1;
ProcessTreeToList(ProcessNode, Dest, Index);
ProcessNode = ProcessNode->Next;
}
}
static void SortProcessList(void)
{
if(ProcessSortType != SORT_BY_TREE)
{
process_sort_fn_t SortFn = 0;
switch(ProcessSortType) {
case SORT_BY_ID:
SortFn = SortProcessByID;
break;
case SORT_BY_PROCESS:
SortFn = SortProcessByExeName;
break;
case SORT_BY_USER_NAME:
SortFn = SortProcessByUserName;
break;
case SORT_BY_PROCESSOR_TIME:
SortFn = SortProcessByPercentProcessorTime;
break;
case SORT_BY_USED_MEMORY:
SortFn = SortProcessByUsedMemory;
break;
case SORT_BY_UPTIME:
SortFn = SortProcessByUpTime;
break;
case SORT_BY_PRIORITY:
SortFn = SortProcessByBasePriority;
break;
case SORT_BY_THREAD_COUNT:
SortFn = SortProcessByThreadCount;
break;
case SORT_BY_DISK_USAGE:
SortFn = SortProcessByDiskUsage;
break;
}
if(SortFn) {
qsort(ProcessList, ProcessCount, sizeof(*ProcessList), SortFn);
}
FindParentChildProcesses();
} else {
SortOrder = ASCENDING;
qsort(ProcessList, ProcessCount, sizeof(*ProcessList), SortProcessByParentPID);
FindParentChildProcesses();
process *TreeProcessList = xmalloc(ProcessCount * sizeof(*ProcessList));
int Index = 0;
ProcessTreeToList(&RootProcess, TreeProcessList, &Index);
ProcessCount = Index;
memcpy(ProcessList, TreeProcessList, ProcessCount * sizeof(*ProcessList));
free(TreeProcessList);
}
}
static BOOL FilterByUserName = FALSE;
static TCHAR FilterUserName[UNLEN];
static BOOL FilterByPID = FALSE;
static DWORD PidFilterList[1024];
static DWORD PidFilterCount;
static BOOL FilterByName = FALSE;
static TCHAR NameFilterList[MAX_NAMEPARTS][MAX_NAMEPARTSIZE+1];
static DWORD NameFilterCount;
static void SelectProcess(DWORD Index)
{
SelectedProcessIndex = Index;
if(SelectedProcessIndex <= ProcessIndex - 1 && ProcessIndex != 0) {
ProcessIndex = SelectedProcessIndex;
}
if(SelectedProcessIndex - ProcessIndex >= VisibleProcessCount) {
ProcessIndex = min(ProcessCount - VisibleProcessCount, SelectedProcessIndex);
}
}
static void ReadjustCursor(void)
{
if(FollowProcess) {
BOOL Found = FALSE;
for(DWORD i = 0; i < ProcessCount; i++) {
if(ProcessList[i].ID == FollowProcessID) {
SelectProcess(i);
Found = TRUE;
break;
}
}
if(!Found) {
/* Process got lost, might as well disable this now */
FollowProcess = FALSE;
}
} else {
/* After process list update ProcessIndex and SelectedProcessIndex may become out of range */
ProcessIndex = min(ProcessIndex, ProcessCount - VisibleProcessCount);
SelectedProcessIndex = min(SelectedProcessIndex, ProcessCount - 1);
}
}
static TCHAR SearchPattern[256];
static BOOLEAN CaseInsensitiveSearch = FALSE;
static BOOLEAN SearchActive;
static void SearchNext(void);
void StartSearch(const TCHAR *Pattern)
{
_tcsncpy_s(SearchPattern, 256, Pattern, 256);
// if the whole string is lower case use case insensitive search
CaseInsensitiveSearch = TRUE;
for (int i = 0; i < 256; i++)
{
if (SearchPattern[i] == 0)
{
break;
}
if (isupper(SearchPattern[i]))
{
CaseInsensitiveSearch = FALSE;
break;
}
}
SearchActive = TRUE;
SearchNext();
}
static BOOLEAN SearchMatchesProcess(const process *Process)
{
TCHAR TempProcessName[MAX_PATH];
_tcsncpy_s(TempProcessName, MAX_PATH, Process->ExeName, MAX_PATH);
if (CaseInsensitiveSearch) // which means that the SearchPattern is already lower case,
// so we convert the process name to lower case to make the
// search case insensitive
{
for (int i = 0; i < MAX_PATH; i++)
{
if (TempProcessName[i] == 0)
break;
TempProcessName[i] = (TCHAR)tolower(TempProcessName[i]);
}
}
return _tcsstr(TempProcessName, SearchPattern) != 0;
}
static void SearchNext(void)
{
if(!SearchActive) return;
for(DWORD i = SelectedProcessIndex + 1; i < ProcessCount; ++i) {
const process *Process = &ProcessList[i];
if(SearchMatchesProcess(Process)) {
SelectProcess(i);
return;
}
}
SetViMessage(VI_NOTICE, _T("search hit BOTTOM, continuing at TOP"));
for(DWORD i = 0; i <= SelectedProcessIndex; ++i) {
const process *Process = &ProcessList[i];
if(SearchMatchesProcess(Process)) {
SelectProcess(i);
return;
}
}
SetViMessage(VI_ERROR, _T("Pattern not found: %s"), SearchPattern);
}
static void SearchPrevious(void)
{
if(!SearchActive) return;
for(DWORD i = SelectedProcessIndex; i > 0; --i) {
const process *Process = &ProcessList[i - 1];
if(SearchMatchesProcess(Process)) {
SelectProcess(i - 1);
return;
}
}
SetViMessage(VI_NOTICE, _T("search hit TOP, continuing at BOTTOM"));
for(DWORD i = ProcessCount; i > SelectedProcessIndex; --i) {
const process *Process = &ProcessList[i - 1];
if(SearchMatchesProcess(Process)) {
SelectProcess(i - 1);
return;
}
}
SetViMessage(VI_ERROR, _T("Pattern not found: %s"), SearchPattern);
}
static void PollProcessList(DWORD UpdateTime)
{
HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
if(!Snapshot) {
Die(_T("CreateToolhelp32Snapshot failed: %ld\n"), GetLastError());
}
PROCESSENTRY32 Entry;
Entry.dwSize = sizeof(Entry);
BOOL Status = Process32First(Snapshot, &Entry);
if(!Status) {
Die(_T("Process32First failed: %ld\n"), GetLastError());
}
DWORD i = 0;
for(; Status; Status = Process32Next(Snapshot, &Entry)) {
process Process = { 0 };
Process.ID = Entry.th32ProcessID;
if(Process.ID == 0)
continue;
Process.ThreadCount = Entry.cntThreads;
Process.BasePriority = Entry.pcPriClassBase;
Process.ParentPID = Entry.th32ParentProcessID;
_tcsncpy_s(Process.ExeName, MAX_PATH, Entry.szExeFile, MAX_PATH);
_tcsncpy_s(Process.UserName, UNLEN, _T("SYSTEM"), UNLEN);
Process.Handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, Entry.th32ProcessID);
if(Process.Handle) {
PROCESS_MEMORY_COUNTERS ProcMemCounters;
if(GetProcessMemoryInfo(Process.Handle, &ProcMemCounters, sizeof(ProcMemCounters))) {
Process.UsedMemory = (unsigned __int64)ProcMemCounters.WorkingSetSize;
}
HANDLE ProcessTokenHandle;
if(OpenProcessToken(Process.Handle, TOKEN_READ, &ProcessTokenHandle)) {
DWORD ReturnLength;
GetTokenInformation(ProcessTokenHandle, TokenUser, 0, 0, &ReturnLength);
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
PTOKEN_USER TokenUserStruct = xmalloc(ReturnLength);
if(GetTokenInformation(ProcessTokenHandle, TokenUser, TokenUserStruct, ReturnLength, &ReturnLength)) {
SID_NAME_USE NameUse;
DWORD NameLength = UNLEN;
TCHAR DomainName[MAX_PATH];
DWORD DomainLength = MAX_PATH;
LookupAccountSid(0, TokenUserStruct->User.Sid, Process.UserName, &NameLength, DomainName, &DomainLength, &NameUse);
// FIXME: we cut user name here for display purposes because something like %9.9s does not work with MS's vsprintf function?
Process.UserName[9] = 0;
}
free(TokenUserStruct);
}
CloseHandle(ProcessTokenHandle);
}
}
if(FilterByUserName && lstrcmpi(Process.UserName, FilterUserName) != 0) {
continue;
}
if(FilterByPID) {
BOOL InFilter = FALSE;
for(DWORD PidIndex = 0; PidIndex < PidFilterCount; PidIndex++) {
if(PidFilterList[PidIndex] == Process.ID) {
InFilter = TRUE;
}
}
if(!InFilter) {
continue;
}
}
if (FilterByName) {
BOOL InFilter = FALSE;
for(DWORD NameIndex = 0; NameIndex < NameFilterCount; NameIndex++) {
if(strstr(Process.ExeName, NameFilterList[NameIndex]) != NULL) {
InFilter = TRUE;
}
}
if (!InFilter) {
continue;
}
}
NewProcessList[i++] = Process;
if(i >= ProcessListSize) {
IncreaseProcListSize();
}
}
CloseHandle(Snapshot);
DWORD NewProcessCount = i;
typedef struct system_times
{
FILETIME IdleTime, KernelTime, UserTime;
} system_times;
system_times PrevSysTimes;
GetSystemTimes(&PrevSysTimes.IdleTime, &PrevSysTimes.KernelTime, &PrevSysTimes.UserTime);
typedef struct process_times
{
FILETIME CreationTime, ExitTime, KernelTime, UserTime;
} process_times;
process_times *ProcessTimes = (process_times *)xmalloc(NewProcessCount * sizeof(*ProcessTimes));
for(DWORD ProcIndex = 0; ProcIndex < NewProcessCount; ProcIndex++) {
process *Process = &NewProcessList[ProcIndex];
process_times *ProcessTime = &ProcessTimes[ProcIndex];
if(Process->Handle) {
GetProcessTimes(Process->Handle, &ProcessTime->CreationTime, &ProcessTime->ExitTime, &ProcessTime->KernelTime, &ProcessTime->UserTime);
IO_COUNTERS IoCounters;
if(GetProcessIoCounters(Process->Handle, &IoCounters)) {
Process->DiskOperationsPrev = IoCounters.ReadTransferCount + IoCounters.WriteTransferCount;
}
}
}
Sleep(UpdateTime);
system_times SysTimes;
GetSystemTimes(&SysTimes.IdleTime, &SysTimes.KernelTime, &SysTimes.UserTime);
ULONGLONG SysKernelDiff = SubtractTimes(&SysTimes.KernelTime, &PrevSysTimes.KernelTime);
ULONGLONG SysUserDiff = SubtractTimes(&SysTimes.UserTime, &PrevSysTimes.UserTime);
ULONGLONG SysIdleDiff = SubtractTimes(&SysTimes.IdleTime, &PrevSysTimes.IdleTime);
RunningProcessCount = 0;
for(DWORD ProcIndex = 0; ProcIndex < NewProcessCount; ProcIndex++) {
process_times ProcessTime = { 0 };
process_times *PrevProcessTime = &ProcessTimes[ProcIndex];
process *Process = &NewProcessList[ProcIndex];
if(Process->Handle) {
GetProcessTimes(Process->Handle, &ProcessTime.CreationTime, &ProcessTime.ExitTime, &ProcessTime.KernelTime, &ProcessTime.UserTime);
ULONGLONG ProcKernelDiff = SubtractTimes(&ProcessTime.KernelTime, &PrevProcessTime->KernelTime);
ULONGLONG ProcUserDiff = SubtractTimes(&ProcessTime.UserTime, &PrevProcessTime->UserTime);
ULONGLONG TotalSys = SysKernelDiff + SysUserDiff;
ULONGLONG TotalProc = ProcKernelDiff + ProcUserDiff;
if(TotalSys > 0) {
Process->PercentProcessorTime = (double)((100.0 * (double)TotalProc) / (double)TotalSys);
if(Process->PercentProcessorTime >= 0.01) {
RunningProcessCount++;
}
}
FILETIME SysTime;
GetSystemTimeAsFileTime(&SysTime);
Process->UpTime = SubtractTimes(&SysTime, &ProcessTime.CreationTime) / 10000;
IO_COUNTERS IoCounters;
if(GetProcessIoCounters(Process->Handle, &IoCounters)) {
Process->DiskOperations = IoCounters.ReadTransferCount + IoCounters.WriteTransferCount;
Process->DiskUsage = (DWORD)((Process->DiskOperations - Process->DiskOperationsPrev) * (1000/UpdateTime));
}
CloseHandle(Process->Handle);
Process->Handle = 0;
}
}
free(ProcessTimes);
/* Since we have the values already we can compute CPU usage too */
ULONGLONG SysTime = SysKernelDiff + SysUserDiff;
if(SysTime > 0) {
double Percentage = (double)(SysTime - SysIdleDiff) / (double)SysTime;
CPUUsage = min(Percentage, 1.0);
}
EnterCriticalSection(&SyncLock);
memcpy(ProcessList, NewProcessList, NewProcessCount * sizeof *ProcessList);
ProcessCount = NewProcessCount;
SortProcessList();
ReadjustCursor();
LeaveCriticalSection(&SyncLock);
}
static void DisableCursor(void)
{
CONSOLE_CURSOR_INFO CursorInfo;
GetConsoleCursorInfo(ConsoleHandle, &CursorInfo);
CursorInfo.bVisible = FALSE; /* Note: this has to be set every time console buffer resizes! */
SetConsoleCursorInfo(ConsoleHandle, &CursorInfo);
}
static WORD GetConsoleColor(void)
{
CONSOLE_SCREEN_BUFFER_INFO Csbi;
GetConsoleScreenBufferInfo(ConsoleHandle, &Csbi);
return Csbi.wAttributes;
}
/*
* Returns TRUE on screen buffer resize.
*/
static BOOL PollConsoleInfo(void)
{
CONSOLE_SCREEN_BUFFER_INFO Csbi;
GetConsoleScreenBufferInfo(ConsoleHandle, &Csbi);
Width = Csbi.srWindow.Right - Csbi.srWindow.Left + 1;
Height = Csbi.srWindow.Bottom - Csbi.srWindow.Top + 1;
if(Width != OldWidth || Height != OldHeight) {
DisableCursor();
COORD Size;
Size.X = (USHORT)Width;
Size.Y = (USHORT)Height;
SetConsoleScreenBufferSize(ConsoleHandle, Size);
OldWidth = Width;
OldHeight = Height;
return TRUE;
}
SizeX = (int)Csbi.dwSize.X;
SizeY = (int)Csbi.dwSize.Y;
if(SavedAttributes == 0)
SavedAttributes = Csbi.wAttributes;
return FALSE;
}
static TCHAR ComputerName[MAX_COMPUTERNAME_LENGTH + 1] = _T("localhost");
static double CPUFrequency;
static TCHAR CPUName[256];
static ULONGLONG TotalMemory;
static ULONGLONG UsedMemory;
static double UsedMemoryPerc;
static ULONGLONG TotalPageMemory;
static ULONGLONG UsedPageMemory;
static double UsedPageMemoryPerc;
#define TO_MB(X) ((X)/1048576)
static ULONGLONG UpTime;
static void PollInitialSystemInfo(void)
{
LARGE_INTEGER PerformanceFrequency;
QueryPerformanceFrequency(&PerformanceFrequency);
CPUFrequency = (double)PerformanceFrequency.QuadPart / 1000000.0;
SYSTEM_INFO SystemInfo;
GetNativeSystemInfo(&SystemInfo);
CPUCoreCount = SystemInfo.dwNumberOfProcessors;
HKEY Key;
if(SUCCEEDED(RegOpenKey(HKEY_LOCAL_MACHINE, _T("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\\"), &Key))) {
DWORD Count = 256;
if(SUCCEEDED(RegQueryValueEx(Key, _T("ProcessorNameString"), 0, 0, (LPBYTE)&CPUName[0], &Count))) {
RegCloseKey(Key);
}
}
DWORD ComputerNameSize = MAX_COMPUTERNAME_LENGTH + 1;
GetComputerName(ComputerName, &ComputerNameSize);
}
static void PollSystemInfo(void)
{
MEMORYSTATUSEX MemoryInfo;
MemoryInfo.dwLength = sizeof(MEMORYSTATUSEX);
GlobalMemoryStatusEx(&MemoryInfo);
TotalMemory = TO_MB(MemoryInfo.ullTotalPhys);
UsedMemory = TO_MB(MemoryInfo.ullTotalPhys - MemoryInfo.ullAvailPhys);
UsedMemoryPerc = (double)UsedMemory / (double)TotalMemory;
TotalPageMemory = TO_MB(MemoryInfo.ullTotalPageFile);
UsedPageMemory = TO_MB(MemoryInfo.ullTotalPageFile - MemoryInfo.ullAvailPageFile);
UsedPageMemoryPerc = (double)UsedPageMemory / (double)TotalPageMemory;
UpTime = GetTickCount64();
}
static HANDLE ProcessListThread;
DWORD WINAPI PollProcessListThreadProc(LPVOID lpParam)
{
UNREFERENCED_PARAMETER(lpParam);
while(1) {
PollProcessList(1000);
}
return 0;
}
typedef enum input_mode {
EXEC,
} input_mode;
static input_mode InputMode = EXEC;
#define TIME_STR_SIZE 12
/*
* Create a dd:hh:mm:ss time-string similar to how the modern taskmgr does it.
*
* The restriction of the day count to two digits is justified by the obvious
* fact that a Windows system cannot possibly reach an uptime of over 100 days
* without crashing.
*/
static void FormatTimeString(TCHAR *Buffer, DWORD BufferSize, ULONGLONG MS)
{
int Seconds = (int)(MS / 1000 % 60);
int Minutes = (int)(MS / 60000 % 60);
int Hours = (int)(MS / 3600000 % 24);
int Days = (int)(MS / 86400000);
_stprintf_s(Buffer, BufferSize, _T("%02d:%02d:%02d:%02d"), Days, Hours, Minutes, Seconds);
}
static void FormatMemoryString(TCHAR *Buffer, DWORD BufferSize, unsigned __int64 Memory)