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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
//! Unified Process Monitoring with GPU Attribution
//!
//! This module provides cross-platform process monitoring with GPU usage attribution.
//! It combines system-wide process enumeration with GPU-specific process tracking from
//! NVIDIA NVML, AMD sysfs, and Intel GPU drivers.
//!
//! The [`ProcessMonitor`] correlates system processes with GPU usage by matching process IDs
//! (PIDs) from GPU driver data with information from `/proc` (Linux), task manager (Windows),
//! or similar platform-specific sources.
//!
//! # Examples
//!
//! ## Basic Process Monitoring
//!
//! ```no_run
//! use ironmonitor::{ProcessMonitor, GpuCollection};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Create monitor with GPU attribution
//! let gpus = GpuCollection::auto_detect()?;
//! let mut monitor = ProcessMonitor::with_gpus(gpus)?;
//!
//! // Get all processes
//! let processes = monitor.processes()?;
//! println!("Total processes: {}", processes.len());
//!
//! // Get GPU processes only
//! let gpu_processes = monitor.gpu_processes()?;
//! println!("GPU processes: {}", gpu_processes.len());
//! # Ok(())
//! # }
//! ```
//!
//! ## Top GPU Consumers
//!
//! ```no_run
//! use ironmonitor::{ProcessMonitor, GpuCollection};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let gpus = GpuCollection::auto_detect()?;
//! let mut monitor = ProcessMonitor::with_gpus(gpus)?;
//!
//! // Get top 10 processes by GPU memory usage
//! let top_gpu = monitor.processes_by_gpu_memory()?;
//! println!("Top GPU consumers:");
//! for proc in top_gpu.iter().take(10) {
//! println!(" {} (PID {}): {} MB on {} GPUs",
//! proc.name,
//! proc.pid,
//! proc.gpu_memory_mb()
//! .map_or_else(|| "n/a".to_string(), |mb| format!("{mb:.0}")),
//! proc.gpu_count()
//! .map_or_else(|| "n/a".to_string(), |n| n.to_string()),
//! );
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Top CPU Consumers
//!
//! ```no_run
//! use ironmonitor::{ProcessMonitor, GpuCollection};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let gpus = GpuCollection::auto_detect()?;
//! let mut monitor = ProcessMonitor::with_gpus(gpus)?;
//!
//! // Get top 10 processes by CPU usage
//! let top_cpu = monitor.processes_by_cpu()?;
//! println!("Top CPU consumers:");
//! for proc in top_cpu.iter().take(10) {
//! // `None` for a process too new to have a lifetime average yet.
//! match proc.cpu_percent {
//! Some(cpu) => println!(" {} (PID {}): {cpu:.1}%", proc.name, proc.pid),
//! None => println!(" {} (PID {}): not yet known", proc.name, proc.pid),
//! }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Monitor Specific Process
//!
//! ```no_run
//! use ironmonitor::{ProcessMonitor, GpuCollection};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let gpus = GpuCollection::auto_detect()?;
//! let mut monitor = ProcessMonitor::with_gpus(gpus)?;
//!
//! // Get specific process by PID
//! if let Some(proc) = monitor.process_by_pid(1234)? {
//! println!("Process: {}", proc.name);
//! if let Some(cpu) = proc.cpu_percent {
//! println!("CPU: {cpu:.1}%");
//! }
//! println!("Memory: {} MB", proc.memory_bytes / 1024 / 1024);
//! match proc.gpu_memory_mb() {
//! Some(mb) => println!("GPU Memory: {mb:.0} MB"),
//! None => println!("GPU Memory: not reported by the driver"),
//! }
//! println!("Using GPUs: {:?}", proc.gpu_indices);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Platform Support
//!
//! | Platform | Process Enum | GPU Attribution | CPU % | Memory | User |
//! |----------|--------------|-----------------|-------|--------|------|
//! | Linux | ✅ /proc | ✅ All vendors | ✅ | ✅ | ✅ |
//! | Windows | ✅ Win32 API | 🚧 | ✅ | ✅ | ✅ |
//! | macOS | ✅ libproc | 🚧 | ✅ | ✅ | 🚧 |
use crate::error::{IronError, Result};
use crate::gpu::GpuCollection;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Process category for smart classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum ProcessCategory {
/// System kernel and core OS processes
System,
/// System services and daemons
Service,
/// Desktop environment and window managers
Desktop,
/// Web browsers
Browser,
/// Development tools (IDEs, compilers, debuggers)
Development,
/// AI/ML frameworks and tools
AiMl,
/// Games and game engines
Gaming,
/// Media players and editors
Media,
/// Communication apps (chat, video calls)
Communication,
/// Productivity apps (office, notes)
Productivity,
/// Containers and virtualization
Container,
/// Network and security tools
Network,
/// Database servers
Database,
/// Holds a GPU context, and nothing else identifies it.
///
/// Not a claim that the process is computing on the GPU: on Windows every
/// windowed application holds one, and NVML reports `C+G` for all of them.
GpuCompute,
/// Shell and terminal processes
Shell,
/// User applications (uncategorized)
Application,
/// Unknown/unclassified processes
#[default]
Unknown,
}
impl ProcessCategory {
/// Classify a process by its name and characteristics
pub fn classify(name: &str, user: Option<&str>, is_gpu_process: bool) -> Self {
let name_lower = name.to_lowercase();
// A process holding a GPU context is not thereby a GPU workload.
//
// This branch used to run first and end with `return Self::GpuCompute`
// for anything not matching an AI/ML or game name, so every windowed
// application on Windows landed there: `ironmon cli processes` reported
// 24 processes under "GPU Compute", the top five being
// WindowsTerminal.exe, brave.exe, Code.exe and a Logitech settings
// agent. `nvidia-smi` labels all of them `C+G` with `[N/A]` memory —
// they are drawing windows.
//
// The AI/ML and game checks stay here, because a GPU context plus one
// of those names is real evidence. Everything else falls through to be
// classified by what it is, so a browser is a browser.
if is_gpu_process {
// AI/ML specific
if Self::matches_any(
&name_lower,
&[
"python",
"python3",
"jupyter",
"conda",
"pytorch",
"tensorflow",
"torch",
"ollama",
"llama",
"whisper",
"stable-diffusion",
"comfyui",
"automatic1111",
"onnx",
"triton",
"vllm",
"tgi",
],
) {
return Self::AiMl;
}
// Games
if Self::matches_any(
&name_lower,
&[
"steam", "game", "unity", "unreal", "godot", "wine", "proton", "lutris",
"heroic", "bottles",
],
) {
return Self::Gaming;
}
// No `return Self::GpuCompute` here. Fall through.
}
// System processes (PID 1, kernel threads, etc.)
if Self::matches_any(
&name_lower,
&[
"init",
"systemd",
"kernel",
"kthread",
"ksoftirq",
"kworker",
"rcu_",
"migration",
"watchdog",
"cpuhp",
"idle",
"swapper",
"launchd",
"system",
"csrss",
"smss",
"wininit",
"services",
"lsass",
"svchost",
"dwm",
"ntoskrnl",
],
) {
return Self::System;
}
// Services and daemons
if Self::matches_any(
&name_lower,
&[
"cron",
"crond",
"atd",
"cupsd",
"avahi",
"dbus",
"udev",
"polkit",
"udisks",
"accounts-daemon",
"colord",
"fwupd",
"gdm",
"lightdm",
"sddm",
"login",
"getty",
"agetty",
"su",
"sudo",
"ssh",
"sshd",
"rsyslog",
"journald",
"logind",
"networkmanager",
"wpa_supplicant",
"dhclient",
"thermald",
"irqbalance",
"snapd",
"flatpak",
"packagekit",
"apt",
"dnf",
"yum",
"pacman",
"zypper",
],
) {
return Self::Service;
}
// Desktop environments
if Self::matches_any(
&name_lower,
&[
"gnome",
"kde",
"plasma",
"xfce",
"mate",
"cinnamon",
"lxde",
"lxqt",
"i3",
"sway",
"hyprland",
"awesome",
"bspwm",
"dwm",
"openbox",
"fluxbox",
"xorg",
"x11",
"wayland",
"mutter",
"kwin",
"picom",
"compton",
"compositor",
"nautilus",
"dolphin",
"thunar",
"nemo",
"caja",
"pcmanfm",
"explorer",
"finder",
"gvfs",
"tracker",
"baloo",
"mimeapps",
"xdg-",
],
) {
return Self::Desktop;
}
// Browsers
if Self::matches_any(
&name_lower,
&[
"firefox",
"chrome",
"chromium",
"brave",
"edge",
"safari",
"opera",
"vivaldi",
"librewolf",
"waterfox",
"tor-browser",
"qutebrowser",
"web-content",
"webextension",
"gpu-process",
],
) {
return Self::Browser;
}
// Development tools
if Self::matches_any(
&name_lower,
&[
"code",
"vscode",
"codium",
"vim",
"nvim",
"neovim",
"emacs",
"sublime",
"atom",
"jetbrains",
"idea",
"pycharm",
"webstorm",
"clion",
"rider",
"goland",
"rust-analyzer",
"gopls",
"clangd",
"pylsp",
"tsserver",
"node",
"npm",
"yarn",
"pnpm",
"cargo",
"rustc",
"gcc",
"g++",
"clang",
"make",
"cmake",
"ninja",
"git",
"gh",
"gdb",
"lldb",
"valgrind",
"strace",
"ltrace",
"perf",
"htop",
"btop",
"top",
"docker-compose",
"kubectl",
],
) {
return Self::Development;
}
// AI/ML tools (non-GPU or pre-GPU detection)
if Self::matches_any(
&name_lower,
&[
"python", "python3", "jupyter", "ipython", "conda", "pip", "poetry", "pdm", "uv",
"ruff", "mypy",
],
) {
return Self::AiMl;
}
// Media
if Self::matches_any(
&name_lower,
&[
"vlc",
"mpv",
"mplayer",
"totem",
"celluloid",
"parole",
"rhythmbox",
"spotify",
"audacious",
"clementine",
"lollypop",
"gimp",
"inkscape",
"krita",
"blender",
"kdenlive",
"shotcut",
"obs",
"ffmpeg",
"handbrake",
"audacity",
"ardour",
"lmms",
"darktable",
"rawtherapee",
"digikam",
"shotwell",
"eog",
"gwenview",
"feh",
"sxiv",
"mpd",
"pulseaudio",
"pipewire",
"wireplumber",
"alsa",
"jack",
],
) {
return Self::Media;
}
// Communication
if Self::matches_any(
&name_lower,
&[
"discord",
"slack",
"teams",
"zoom",
"skype",
"telegram",
"signal",
"element",
"matrix",
"thunderbird",
"evolution",
"geary",
"mutt",
"neomutt",
"weechat",
"irssi",
"hexchat",
],
) {
return Self::Communication;
}
// Productivity
if Self::matches_any(
&name_lower,
&[
"libreoffice",
"soffice",
"writer",
"calc",
"impress",
"obsidian",
"notion",
"joplin",
"simplenote",
"standard-notes",
"zettlr",
"logseq",
"roam",
"okular",
"evince",
"zathura",
"calibre",
"foliate",
"gnome-calendar",
"gnome-contacts",
],
) {
return Self::Productivity;
}
// Containers & Virtualization
if Self::matches_any(
&name_lower,
&[
"docker",
"containerd",
"runc",
"cri-o",
"podman",
"buildah",
"skopeo",
"kubernetes",
"kubelet",
"k3s",
"k8s",
"minikube",
"qemu",
"kvm",
"libvirt",
"virt-manager",
"virtualbox",
"vmware",
"vagrant",
"lxc",
"lxd",
"incus",
"systemd-nspawn",
],
) {
return Self::Container;
}
// Network & Security
if Self::matches_any(
&name_lower,
&[
"nginx",
"apache",
"httpd",
"caddy",
"traefik",
"haproxy",
"squid",
"dnsmasq",
"bind",
"named",
"unbound",
"pihole",
"openvpn",
"wireguard",
"iptables",
"nftables",
"firewalld",
"ufw",
"fail2ban",
"snort",
"suricata",
"wireshark",
"tcpdump",
"nmap",
"curl",
"wget",
"rsync",
"syncthing",
"rclone",
],
) {
return Self::Network;
}
// Databases
if Self::matches_any(
&name_lower,
&[
"postgres",
"postgresql",
"mysql",
"mariadb",
"sqlite",
"mongodb",
"redis",
"memcached",
"elasticsearch",
"opensearch",
"cassandra",
"couchdb",
"influxdb",
"clickhouse",
"duckdb",
],
) {
return Self::Database;
}
// Gaming (non-GPU or waiting for GPU)
if Self::matches_any(
&name_lower,
&[
"steam",
"steamwebhelper",
"game",
"unity",
"unreal",
"godot",
"wine",
"proton",
"lutris",
"heroic",
"bottles",
"gamescope",
"mangohud",
"gamemode",
],
) {
return Self::Gaming;
}
// Shells
if Self::matches_any(
&name_lower,
&[
"bash",
"zsh",
"fish",
"sh",
"dash",
"ksh",
"tcsh",
"csh",
"powershell",
"pwsh",
"cmd",
"terminal",
"konsole",
"gnome-terminal",
"alacritty",
"kitty",
"wezterm",
"foot",
"tilix",
"terminator",
"tmux",
"screen",
"byobu",
],
) {
return Self::Shell;
}
// Check user context - root/system users often run services
if let Some(u) = user {
let u_lower = u.to_lowercase();
if u_lower == "root" || u_lower == "system" || u_lower.starts_with("_") {
return Self::Service;
}
}
// A GPU-holding process that matches nothing by name is still worth
// separating from the general Unknown pile — but only after every
// name-based category has had its turn, so a browser is a browser.
if is_gpu_process {
return Self::GpuCompute;
}
Self::Unknown
}
/// Check if the name contains any pattern as a whole word. A bare substring
/// match read `obsidian` as `obs`, the OBS recorder, and so classified a
/// notes app as media.
fn matches_any(name: &str, patterns: &[&str]) -> bool {
patterns.iter().any(|p| contains_whole_word(name, p))
}
/// Get display name for the category
pub fn display_name(&self) -> &'static str {
match self {
Self::System => "System",
Self::Service => "Services",
Self::Desktop => "Desktop",
Self::Browser => "Browsers",
Self::Development => "Development",
Self::AiMl => "AI/ML",
Self::Gaming => "Gaming",
Self::Media => "Media",
Self::Communication => "Communication",
Self::Productivity => "Productivity",
Self::Container => "Containers",
Self::Network => "Network",
Self::Database => "Database",
Self::GpuCompute => "Using GPU",
Self::Shell => "Shell",
Self::Application => "Applications",
Self::Unknown => "Other",
}
}
/// Get an emoji/icon for the category
pub fn icon(&self) -> &'static str {
match self {
Self::System => "⚙️",
Self::Service => "🔧",
Self::Desktop => "🖥️",
Self::Browser => "🌐",
Self::Development => "💻",
Self::AiMl => "🤖",
Self::Gaming => "🎮",
Self::Media => "🎵",
Self::Communication => "💬",
Self::Productivity => "📝",
Self::Container => "📦",
Self::Network => "🌍",
Self::Database => "🗄️",
Self::GpuCompute => "🔥",
Self::Shell => "🐚",
Self::Application => "📱",
Self::Unknown => "❓",
}
}
/// Get all categories in display order
pub fn all() -> &'static [ProcessCategory] {
&[
Self::AiMl,
Self::GpuCompute,
Self::Gaming,
Self::Browser,
Self::Development,
Self::Media,
Self::Communication,
Self::Productivity,
Self::Container,
Self::Database,
Self::Network,
Self::Desktop,
Self::Service,
Self::System,
Self::Shell,
Self::Application,
Self::Unknown,
]
}
}
impl std::fmt::Display for ProcessCategory {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.display_name())
}
}
/// GPU process type classification for process monitoring
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProcessGpuType {
/// Process uses graphics rendering (3D, OpenGL, Vulkan, DirectX)
Graphical,
/// Process uses compute workloads (CUDA, OpenCL, SYCL)
Compute,
/// Process uses both graphics and compute
GraphicalCompute,
/// Unknown or unable to determine
Unknown,
}
impl ProcessGpuType {
/// Create from engine usage pattern
pub fn from_engine_usage(gfx: u64, compute: u64) -> Self {
match (gfx > 0, compute > 0) {
(true, true) => Self::GraphicalCompute,
(true, false) => Self::Graphical,
(false, true) => Self::Compute,
(false, false) => Self::Unknown,
}
}
}
impl std::fmt::Display for ProcessGpuType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Graphical => write!(f, "Graphics"),
Self::Compute => write!(f, "Compute"),
Self::GraphicalCompute => write!(f, "Gfx+Compute"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
/// Unified process information with GPU attribution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessMonitorInfo {
/// Process ID
pub pid: u32,
/// Parent Process ID
pub parent_pid: Option<u32>,
/// Process name/command
pub name: String,
/// User running the process
pub user: Option<String>,
/// Process category (smart classification)
pub category: ProcessCategory,
/// CPU usage percentage: the delta between two samples of this process.
/// `None` until a previous sample exists (see
/// [`ProcessMonitor::sample_cpu_times`]), since a lifetime average is not
/// current usage. This used to report the lifetime average on the first
/// sample, and before that it divided by an assumed one second or reported 0%.
pub cpu_percent: Option<f32>,
/// Memory usage in bytes (Working Set / RSS)
pub memory_bytes: u64,
/// Virtual memory in bytes, in each platform's own measure. Linux: the
/// address-space size (`vsize`). Windows: the committed private bytes
/// (`PagefileUsage`), not the address-space size. macOS: the virtual size
/// from `proc_taskinfo`. The three are not directly comparable.
pub virtual_memory_bytes: u64,
/// Private memory in bytes (unique to this process)
///
/// `None` where it is not read: Linux would need `smaps_rollup` and macOS
/// has no per-process private figure in `proc_taskinfo`. Both used to
/// report 0, a process with no private memory at all.
pub private_bytes: Option<u64>,
/// Number of threads
pub thread_count: u32,
/// Number of open handles (Windows) or file descriptors (Unix), or `None`
/// where it could not be read.
///
/// These three were `u64`/`u32` set to `0` whenever the source was
/// unavailable: on Linux `/proc/<pid>/io` and `/proc/<pid>/fd` are
/// unreadable for other users' processes without privilege -- 51 of 72
/// processes under WSL2 when this was written -- and macOS set all three
/// to `0` beside comments saying they were not read. The TUI drew those
/// processes as having done no I/O.
pub handle_count: Option<u32>,
/// I/O read bytes since process start, or `None` where not read.
pub io_read_bytes: Option<u64>,
/// I/O write bytes since process start, or `None` where not read.
pub io_write_bytes: Option<u64>,
/// Process start time (Unix timestamp in seconds)
pub start_time: Option<u64>,
/// GPU indices this process is using. `None` when GPU attribution did not
/// run: the monitor has no GPU collection, because `GpuCollection::auto_detect`
/// failed or the monitor was built without GPUs. `Some(vec![])` means
/// attribution ran and found no GPU use. This was a `Vec`, empty in both
/// cases, so a failed GPU query read as a machine with no GPU.
pub gpu_indices: Option<Vec<usize>>,
/// GPU memory usage per GPU (GPU index -> memory in bytes).
///
/// A device that reports no figure for this process has no entry, rather
/// than an entry of zero.
pub gpu_memory_per_device: HashMap<usize, u64>,
/// Total GPU memory across every device that reported one, or `None` when
/// no device did.
///
/// This was `u64`, and the attribution loop wrote
/// `gpu_proc.memory_usage.unwrap_or(0)` into it. NVML does not expose
/// per-process GPU memory under Windows' WDDM driver model — `nvidia-smi`
/// prints `[N/A]` for every process on this desktop — so every
/// GPU-attributed process reported 0.0 MB as though measured.
/// `observability/api.rs` already had to guard `> 0` to undo it.
pub total_gpu_memory_bytes: Option<u64>,
/// Process state (R=Running, S=Sleeping, D=Disk sleep, Z=Zombie, T=Stopped,
/// U=Unknown). On macOS, `I` is an idle task, or one still being created.
///
/// `U` is not a Linux state code: it means this platform did not tell us. Windows
/// has no per-process state — scheduling state lives on threads — and the
/// enumeration here used to report `'R'` for every process, which made the UI
/// claim all 420 processes on an idle desktop were running and none were asleep.
pub state: char,
/// Process priority, in the platform's own units. The units differ and are
/// not comparable across platforms:
///
/// - Linux: the kernel's `priority` field from `/proc/<pid>/stat`. For an
/// ordinary task this is `nice + 20` (0 to 39); a real-time task is
/// negative (-2 to -100).
/// - Windows: the process priority class constant from `GetPriorityClass`
/// (`0x40` idle, `0x4000` below normal, `0x20` normal, `0x8000` above
/// normal, `0x80` high, `0x100` realtime). `None` when the call fails. It
/// used to be `Some(0)`, which is not a class.
/// - macOS: the task's scheduling priority from `proc_taskinfo`
/// (`pti_priority`, a Mach priority on a 0 to 127 scale, where 31 is the
/// usual default). It is not a nice value.
pub priority: Option<i32>,
// nvtop feature parity: Per-process engine utilization
/// GPU graphics engine time used (nanoseconds)
pub gfx_engine_used: Option<u64>,
/// GPU compute engine time used (nanoseconds)
pub compute_engine_used: Option<u64>,
/// GPU encoder time used (nanoseconds)
pub enc_engine_used: Option<u64>,
/// GPU decoder time used (nanoseconds)
pub dec_engine_used: Option<u64>,
/// GPU usage percentage (0-100)
pub gpu_usage_percent: Option<f32>,
/// Encoder usage percentage (0-100)
pub encoder_usage_percent: Option<f32>,
/// Decoder usage percentage (0-100)
pub decoder_usage_percent: Option<f32>,
/// GPU process type (Graphics, Compute, Mixed)
pub gpu_process_type: ProcessGpuType,
/// GPU memory percentage of total device memory
pub gpu_memory_percentage: Option<f32>,
/// Cumulative CPU time in microseconds (used for delta-based CPU% calculation)
#[serde(skip)]
pub cpu_time_us: u64,
}
impl ProcessMonitorInfo {
/// Get total CPU usage percentage
pub fn cpu_usage(&self) -> Option<f32> {
self.cpu_percent
}
/// Get memory usage in megabytes
pub fn memory_mb(&self) -> f64 {
self.memory_bytes as f64 / (1024.0 * 1024.0)
}
/// Total GPU memory in megabytes, or `None` where no device reported it.
pub fn gpu_memory_mb(&self) -> Option<f64> {
self.total_gpu_memory_bytes
.map(|b| b as f64 / (1024.0 * 1024.0))
}
/// Whether the process is using any GPU. `None` when GPU attribution did not
/// run, so the answer is unknown rather than no.
pub fn is_gpu_process(&self) -> Option<bool> {
self.gpu_indices.as_ref().map(|gpus| !gpus.is_empty())
}
/// Number of GPUs used by this process, or `None` when attribution did not
/// run.
pub fn gpu_count(&self) -> Option<usize> {
self.gpu_indices.as_ref().map(Vec::len)
}
/// Get the process category
pub fn category(&self) -> ProcessCategory {
self.category
}
/// Reclassify the process (e.g., after GPU attribution is added)
pub fn reclassify(&mut self) {
self.category = ProcessCategory::classify(
&self.name,
self.user.as_deref(),
self.is_gpu_process() == Some(true),
);
}
}
/// Statistics for a process category
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CategoryStats {
/// The category
pub category: ProcessCategory,
/// Number of processes in this category
pub process_count: usize,
/// Number of GPU-using processes in this category
pub gpu_process_count: usize,
/// Total CPU usage percentage across all processes
/// Sum of the members' CPU, or `None` when any member's is not yet known.
pub total_cpu_percent: Option<f32>,
/// Total memory usage in bytes
pub total_memory_bytes: u64,
/// Total GPU memory over the processes in this category that reported
/// one, or `None` when none of them did. See
/// [`ProcessMonitorInfo::total_gpu_memory_bytes`].
pub total_gpu_memory_bytes: Option<u64>,
}
impl CategoryStats {
/// Get memory usage in MB
pub fn memory_mb(&self) -> f64 {
self.total_memory_bytes as f64 / (1024.0 * 1024.0)
}
/// GPU memory in MB over the processes that reported one, or `None`.
pub fn gpu_memory_mb(&self) -> Option<f64> {
self.total_gpu_memory_bytes
.map(|b| b as f64 / (1024.0 * 1024.0))
}
}
/// The account name for a macOS uid, or `None` when the account database has no
/// entry for it.
#[cfg(target_os = "macos")]
fn user_name(uid: u32) -> Option<String> {
// SAFETY: `getpwuid` returns a pointer into static storage, or null. The
// name is copied out before any other call can overwrite that storage.
unsafe {
let entry = libc::getpwuid(uid);
if entry.is_null() {
return None;
}
Some(
std::ffi::CStr::from_ptr((*entry).pw_name)
.to_string_lossy()
.into_owned(),
)
}
}
/// Whether `word` occurs in `name` with no ASCII letter or digit on either side.
/// `.`, `-`, `_` and the ends of the name are boundaries, so `python3.11`
/// contains `python3` and `obs-studio` contains `obs`, but `obsidian` does not.
fn contains_whole_word(name: &str, word: &str) -> bool {
name.match_indices(word).any(|(i, _)| {
let before = name[..i].chars().next_back();
let after = name[i + word.len()..].chars().next();
!before.is_some_and(|c| c.is_ascii_alphanumeric())
&& !after.is_some_and(|c| c.is_ascii_alphanumeric())
})
}
/// The number of logical CPUs to normalise process CPU time against.
///
/// One place, because there were four. Every one of them was correct when it was
/// written, which is exactly how this crate ended up with four parsers for
/// `vm.swapusage` and three copies of one page-size constant.
fn logical_cpu_count() -> Option<f32> {
std::thread::available_parallelism()
.ok()
.map(|n| n.get() as f32)
}
/// Process monitor that combines system and GPU process information
pub struct ProcessMonitor {
/// GPU collection for GPU process tracking
gpu_collection: Option<GpuCollection>,
/// Cache of last update time (for CPU percentage calculation)
last_update: std::time::Instant,
/// Previous per-process CPU times for delta-based CPU% calculation
/// Maps PID -> (cumulative_cpu_time_us, wall_clock_instant)
prev_cpu_times: HashMap<u32, (u64, std::time::Instant)>,
/// Number of logical CPUs for normalizing per-process CPU%
/// The divisor that turns per-process CPU time into a share of total system
/// capacity, or `None` when the logical CPU count could not be read.
///
/// This was an `f32` with an `unwrap_or(1.0)` written four times over. One is
/// not a neutral divisor — it is the count of a single-core machine, so a
/// process saturating one core of this 24-core desktop was published at
/// `100.0` instead of `4.2`. The absent case now skips normalisation instead
/// of performing it with an invented denominator, and
/// [`ProcessMonitor::cpu_percent_is_normalized`] says which happened.
num_logical_cpus: Option<f32>,
}
impl ProcessMonitor {
/// Whether [`ProcessInfo::cpu_percent`] is a share of total system capacity.
///
/// False when the logical CPU count could not be read, in which case the
/// figure is per-core and will exceed 100 for a process using more than one
/// core. `cpu_percent` is a bare number across many call sites and cannot say
/// "not normalised", so the statement lives here.
pub fn cpu_percent_is_normalized(&self) -> bool {
self.num_logical_cpus.is_some()
}
/// Create a new process monitor
///
/// Automatically detects available GPUs for GPU process attribution.
pub fn new() -> Result<Self> {
let gpu_collection = GpuCollection::auto_detect().ok();
let num_logical_cpus = logical_cpu_count();
Ok(Self {
gpu_collection,
last_update: std::time::Instant::now(),
prev_cpu_times: HashMap::new(),
num_logical_cpus,
})
}
/// Create a process monitor with a pre-initialized GPU collection
///
/// This is useful when you already have a [`GpuCollection`] instance
/// and want to reuse it for process monitoring.
pub fn with_gpus(gpu_collection: GpuCollection) -> Result<Self> {
let num_logical_cpus = logical_cpu_count();
Ok(Self {
gpu_collection: Some(gpu_collection),
last_update: std::time::Instant::now(),
prev_cpu_times: HashMap::new(),
num_logical_cpus,
})
}
/// Create a process monitor without GPU tracking
pub fn without_gpu() -> Result<Self> {
let num_logical_cpus = logical_cpu_count();
Ok(Self {
gpu_collection: None,
last_update: std::time::Instant::now(),
prev_cpu_times: HashMap::new(),
num_logical_cpus,
})
}
/// Record every process's cumulative CPU time without building the full
/// listing, so the next [`ProcessMonitor::processes`] call reports CPU% over
/// the interval since this one.
///
/// Without a previous sample, `processes` can only report each process's
/// lifetime average -- its CPU time divided by how long it has existed. For
/// a process started days ago that says almost nothing about now. A caller
/// that samples once, such as an ontology snapshot, should call this first
/// and wait before sampling.
pub fn sample_cpu_times(&mut self) -> Result<()> {
let now = std::time::Instant::now();
let procs = self.get_system_processes()?;
self.prev_cpu_times = procs
.iter()
.filter(|p| p.cpu_time_us > 0)
.map(|p| (p.pid, (p.cpu_time_us, now)))
.collect();
Ok(())
}
/// Get all running processes with GPU attribution
pub fn processes(&mut self) -> Result<Vec<ProcessMonitorInfo>> {
let now = std::time::Instant::now();
// Get system processes
let mut system_processes = self.get_system_processes()?;
// Compute delta-based CPU% from stored previous samples
let mut new_cpu_times = HashMap::with_capacity(system_processes.len());
for proc in &mut system_processes {
// The platform readers fill `cpu_percent` with the process's lifetime
// average. That is not current usage, so it is cleared here and only a
// delta against a previous sample sets it. Without one the field is
// unknown, not the lifetime figure presented as now. This used to keep
// the lifetime average on the first sample.
proc.cpu_percent = None;
if proc.cpu_time_us > 0 {
if let Some(&(prev_time_us, prev_instant)) = self.prev_cpu_times.get(&proc.pid) {
let elapsed = now.duration_since(prev_instant);
let elapsed_us = elapsed.as_micros() as f64;
if elapsed_us > 0.0 && proc.cpu_time_us >= prev_time_us {
let delta_cpu_us = (proc.cpu_time_us - prev_time_us) as f64;
// CPU% = (cpu_time_delta / wall_time_delta) * 100 / num_cpus
// Normalized to 0-100% of total system capacity (like Task
// Manager). Without a core count there is no such share to
// report, so the raw per-core figure is left as the platform
// gave it rather than divided by a made-up denominator.
let share = (delta_cpu_us / elapsed_us) * 100.0;
proc.cpu_percent = Some(match self.num_logical_cpus {
Some(cpus) => (share / cpus as f64) as f32,
None => share as f32,
});
}
}
new_cpu_times.insert(proc.pid, (proc.cpu_time_us, now));
}
}
self.prev_cpu_times = new_cpu_times;
// Add GPU information if available
if let Some(ref gpu_collection) = self.gpu_collection {
// Attribution has run, so every process now has a definite answer:
// empty until a device claims it. The readers leave `None`, which
// means it did not run.
for proc in &mut system_processes {
proc.gpu_indices = Some(Vec::new());
}
self.add_gpu_attribution(&mut system_processes, gpu_collection)?;
// Reclassify processes after GPU attribution (GPU processes may change category)
for proc in &mut system_processes {
if proc.is_gpu_process() == Some(true) {
proc.reclassify();
}
}
}
self.last_update = now;
Ok(system_processes)
}
/// Get processes sorted by CPU usage (descending)
pub fn processes_by_cpu(&mut self) -> Result<Vec<ProcessMonitorInfo>> {
let mut procs = self.processes()?;
procs.sort_by(|a, b| {
b.cpu_percent
.partial_cmp(&a.cpu_percent)
.unwrap_or(std::cmp::Ordering::Equal)
});
Ok(procs)
}
/// Get processes sorted by memory usage (descending)
pub fn processes_by_memory(&mut self) -> Result<Vec<ProcessMonitorInfo>> {
let mut procs = self.processes()?;
procs.sort_by_key(|p| std::cmp::Reverse(p.memory_bytes));
Ok(procs)
}
/// Get processes sorted by GPU memory usage (descending)
pub fn processes_by_gpu_memory(&mut self) -> Result<Vec<ProcessMonitorInfo>> {
let mut procs = self.processes()?;
procs.sort_by_key(|p| std::cmp::Reverse(p.total_gpu_memory_bytes));
Ok(procs)
}
/// Get only GPU-using processes
pub fn gpu_processes(&mut self) -> Result<Vec<ProcessMonitorInfo>> {
let procs = self.processes()?;
Ok(procs
.into_iter()
.filter(|p| p.is_gpu_process() == Some(true))
.collect())
}
/// Get process by PID
pub fn process_by_pid(&mut self, pid: u32) -> Result<Option<ProcessMonitorInfo>> {
let procs = self.processes()?;
Ok(procs.into_iter().find(|p| p.pid == pid))
}
/// Get processes filtered by category
pub fn processes_by_category(
&mut self,
category: ProcessCategory,
) -> Result<Vec<ProcessMonitorInfo>> {
let procs = self.processes()?;
Ok(procs
.into_iter()
.filter(|p| p.category == category)
.collect())
}
/// Get processes grouped by category
pub fn processes_grouped_by_category(
&mut self,
) -> Result<HashMap<ProcessCategory, Vec<ProcessMonitorInfo>>> {
let procs = self.processes()?;
let mut grouped: HashMap<ProcessCategory, Vec<ProcessMonitorInfo>> = HashMap::new();
for proc in procs {
grouped.entry(proc.category).or_default().push(proc);
}
Ok(grouped)
}
/// Get category statistics (count and total CPU/memory per category)
pub fn category_stats(&mut self) -> Result<Vec<CategoryStats>> {
let grouped = self.processes_grouped_by_category()?;
let mut stats: Vec<CategoryStats> = grouped
.into_iter()
.map(|(category, procs)| {
let count = procs.len();
// `None` when any member's figure is not yet known.
let total_cpu: Option<f32> = procs.iter().map(|p| p.cpu_percent).sum();
let total_memory: u64 = procs.iter().map(|p| p.memory_bytes).sum();
// Sum what was reported. `None` when nothing in the category
// reported anything, which is not the same as a category whose
// processes all measured zero.
let reported: Vec<u64> = procs
.iter()
.filter_map(|p| p.total_gpu_memory_bytes)
.collect();
let total_gpu_memory = if reported.is_empty() {
None
} else {
Some(reported.iter().sum())
};
let gpu_process_count = procs
.iter()
.filter(|p| p.is_gpu_process() == Some(true))
.count();
CategoryStats {
category,
process_count: count,
gpu_process_count,
total_cpu_percent: total_cpu,
total_memory_bytes: total_memory,
total_gpu_memory_bytes: total_gpu_memory,
}
})
.collect();
// Sort by total CPU usage descending
stats.sort_by(|a, b| {
b.total_cpu_percent
.partial_cmp(&a.total_cpu_percent)
.unwrap_or(std::cmp::Ordering::Equal)
});
Ok(stats)
}
/// Get total number of running processes
pub fn process_count(&mut self) -> Result<usize> {
Ok(self.processes()?.len())
}
/// Get number of GPU-using processes
pub fn gpu_process_count(&mut self) -> Result<usize> {
Ok(self.gpu_processes()?.len())
}
/// Get number of detected GPUs, or `None` when GPU detection was not run or
/// failed. It used to return 0 then, which is a count of a machine with no GPU.
pub fn gpu_count(&self) -> Option<usize> {
self.gpu_collection.as_ref().map(|gc| gc.len())
}
/// Update process list (refresh data)
///
/// This method triggers a refresh of the internal process cache.
/// The actual update happens automatically in `processes()`, so this
/// is primarily for explicit refresh semantics in user code.
pub fn update(&mut self) -> Result<()> {
// Refresh by calling processes() and discarding result
let _ = self.processes()?;
Ok(())
}
// Platform-specific system process enumeration
#[cfg(target_os = "linux")]
fn get_system_processes(&self) -> Result<Vec<ProcessMonitorInfo>> {
linux::enumerate_processes()
}
#[cfg(target_os = "windows")]
fn get_system_processes(&self) -> Result<Vec<ProcessMonitorInfo>> {
windows_impl::enumerate_processes()
}
#[cfg(target_os = "macos")]
fn get_system_processes(&self) -> Result<Vec<ProcessMonitorInfo>> {
macos::enumerate_processes()
}
/// Add GPU attribution to processes
fn add_gpu_attribution(
&self,
processes: &mut [ProcessMonitorInfo],
gpu_collection: &GpuCollection,
) -> Result<()> {
// Create a map of PID -> Process for quick lookup
let mut process_map: HashMap<u32, &mut ProcessMonitorInfo> =
processes.iter_mut().map(|p| (p.pid, p)).collect();
// Iterate through each GPU and its processes
for (gpu_idx, gpu) in gpu_collection.gpus().iter().enumerate() {
if let Ok(gpu_processes) = gpu.processes() {
for gpu_proc in gpu_processes {
let pid = gpu_proc.pid;
// `None` here is NVML declining to report, which is every
// process under WDDM. It is not zero bytes.
let gpu_mem = gpu_proc.memory_usage;
if let Some(proc_info) = process_map.get_mut(&pid) {
// Add this GPU to the process's GPU list
let indices = proc_info.gpu_indices.get_or_insert_with(Vec::new);
if !indices.contains(&gpu_idx) {
indices.push(gpu_idx);
}
// Add GPU memory for this device, if the device gave
// one. A process attributed to a GPU that reports no
// figure keeps `None`, and stays distinguishable from
// one measured at zero.
if let Some(bytes) = gpu_mem {
proc_info.gpu_memory_per_device.insert(gpu_idx, bytes);
proc_info.total_gpu_memory_bytes =
Some(proc_info.total_gpu_memory_bytes.unwrap_or(0) + bytes);
}
// Copy user from GPU process if not already set
if proc_info.user.is_none() && !gpu_proc.user.is_empty() {
proc_info.user = Some(gpu_proc.user.clone());
}
// Copy GPU utilization data
if gpu_proc.gpu_usage.is_some() {
proc_info.gpu_usage_percent = gpu_proc.gpu_usage.map(|u| u as f32);
}
if gpu_proc.encoder_usage.is_some() {
proc_info.encoder_usage_percent =
gpu_proc.encoder_usage.map(|u| u as f32);
}
if gpu_proc.decoder_usage.is_some() {
proc_info.decoder_usage_percent =
gpu_proc.decoder_usage.map(|u| u as f32);
}
if gpu_proc.memory_usage_percent.is_some() {
proc_info.gpu_memory_percentage =
gpu_proc.memory_usage_percent.map(|u| u as f32);
}
// Update process type based on GPU process type
proc_info.gpu_process_type = match gpu_proc.process_type {
crate::gpu::GpuProcessType::Graphics => ProcessGpuType::Graphical,
crate::gpu::GpuProcessType::Compute => ProcessGpuType::Compute,
crate::gpu::GpuProcessType::GraphicsAndCompute => {
ProcessGpuType::GraphicalCompute
}
crate::gpu::GpuProcessType::Unknown => ProcessGpuType::Unknown,
};
}
}
}
}
Ok(())
}
/// Kill a process by PID
///
/// This method attempts to terminate a process. On Unix systems, it sends SIGTERM
/// by default, which allows the process to clean up. On Windows, it terminates
/// the process forcefully.
///
/// # Safety
///
/// Killing processes requires appropriate permissions:
/// - On Linux/Unix: Must have permission to send signals to the target process
/// - On Windows: Must have PROCESS_TERMINATE access rights
///
/// # Arguments
///
/// * `pid` - Process ID to terminate
/// * `force` - If true, use SIGKILL (Unix) or forceful termination (Windows)
///
/// # Examples
///
/// ```no_run
/// use ironmonitor::{ProcessMonitor, GpuCollection};
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let gpus = GpuCollection::auto_detect()?;
/// let mut monitor = ProcessMonitor::with_gpus(gpus)?;
///
/// // Gracefully terminate process 1234
/// monitor.kill_process(1234, false)?;
///
/// // Force kill process 5678
/// monitor.kill_process(5678, true)?;
/// # Ok(())
/// # }
/// ```
pub fn kill_process(&self, pid: u32, force: bool) -> Result<()> {
#[cfg(target_os = "linux")]
{
use std::process::Command;
let signal = if force { "KILL" } else { "TERM" };
let status = Command::new("kill")
.arg(format!("-{}", signal))
.arg(pid.to_string())
.status()
.map_err(IronError::Io)?;
if !status.success() {
return Err(IronError::Other(format!(
"Failed to kill process {}: {}",
pid,
status.code().unwrap_or(-1)
)));
}
Ok(())
}
#[cfg(target_os = "windows")]
{
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::System::Threading::{
OpenProcess, TerminateProcess, PROCESS_TERMINATE,
};
let _ = force; // Windows always uses forceful termination
unsafe {
let handle = OpenProcess(PROCESS_TERMINATE, false, pid).map_err(|e| {
IronError::Other(format!("Failed to open process {}: {}", pid, e))
})?;
if handle.is_invalid() {
return Err(IronError::Other(format!(
"Invalid handle for process {}",
pid
)));
}
let result = TerminateProcess(handle, 1);
let _ = CloseHandle(handle);
if result.is_err() {
return Err(IronError::Other(format!(
"Failed to terminate process {}",
pid
)));
}
Ok(())
}
}
#[cfg(target_os = "macos")]
{
use std::process::Command;
let signal = if force { "KILL" } else { "TERM" };
let status = Command::new("kill")
.arg(format!("-{}", signal))
.arg(pid.to_string())
.status()
.map_err(IronError::Io)?;
if !status.success() {
return Err(IronError::Other(format!(
"Failed to kill process {}: {}",
pid,
status.code().unwrap_or(-1)
)));
}
Ok(())
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
{
let _ = (pid, force);
Err(IronError::UnsupportedPlatform(
"Process termination not supported on this platform".to_string(),
))
}
}
}
impl Default for ProcessMonitor {
fn default() -> Self {
let num_logical_cpus = logical_cpu_count();
Self::new().unwrap_or_else(|_| Self {
gpu_collection: None,
last_update: std::time::Instant::now(),
prev_cpu_times: HashMap::new(),
num_logical_cpus,
})
}
}
// Linux-specific process enumeration
#[cfg(target_os = "linux")]
mod linux {
use super::*;
use std::fs;
use std::path::Path;
pub fn enumerate_processes() -> Result<Vec<ProcessMonitorInfo>> {
let mut processes = Vec::new();
let proc_dir = Path::new("/proc");
if !proc_dir.exists() {
return Err(IronError::UnsupportedPlatform(
"/proc filesystem not available".to_string(),
));
}
// Read uptime for CPU calculation
let uptime = read_uptime()?;
// Iterate through /proc entries
for entry in fs::read_dir(proc_dir)? {
let entry = entry?;
let filename = entry.file_name();
let filename_str = filename.to_string_lossy();
// Check if directory name is a number (PID)
if let Ok(pid) = filename_str.parse::<u32>() {
if let Ok(proc_info) = read_process_info(pid, uptime) {
processes.push(proc_info);
}
}
}
Ok(processes)
}
pub(super) fn read_uptime() -> Result<f64> {
let uptime_str = fs::read_to_string("/proc/uptime")?;
let uptime: f64 = uptime_str
.split_whitespace()
.next()
.ok_or_else(|| IronError::Parse("Invalid uptime format".to_string()))?
.parse()
.map_err(|e| IronError::Parse(format!("Failed to parse uptime: {}", e)))?;
Ok(uptime)
}
pub(super) fn read_process_info(pid: u32, uptime: f64) -> Result<ProcessMonitorInfo> {
let proc_path = format!("/proc/{}", pid);
let proc_dir = Path::new(&proc_path);
if !proc_dir.exists() {
return Err(IronError::DeviceNotFound(format!(
"Process {} not found",
pid
)));
}
// Read /proc/[pid]/stat
let stat_path = format!("{}/stat", proc_path);
let stat_content = fs::read_to_string(&stat_path)?;
// Parse stat file (fields documented in proc(5) man page)
let (name, stat_fields) = parse_stat_line(&stat_content)?;
if stat_fields.len() < 22 {
return Err(IronError::Parse(
"Insufficient fields in stat file".to_string(),
));
}
// Extract fields (0-indexed after splitting on ')')
// Reference: proc(5) man page
// Field 0: state, 1: ppid, 2: pgrp, 3: session, 4: tty_nr,
// 5: tpgid, 6: flags, 7: minflt, 8: cminflt, 9: majflt,
// 10: cmajflt, 11: utime, 12: stime, 13: cutime, 14: cstime,
// 15: priority, 16: nice, 17: num_threads, 18: itrealvalue,
// 19: starttime, 20: vsize, 21: rss
// 'U' rather than '?' for an unreadable state: the rest of IronMonitor uses 'U'
// to mean "not reported", and two different sentinels for one condition
// means every consumer has to know both.
let state = stat_fields[0].chars().next().unwrap_or('U');
// The kernel writes every one of these as a decimal. One that does not
// parse is a stat line this does not understand, and the process is
// not reported rather than reported with zero CPU time, zero threads or
// a start at boot -- which is what `unwrap_or(0)` made of it.
fn stat_number<T: std::str::FromStr>(fields: &[String], i: usize, what: &str) -> Result<T> {
fields[i]
.parse()
.map_err(|_| IronError::Parse(format!("/proc/<pid>/stat {what}: {:?}", fields[i])))
}
let parent_pid: u32 = stat_number(&stat_fields, 1, "ppid")?;
let utime: u64 = stat_number(&stat_fields, 11, "utime")?;
let stime: u64 = stat_number(&stat_fields, 12, "stime")?;
let priority: i32 = stat_number(&stat_fields, 15, "priority")?;
let num_threads: u32 = stat_number(&stat_fields, 17, "num_threads")?;
let starttime: u64 = stat_number(&stat_fields, 19, "starttime")?;
let vsize: u64 = stat_number(&stat_fields, 20, "vsize")?; // virtual memory size in bytes
// Calculate CPU percentage (lifetime average as fallback for first delta sample)
let clk_tck = crate::platform::linux::clock_ticks_per_second()
.ok_or_else(|| IronError::Other("sysconf(_SC_CLK_TCK) returned no tick rate".into()))?;
let page_size = crate::platform::linux::page_size().ok_or_else(|| {
IronError::Other("sysconf(_SC_PAGESIZE) returned no page size".into())
})?;
let total_ticks = utime + stime;
let total_time = total_ticks as f64 / clk_tck as f64;
let seconds_since_boot = uptime;
// A process younger than the clock's resolution has no lifetime to
// average over yet; the next sample's delta gives its figure. This
// floored the age at one second, understating a new process's usage.
let proc_uptime = seconds_since_boot - (starttime as f64 / clk_tck as f64);
let cpu_percent = (proc_uptime > 0.0).then(|| ((total_time / proc_uptime) * 100.0) as f32);
// Cumulative CPU time in microseconds for delta-based calculation
let cpu_time_us = total_ticks * 1_000_000 / clk_tck;
// Calculate start_time as unix timestamp
// Boot time from /proc/stat's btime field, or approximate from uptime
let boot_time_secs = std::fs::read_to_string("/proc/stat")
.ok()
.and_then(|content| {
content
.lines()
.find(|line| line.starts_with("btime "))
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|s| s.parse::<u64>().ok())
});
let process_start_time =
boot_time_secs.map(|btime| btime + (starttime as f64 / clk_tck as f64) as u64);
// Read /proc/[pid]/statm for memory: size and resident, in pages.
//
// A statm that cannot be read means the process exited after its stat
// was read, and it is not reported. This used to report it resident in
// zero bytes, which ranked it as the smallest process on the machine.
let statm_content = fs::read_to_string(format!("{}/statm", proc_path))?;
let mut statm = statm_content.split_whitespace().map(str::parse::<u64>);
let (Some(Ok(size_pages)), Some(Ok(resident_pages))) = (statm.next(), statm.next()) else {
return Err(IronError::Parse(format!(
"/proc/{pid}/statm: no size and resident pages in {statm_content:?}"
)));
};
let memory_bytes = resident_pages * page_size;
// stat's vsize is in bytes; a kernel thread has none, and statm then
// says the same 0 in pages.
let virtual_memory_bytes = if vsize > 0 {
vsize
} else {
size_pages * page_size
};
// Read /proc/[pid]/io for I/O stats (may require privileges)
let (io_read_bytes, io_write_bytes) = match fs::read_to_string(format!("{}/io", proc_path))
{
Ok(io_content) => {
let field = |name: &str| {
io_content
.lines()
.find_map(|line| line.strip_prefix(name))
.and_then(|v| v.trim().parse().ok())
};
(field("read_bytes: "), field("write_bytes: "))
}
// Refused for other users' processes without privilege: not read,
// which is not "did no I/O".
Err(_) => (None, None),
};
// Count file descriptors in /proc/[pid]/fd for handle_count
let handle_count: Option<u32> = fs::read_dir(format!("{}/fd", proc_path))
.ok()
.map(|entries| entries.count() as u32);
// Try to read user
let user = read_process_user(pid);
// Classify the process
let category = ProcessCategory::classify(&name, user.as_deref(), false);
Ok(ProcessMonitorInfo {
pid,
parent_pid: if parent_pid > 0 {
Some(parent_pid)
} else {
None
},
name,
user,
category,
cpu_percent,
memory_bytes,
virtual_memory_bytes,
private_bytes: None,
thread_count: num_threads,
handle_count,
io_read_bytes,
io_write_bytes,
start_time: process_start_time,
gpu_indices: None,
gpu_memory_per_device: HashMap::new(),
total_gpu_memory_bytes: None,
state,
priority: Some(priority),
gfx_engine_used: None,
compute_engine_used: None,
enc_engine_used: None,
dec_engine_used: None,
gpu_usage_percent: None,
encoder_usage_percent: None,
decoder_usage_percent: None,
gpu_process_type: ProcessGpuType::Unknown,
gpu_memory_percentage: None,
cpu_time_us,
})
}
fn parse_stat_line(stat: &str) -> Result<(String, Vec<String>)> {
// Format: pid (name) state ...
// Name can contain spaces and parentheses, so we need to find the last ')'
let start = stat
.find('(')
.ok_or_else(|| IronError::Parse("No opening parenthesis in stat".to_string()))?;
let end = stat
.rfind(')')
.ok_or_else(|| IronError::Parse("No closing parenthesis in stat".to_string()))?;
let name = stat[start + 1..end].to_string();
let rest = &stat[end + 2..]; // Skip ') '
let fields: Vec<String> = rest.split_whitespace().map(|s| s.to_string()).collect();
Ok((name, fields))
}
fn read_process_user(pid: u32) -> Option<String> {
// Read UID from /proc/[pid]/status
let status_path = format!("/proc/{}/status", pid);
if let Ok(content) = fs::read_to_string(&status_path) {
for line in content.lines() {
if line.starts_with("Uid:") {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() > 1 {
// Get real UID (first number after "Uid:")
if let Ok(uid) = parts[1].parse::<u32>() {
// Try to resolve UID to username
return get_username_from_uid(uid);
}
}
}
}
}
None
}
fn get_username_from_uid(uid: u32) -> Option<String> {
// Simple approach: read /etc/passwd
if let Ok(content) = fs::read_to_string("/etc/passwd") {
for line in content.lines() {
let parts: Vec<&str> = line.split(':').collect();
if parts.len() > 2 {
if let Ok(line_uid) = parts[2].parse::<u32>() {
if line_uid == uid {
return Some(parts[0].to_string());
}
}
}
}
}
None
}
}
// Windows-specific process enumeration
#[cfg(target_os = "windows")]
mod windows_impl {
use super::*;
use ::windows::Win32::Foundation::CloseHandle;
use ::windows::Win32::Security::{
GetTokenInformation, LookupAccountSidW, TokenUser, SID_NAME_USE, TOKEN_QUERY, TOKEN_USER,
};
use ::windows::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
TH32CS_SNAPPROCESS,
};
use ::windows::Win32::System::ProcessStatus::{
GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX,
};
use ::windows::Win32::System::Threading::{
GetPriorityClass, GetProcessHandleCount, GetProcessIoCounters, GetProcessTimes,
OpenProcess, OpenProcessToken, QueryFullProcessImageNameW, IO_COUNTERS,
PROCESS_QUERY_LIMITED_INFORMATION,
};
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
use std::sync::{Mutex, OnceLock};
/// Cache of per-process attributes that cannot change while a process lives.
///
/// [`get_process_user`] performs `OpenProcess` + `OpenProcessToken` +
/// `GetTokenInformation` twice + `LookupAccountSidW`. The SID lookup is the
/// expensive part: it can round-trip to LSA, and on a domain-joined machine to a
/// domain controller. It was previously executed for every process on every
/// refresh, which dominated enumeration cost.
///
/// The key includes the process creation time, so a recycled PID is treated as a
/// distinct process and can never inherit another process's username.
/// Keyed on (pid, creation_time); the value is the resolved username, or `None`
/// when the lookup failed for that process.
type UserCache = Mutex<HashMap<(u32, u64), Option<String>>>;
static PROCESS_USER_CACHE: OnceLock<UserCache> = OnceLock::new();
/// Upper bound on cached entries before the cache is dropped wholesale.
///
/// Processes are created and destroyed constantly, so entries go stale by
/// accumulation rather than by mutation. Rather than tracking liveness, the cache
/// is simply bounded: the ceiling is far above any realistic process count, so in
/// practice a clear is rare and only costs one repopulating scan.
const PROCESS_USER_CACHE_CAP: usize = 4096;
/// Username for `pid`, memoized against the process creation time.
fn cached_process_user(pid: u32, creation_100ns: u64) -> Option<String> {
// A creation time of 0 means GetProcessTimes failed, so there is no stable key
// to memoize against. Fall through uncached rather than risk a wrong answer.
if creation_100ns == 0 {
return get_process_user(pid);
}
let cache = PROCESS_USER_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let key = (pid, creation_100ns);
if let Ok(map) = cache.lock() {
if let Some(hit) = map.get(&key) {
return hit.clone();
}
}
let user = get_process_user(pid);
if let Ok(mut map) = cache.lock() {
if map.len() >= PROCESS_USER_CACHE_CAP {
map.clear();
}
map.insert(key, user.clone());
}
user
}
/// Get the username of a process by PID
fn get_process_user(pid: u32) -> Option<String> {
unsafe {
// Try with limited access first (works on more processes)
let process_handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
if let Ok(handle) = process_handle {
if !handle.is_invalid() {
let mut token_handle = ::windows::Win32::Foundation::HANDLE::default();
if OpenProcessToken(handle, TOKEN_QUERY, &mut token_handle).is_ok() {
// Get token user info size
let mut return_length = 0u32;
let _ = GetTokenInformation(
token_handle,
TokenUser,
None,
0,
&mut return_length,
);
if return_length > 0 {
let mut token_info = vec![0u8; return_length as usize];
if GetTokenInformation(
token_handle,
TokenUser,
Some(token_info.as_mut_ptr() as *mut _),
return_length,
&mut return_length,
)
.is_ok()
{
let token_user = &*(token_info.as_ptr() as *const TOKEN_USER);
// Lookup username from SID
let mut name_buf = [0u16; 256];
let mut name_len = name_buf.len() as u32;
let mut domain_buf = [0u16; 256];
let mut domain_len = domain_buf.len() as u32;
let mut sid_type = SID_NAME_USE::default();
if LookupAccountSidW(
None,
token_user.User.Sid,
::windows::core::PWSTR(name_buf.as_mut_ptr()),
&mut name_len,
::windows::core::PWSTR(domain_buf.as_mut_ptr()),
&mut domain_len,
&mut sid_type,
)
.is_ok()
{
let _ = CloseHandle(token_handle);
let _ = CloseHandle(handle);
let name =
String::from_utf16_lossy(&name_buf[..name_len as usize]);
return Some(name);
}
}
}
let _ = CloseHandle(token_handle);
}
let _ = CloseHandle(handle);
}
}
}
None
}
/// Lifetime-average CPU% and Unix start time from a creation time and
/// cumulative CPU time, the same first-sample figure the handle path
/// computes from `GetProcessTimes`. `(None, None)` without a creation
/// time, which used to read as 0%.
fn lifetime_cpu(creation_100ns: u64, cpu_us: u64) -> (Option<f32>, Option<u64>) {
const UNIX_EPOCH_DIFF: u64 = 116_444_736_000_000_000;
if creation_100ns <= UNIX_EPOCH_DIFF {
return (None, None);
}
let start_unix = (creation_100ns - UNIX_EPOCH_DIFF) / 10_000_000;
let now_ft =
unsafe { windows::Win32::System::SystemInformation::GetSystemTimeAsFileTime() };
let now_100ns = (now_ft.dwHighDateTime as u64) << 32 | (now_ft.dwLowDateTime as u64);
let uptime_secs = now_100ns.saturating_sub(creation_100ns) as f64 / 10_000_000.0;
let pct = (uptime_secs > 0.0)
.then(|| ((cpu_us as f64 / 1_000_000.0 / uptime_secs) * 100.0) as f32);
(pct, Some(start_unix))
}
pub fn enumerate_processes() -> Result<Vec<ProcessMonitorInfo>> {
let mut processes = Vec::new();
// Memory, handle, I/O and CPU-time figures for every process, including
// the ones that cannot be opened below. See `system_process_table`.
let table = crate::platform::windows::system_process_table().unwrap_or_default();
unsafe {
// Take a snapshot of all processes
let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0).map_err(|e| {
IronError::Other(format!("Failed to create process snapshot: {}", e))
})?;
if snapshot.is_invalid() {
return Err(IronError::Other("Invalid snapshot handle".to_string()));
}
let mut entry = PROCESSENTRY32W {
dwSize: std::mem::size_of::<PROCESSENTRY32W>() as u32,
..Default::default()
};
// Get first process
if Process32FirstW(snapshot, &mut entry).is_err() {
let _ = CloseHandle(snapshot);
return Ok(processes);
}
// Iterate through all processes
loop {
let pid = entry.th32ProcessID;
// Open with the narrowest right that still satisfies every query
// below. On Vista and later PROCESS_QUERY_LIMITED_INFORMATION is
// sufficient for GetProcessTimes, GetProcessMemoryInfo,
// GetProcessIoCounters, GetPriorityClass, GetProcessHandleCount and
// QueryFullProcessImageNameW.
//
// The previous PROCESS_QUERY_INFORMATION | PROCESS_VM_READ mask asked
// for strictly more than was needed. That is both slower to grant and
// outright denied for protected and elevated processes, so those
// processes were silently dropped from the listing entirely.
let process_handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid);
// Whether the full, handle-backed path produced a row. When it does
// not, a reduced row is emitted from the snapshot entry below.
let mut emitted = false;
if let Ok(handle) = process_handle {
if !handle.is_invalid() {
// Get process name
let mut name_buffer = [0u16; 260];
let mut name_len = name_buffer.len() as u32;
use ::windows::core::PWSTR;
let name = if QueryFullProcessImageNameW(
handle,
::windows::Win32::System::Threading::PROCESS_NAME_WIN32,
PWSTR(name_buffer.as_mut_ptr()),
&mut name_len,
)
.is_ok()
{
let os_string = OsString::from_wide(&name_buffer[..name_len as usize]);
std::path::Path::new(&os_string)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("Unknown")
.to_string()
} else {
// Fallback to executable name from snapshot
let null_pos = entry
.szExeFile
.iter()
.position(|&c| c == 0)
.unwrap_or(entry.szExeFile.len());
String::from_utf16_lossy(&entry.szExeFile[..null_pos])
};
// Get memory info
let mut mem_counters = PROCESS_MEMORY_COUNTERS_EX::default();
let table_row = table.get(&pid);
let memory = if GetProcessMemoryInfo(
handle,
std::ptr::addr_of_mut!(mem_counters) as *mut _,
std::mem::size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32,
)
.is_ok()
{
Some((
mem_counters.WorkingSetSize as u64,
mem_counters.PagefileUsage as u64,
mem_counters.PrivateUsage as u64,
))
} else {
// The handle opened but the query was refused; the
// process table has the same figures. With neither,
// see `times` below.
table_row.map(|r| {
(r.working_set_bytes, r.pagefile_usage_bytes, r.private_bytes)
})
};
// Get handle count
// Either call may be refused on a handle that opened;
// the kernel process table has the same figures.
let mut handles: u32 = 0;
let handle_count = if GetProcessHandleCount(handle, &mut handles).is_ok() {
Some(handles)
} else {
table_row.map(|r| r.handle_count)
};
// Get I/O counters
let mut io_counters = IO_COUNTERS::default();
let (io_read_bytes, io_write_bytes) =
if GetProcessIoCounters(handle, &mut io_counters).is_ok() {
(
Some(io_counters.ReadTransferCount),
Some(io_counters.WriteTransferCount),
)
} else {
(
table_row.map(|r| r.io_read_bytes),
table_row.map(|r| r.io_write_bytes),
)
};
// Get priority class
let priority_class = GetPriorityClass(handle);
// Get CPU times
let mut creation_time = Default::default();
let mut exit_time = Default::default();
let mut kernel_time = Default::default();
let mut user_time = Default::default();
let times = if GetProcessTimes(
handle,
&mut creation_time,
&mut exit_time,
&mut kernel_time,
&mut user_time,
)
.is_ok()
{
// Convert FILETIME (100ns units)
let kernel_100ns = (kernel_time.dwHighDateTime as u64) << 32
| (kernel_time.dwLowDateTime as u64);
let user_100ns = (user_time.dwHighDateTime as u64) << 32
| (user_time.dwLowDateTime as u64);
// Cumulative CPU time in microseconds for delta-based calculation
let cpu_us = (kernel_100ns + user_100ns) / 10;
// Convert creation_time FILETIME to Unix timestamp
// FILETIME is 100ns intervals since Jan 1, 1601
// Unix epoch is Jan 1, 1970 - difference is 116444736000000000 (100ns intervals)
let creation_100ns = (creation_time.dwHighDateTime as u64) << 32
| (creation_time.dwLowDateTime as u64);
let unix_epoch_diff: u64 = 116444736000000000;
let start_unix = if creation_100ns > unix_epoch_diff {
Some((creation_100ns - unix_epoch_diff) / 10_000_000)
} else {
None
};
// Calculate CPU% as lifetime average (fallback for first delta sample)
let total_cpu_secs = cpu_us as f64 / 1_000_000.0;
// Get current time as FILETIME for uptime calculation
let now_ft =
windows::Win32::System::SystemInformation::GetSystemTimeAsFileTime(
);
let now_100ns = (now_ft.dwHighDateTime as u64) << 32
| (now_ft.dwLowDateTime as u64);
// No lifetime yet (or a clock behind the creation
// time): no average, where this assumed one second.
let pct = (now_100ns > creation_100ns).then(|| {
let uptime_secs =
(now_100ns - creation_100ns) as f64 / 10_000_000.0;
((total_cpu_secs / uptime_secs) * 100.0) as f32
});
Some((pct, start_unix, cpu_us, creation_100ns))
} else {
// Refused on a handle that opened: the process
// table has the same CPU times. This used to
// report the process as never having run.
table_row.map(|r| {
let cpu_us = (r.user_time_100ns + r.kernel_time_100ns) / 10;
let (pct, start) = lifetime_cpu(r.create_time_100ns, cpu_us);
(pct, start, cpu_us, r.create_time_100ns)
})
};
// Neither the handle nor the process table had figures:
// the process exited between the snapshot and the table.
// It is left out rather than listed as using no memory and
// no CPU. The reduced path below would find no table row
// either, so this moves straight to the next entry.
let (
Some((memory_bytes, virtual_memory_bytes, private_bytes)),
Some((cpu_percent, start_time, cpu_time_us, creation_100ns)),
) = (memory, times)
else {
let _ = CloseHandle(handle);
if Process32NextW(snapshot, &mut entry).is_err() {
break;
}
continue;
};
// Get user (memoized against the process creation time — the
// SID lookup underneath is the single most expensive call in
// this loop).
let user = cached_process_user(pid, creation_100ns);
// Classify the process
let category = ProcessCategory::classify(&name, user.as_deref(), false);
processes.push(ProcessMonitorInfo {
pid,
name,
user,
category,
cpu_percent,
memory_bytes,
gpu_indices: None,
gpu_memory_per_device: HashMap::new(),
total_gpu_memory_bytes: None,
// Windows exposes scheduling state per thread, not per
// process. Reporting 'R' here was a guess, not a reading.
state: 'U',
// `GetPriorityClass` returns 0 when it fails, and 0 is
// not a priority class. It was stored as `Some(0)`.
priority: (priority_class != 0).then_some(priority_class as i32),
gfx_engine_used: None,
compute_engine_used: None,
enc_engine_used: None,
dec_engine_used: None,
gpu_usage_percent: None,
encoder_usage_percent: None,
decoder_usage_percent: None,
gpu_process_type: ProcessGpuType::Unknown,
gpu_memory_percentage: None,
// New Windows-specific fields
parent_pid: Some(entry.th32ParentProcessID),
virtual_memory_bytes,
private_bytes: Some(private_bytes),
thread_count: entry.cntThreads,
handle_count,
io_read_bytes,
io_write_bytes,
start_time,
cpu_time_us,
});
let _ = CloseHandle(handle);
emitted = true;
}
}
if !emitted {
// The process could not be opened — almost always because it runs
// as SYSTEM or is protected, and IronMonitor is not elevated.
//
// Previously such processes were skipped entirely, so an
// unelevated run silently omitted every SYSTEM process (System,
// smss, csrss, wininit, services, lsass, and most svchost
// instances). The process count looked plausible, which made the
// omission easy to miss.
//
// The Toolhelp snapshot entry needs no handle, and neither does
// the kernel's process table, which carries memory, handle, I/O
// and CPU-time figures for every process.
//
// These rows used to leave all of those at zero: on the machine
// it was found on, 167 of 515 processes -- `dwm.exe`, `lsass.exe`
// and `Registry` among them -- reported using no memory, and every
// "largest by memory" list was ranked without them. A process
// with no table row exited between the two snapshots; it used to
// be listed here using no memory and no CPU, and is now left out.
let Some(row) = table.get(&pid).copied() else {
if Process32NextW(snapshot, &mut entry).is_err() {
break;
}
continue;
};
let cpu_time_us = (row.user_time_100ns + row.kernel_time_100ns) / 10;
let (cpu_percent, start_time) =
lifetime_cpu(row.create_time_100ns, cpu_time_us);
let null_pos = entry
.szExeFile
.iter()
.position(|&c| c == 0)
.unwrap_or(entry.szExeFile.len());
let name = String::from_utf16_lossy(&entry.szExeFile[..null_pos]);
let category = ProcessCategory::classify(&name, None, false);
processes.push(ProcessMonitorInfo {
pid,
name,
// Unknown rather than a guess: attributing these to the current
// user would be wrong, and they are usually SYSTEM.
user: None,
category,
cpu_percent,
memory_bytes: row.working_set_bytes,
gpu_indices: None,
gpu_memory_per_device: HashMap::new(),
total_gpu_memory_bytes: None,
state: 'U',
priority: None,
gfx_engine_used: None,
compute_engine_used: None,
enc_engine_used: None,
dec_engine_used: None,
gpu_usage_percent: None,
encoder_usage_percent: None,
decoder_usage_percent: None,
gpu_process_type: ProcessGpuType::Unknown,
gpu_memory_percentage: None,
parent_pid: Some(entry.th32ParentProcessID),
virtual_memory_bytes: row.pagefile_usage_bytes,
private_bytes: Some(row.private_bytes),
thread_count: entry.cntThreads,
handle_count: Some(row.handle_count),
io_read_bytes: Some(row.io_read_bytes),
io_write_bytes: Some(row.io_write_bytes),
start_time,
cpu_time_us,
});
}
// Move to next process
if Process32NextW(snapshot, &mut entry).is_err() {
break;
}
}
let _ = CloseHandle(snapshot);
}
Ok(processes)
}
}
// macOS-specific process enumeration
#[cfg(target_os = "macos")]
mod macos {
use super::*;
use std::ffi::CStr;
use std::mem;
// macOS proc_info constants
const PROC_PIDTASKALLINFO: i32 = 2;
const PROC_PIDPATHINFO_MAXSIZE: usize = 4096;
// FFI declarations for libproc
#[link(name = "proc", kind = "dylib")]
extern "C" {
fn proc_listpids(proc_type: u32, type_info: u32, buffer: *mut u8, buffer_size: i32) -> i32;
fn proc_pidinfo(pid: i32, flavor: i32, arg: u64, buffer: *mut u8, buffer_size: i32) -> i32;
fn proc_pidpath(pid: i32, buffer: *mut u8, buffer_size: u32) -> i32;
}
#[repr(C)]
struct MachTimebaseInfo {
numer: u32,
denom: u32,
}
extern "C" {
fn mach_timebase_info(info: *mut MachTimebaseInfo) -> i32;
}
#[repr(C)]
struct ProcTaskAllInfo {
pbsd: ProcBsdInfo,
ptinfo: ProcTaskInfo,
}
#[repr(C)]
struct ProcBsdInfo {
pbi_flags: u32,
pbi_status: u32,
pbi_xstatus: u32,
pbi_pid: u32,
pbi_ppid: u32,
pbi_uid: u32,
pbi_gid: u32,
pbi_ruid: u32,
pbi_rgid: u32,
pbi_svuid: u32,
pbi_svgid: u32,
_pad1: u32,
pbi_comm: [u8; 16],
pbi_name: [u8; 32],
pbi_nfiles: u32,
pbi_pgid: u32,
pbi_pjobc: u32,
e_tdev: u32,
e_tpgid: u32,
pbi_nice: i32,
pbi_start_tvsec: u64,
pbi_start_tvusec: u64,
}
#[repr(C)]
struct ProcTaskInfo {
pti_virtual_size: u64,
pti_resident_size: u64,
pti_total_user: u64,
pti_total_system: u64,
pti_threads_user: u64,
pti_threads_system: u64,
pti_policy: i32,
pti_faults: i32,
pti_pageins: i32,
pti_cow_faults: i32,
pti_messages_sent: i32,
pti_messages_received: i32,
pti_syscalls_mach: i32,
pti_syscalls_unix: i32,
pti_csw: i32,
pti_threadnum: i32,
pti_numrunning: i32,
pti_priority: i32,
}
pub fn enumerate_processes() -> Result<Vec<ProcessMonitorInfo>> {
let mut processes = Vec::new();
unsafe {
// First, get the number of processes
let num_pids = proc_listpids(1, 0, std::ptr::null_mut(), 0); // PROC_ALL_PIDS = 1
if num_pids <= 0 {
return Err(IronError::Other("Failed to get process count".to_string()));
}
// `num_pids` is a size in bytes, not a count. The buffer size passed
// below used to be that figure times four, telling the kernel the
// buffer was four times the allocation, so processes started between
// the two calls could be written past its end.
let mut pid_buffer = vec![0i32; num_pids as usize / mem::size_of::<i32>()];
let buffer_size = (pid_buffer.len() * mem::size_of::<i32>()) as i32;
// Get all PIDs
let actual_size = proc_listpids(
1, // PROC_ALL_PIDS
0,
pid_buffer.as_mut_ptr() as *mut u8,
buffer_size,
);
if actual_size <= 0 {
return Err(IronError::Other("Failed to list processes".to_string()));
}
let num_processes =
(actual_size as usize / mem::size_of::<i32>()).min(pid_buffer.len());
// `pti_total_user` and `pti_total_system` are mach absolute time:
// nanoseconds on Intel, timebase ticks (24 MHz, 125/3 ns each) on
// Apple silicon. They were read as microseconds, a CPU time a
// thousand times too large on Intel and about 24 times on Apple
// silicon, and a lifetime CPU percentage scaled the same way.
let mut timebase = MachTimebaseInfo { numer: 0, denom: 0 };
if mach_timebase_info(&mut timebase) != 0 || timebase.denom == 0 {
return Err(IronError::Other(
"mach_timebase_info gave no timebase to convert CPU time".to_string(),
));
}
let mach_to_us = |t: u64| {
(t as u128 * timebase.numer as u128 / timebase.denom as u128 / 1_000) as u64
};
// Iterate through each PID
for &pid in &pid_buffer[..num_processes] {
if pid <= 0 {
continue;
}
// Get process info
let mut task_info: ProcTaskAllInfo = mem::zeroed();
let info_size = proc_pidinfo(
pid,
PROC_PIDTASKALLINFO,
0,
&mut task_info as *mut _ as *mut u8,
mem::size_of::<ProcTaskAllInfo>() as i32,
);
if info_size <= 0 {
continue; // Process may have exited
}
// Get process path
let mut path_buffer = [0u8; PROC_PIDPATHINFO_MAXSIZE];
let path_len = proc_pidpath(
pid,
path_buffer.as_mut_ptr(),
PROC_PIDPATHINFO_MAXSIZE as u32,
);
let name = if path_len > 0 {
// Extract filename from path
let path_slice = &path_buffer[..path_len as usize];
if let Ok(path_str) = CStr::from_bytes_until_nul(path_slice)
.map(|c| c.to_string_lossy().to_string())
{
std::path::Path::new(&path_str)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("Unknown")
.to_string()
} else {
// Fallback to comm name
let null_pos = task_info
.pbsd
.pbi_comm
.iter()
.position(|&c| c == 0)
.unwrap_or(task_info.pbsd.pbi_comm.len());
String::from_utf8_lossy(&task_info.pbsd.pbi_comm[..null_pos]).to_string()
}
} else {
// Use process name from pbsd info
let null_pos = task_info
.pbsd
.pbi_comm
.iter()
.position(|&c| c == 0)
.unwrap_or(task_info.pbsd.pbi_comm.len());
String::from_utf8_lossy(&task_info.pbsd.pbi_comm[..null_pos]).to_string()
};
// Cumulative CPU time in microseconds for delta-based calculation
let cpu_time_us =
mach_to_us(task_info.ptinfo.pti_total_user + task_info.ptinfo.pti_total_system);
// Calculate CPU% as lifetime average (fallback for first delta sample)
let process_start_secs = task_info.pbsd.pbi_start_tvsec;
// A process started within the current second has no lifetime
// to average over at this resolution; this assumed one second.
let now_secs = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.map(|d| d.as_secs());
let total_cpu_secs = cpu_time_us as f64 / 1_000_000.0;
let cpu_percent = now_secs.filter(|&now| now > process_start_secs).map(|now| {
((total_cpu_secs / (now - process_start_secs) as f64) * 100.0) as f32
});
// Status mapping, to the state letters the struct documents. SSTOP
// is stopped (`T`). It used to be mapped through the word "Stopped"
// and then its first letter, which is `S`, sleeping.
let state = match task_info.pbsd.pbi_status {
1 => 'I', // SIDL: being created, or idle
2 => 'R', // SRUN
3 => 'S', // SSLEEP
4 => 'T', // SSTOP
5 => 'Z', // SZOMB
_ => 'U',
};
// The uid is a number. The name comes from the account database,
// or is `None` when there is no such account. It used to be the
// number itself, so `root` was never recognised as root.
let user = user_name(task_info.pbsd.pbi_uid);
let category = ProcessCategory::classify(&name, user.as_deref(), false);
processes.push(ProcessMonitorInfo {
pid: pid as u32,
parent_pid: Some(task_info.pbsd.pbi_ppid),
name,
user,
category,
cpu_percent,
memory_bytes: task_info.ptinfo.pti_resident_size,
virtual_memory_bytes: task_info.ptinfo.pti_virtual_size,
private_bytes: None,
thread_count: task_info.ptinfo.pti_threadnum as u32,
// None of the three is read here; `proc_pid_rusage`
// carries disk I/O and is the place to start.
handle_count: None,
io_read_bytes: None,
io_write_bytes: None,
start_time: Some(task_info.pbsd.pbi_start_tvsec),
gpu_indices: None,
gpu_memory_per_device: HashMap::new(),
total_gpu_memory_bytes: None,
state,
priority: Some(task_info.ptinfo.pti_priority),
gfx_engine_used: None,
compute_engine_used: None,
enc_engine_used: None,
dec_engine_used: None,
gpu_usage_percent: None,
encoder_usage_percent: None,
decoder_usage_percent: None,
gpu_process_type: ProcessGpuType::Unknown,
gpu_memory_percentage: None,
cpu_time_us,
});
}
}
Ok(processes)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A process whose `/proc/<pid>/io` is refused has not done no I/O.
///
/// Unprivileged, init's counters are unreadable, and the reader recorded
/// them as zero bytes read and written. Its own process is readable, so
/// the same reader must return figures there.
#[cfg(target_os = "linux")]
#[test]
fn unreadable_io_counters_are_not_zero_io() {
let uptime = linux::read_uptime().expect("uptime");
let own = linux::read_process_info(std::process::id(), uptime).expect("own process");
assert!(
own.io_read_bytes.is_some(),
"this process's own counters are readable"
);
assert!(own.handle_count.is_some());
if unsafe { libc::geteuid() } != 0 {
let init = linux::read_process_info(1, uptime).expect("pid 1");
if std::fs::read_to_string("/proc/1/io").is_err() {
assert_eq!(
init.io_read_bytes, None,
"refused counters read as a figure"
);
assert_eq!(init.io_write_bytes, None);
}
}
}
/// A process that cannot be opened still has a working set, and the
/// enumeration must report it.
///
/// Unelevated, those rows were emitted with memory at zero: 167 of 515
/// processes on the machine this was found on, `dwm.exe` and `lsass.exe`
/// among them. The kernel process table reads them without a handle, so any
/// process it reports as holding real memory must not be listed with none.
/// A working set can legitimately be zero -- an idle process whose pages
/// were trimmed -- so the check applies only above 8 MiB.
#[cfg(target_os = "windows")]
#[test]
fn processes_that_cannot_be_opened_still_report_their_memory() {
let table = crate::platform::windows::system_process_table().expect("process table");
let procs = windows_impl::enumerate_processes().expect("processes");
let missing: Vec<String> = procs
.iter()
.filter(|p| p.memory_bytes == 0)
.filter(|p| {
table
.get(&p.pid)
.is_some_and(|r| r.working_set_bytes >= 8 << 20)
})
.map(|p| format!("{} {}", p.pid, p.name))
.collect();
assert!(
missing.is_empty(),
"reported with no memory, though the kernel says otherwise: {missing:?}"
);
}
/// Protected system processes must appear in the listing.
///
/// `csrss.exe` and `wininit.exe` run as protected processes: `OpenProcess` with
/// `PROCESS_VM_READ` is denied for them even from an elevated context. The
/// enumeration loop only emits a process when the open succeeds, so requesting
/// that right silently dropped every protected process from the results.
/// Narrowing the mask to `PROCESS_QUERY_LIMITED_INFORMATION` both restores them
/// and removes the failed-open cost.
#[cfg(target_os = "windows")]
#[test]
fn enumeration_includes_protected_system_processes() {
let mut monitor = match ProcessMonitor::new() {
Ok(m) => m,
Err(e) => {
eprintln!("skipping: ProcessMonitor unavailable: {e}");
return;
}
};
let processes = monitor.processes().expect("enumeration should succeed");
assert!(
processes.len() > 20,
"implausibly short process listing: {}",
processes.len()
);
let names: Vec<String> = processes.iter().map(|p| p.name.to_lowercase()).collect();
for protected in ["csrss.exe", "wininit.exe"] {
assert!(
names.iter().any(|n| n == protected),
"protected process {protected} missing; OpenProcess is requesting more \
access than it needs. Present: {} processes",
processes.len()
);
}
}
/// The username memoization must not leak one process's identity to another.
///
/// Windows recycles PIDs aggressively, so the cache is keyed on
/// (pid, creation_time) rather than pid alone.
#[cfg(target_os = "windows")]
#[test]
fn repeated_enumeration_is_stable_and_consistent() {
let mut monitor = match ProcessMonitor::new() {
Ok(m) => m,
Err(e) => {
eprintln!("skipping: ProcessMonitor unavailable: {e}");
return;
}
};
let first = monitor.processes().expect("first enumeration");
let second = monitor
.processes()
.expect("second enumeration (cache warm)");
// The invariant under test is that a PID never reports one *identity* and
// then a different one — that would mean the memoization handed back another
// process's user.
//
// Some -> None is not that bug: it happens when a process becomes unopenable
// between scans (usually because it is exiting), and the reduced
// snapshot-only row legitimately carries no user. Only compare when both
// scans actually resolved a name.
let by_pid: HashMap<u32, Option<String>> =
first.iter().map(|p| (p.pid, p.user.clone())).collect();
for proc in &second {
let (Some(Some(previous)), Some(current)) = (by_pid.get(&proc.pid), proc.user.as_ref())
else {
continue;
};
assert_eq!(
previous, current,
"pid {} reported user {:?} then {:?}; the username cache returned \
another process's identity",
proc.pid, previous, current
);
}
}
fn make_test_process() -> ProcessMonitorInfo {
ProcessMonitorInfo {
pid: 1234,
parent_pid: Some(1),
name: "test_process".to_string(),
user: Some("testuser".to_string()),
category: ProcessCategory::Unknown,
cpu_percent: Some(25.5),
memory_bytes: 1024 * 1024 * 512,
virtual_memory_bytes: 1024 * 1024 * 1024,
private_bytes: Some(1024 * 1024 * 256),
thread_count: 4,
handle_count: Some(100),
io_read_bytes: Some(0),
io_write_bytes: Some(0),
start_time: None,
gpu_indices: Some(vec![]),
gpu_memory_per_device: HashMap::new(),
total_gpu_memory_bytes: None,
state: 'R',
priority: Some(0),
gfx_engine_used: None,
compute_engine_used: None,
enc_engine_used: None,
dec_engine_used: None,
gpu_usage_percent: None,
encoder_usage_percent: None,
decoder_usage_percent: None,
gpu_process_type: ProcessGpuType::Unknown,
cpu_time_us: 0,
gpu_memory_percentage: None,
}
}
#[test]
fn test_classify_system() {
assert_eq!(
ProcessCategory::classify("systemd", None, false),
ProcessCategory::System
);
}
#[test]
fn test_classify_browser() {
assert_eq!(
ProcessCategory::classify("firefox", None, false),
ProcessCategory::Browser
);
assert_eq!(
ProcessCategory::classify("chrome", None, false),
ProcessCategory::Browser
);
}
#[test]
fn test_classify_development() {
assert_eq!(
ProcessCategory::classify("cargo", None, false),
ProcessCategory::Development
);
assert_eq!(
ProcessCategory::classify("rustc", None, false),
ProcessCategory::Development
);
}
#[test]
fn test_classify_ai_ml_gpu() {
assert_eq!(
ProcessCategory::classify("python", None, true),
ProcessCategory::AiMl
);
assert_eq!(
ProcessCategory::classify("ollama", None, true),
ProcessCategory::AiMl
);
}
#[test]
fn test_classify_gpu_gaming() {
assert_eq!(
ProcessCategory::classify("steam", None, true),
ProcessCategory::Gaming
);
}
/// A name nothing recognises, holding a GPU context, is still separated
/// out — but only after the name categories have had their turn.
#[test]
fn test_classify_gpu_generic() {
assert_eq!(
ProcessCategory::classify("someapp", None, true),
ProcessCategory::GpuCompute
);
}
/// A browser holding a GPU context is a browser.
///
/// Every windowed application on Windows holds one, so this branch used to
/// report 24 processes as "GPU Compute" — WindowsTerminal.exe, brave.exe
/// and Code.exe among them, all of which `nvidia-smi` labels `C+G` with
/// `[N/A]` memory. A GPU context is not evidence of a GPU workload.
#[test]
fn a_gpu_context_does_not_override_what_a_process_is() {
for (name, want) in [
("brave.exe", ProcessCategory::Browser),
("Code.exe", ProcessCategory::Development),
] {
assert_eq!(
ProcessCategory::classify(name, None, true),
want,
"{name} holds a GPU context and is still a {want:?}"
);
assert_eq!(
ProcessCategory::classify(name, None, false),
want,
"{name} classifies the same either way"
);
}
// The evidence-backed branches are untouched: a GPU context plus one of
// these names is a real signal.
assert_eq!(
ProcessCategory::classify("python", None, true),
ProcessCategory::AiMl
);
assert_eq!(
ProcessCategory::classify("steam", None, true),
ProcessCategory::Gaming
);
}
#[test]
fn test_classify_service() {
assert_eq!(
ProcessCategory::classify("sshd", None, false),
ProcessCategory::Service
);
}
#[test]
fn test_classify_media() {
assert_eq!(
ProcessCategory::classify("vlc", None, false),
ProcessCategory::Media
);
}
/// A pattern counts only as a whole word. `obs` is the OBS recorder, and
/// the same letters inside `obsidian` are a notes app.
#[test]
fn a_pattern_inside_a_longer_word_does_not_classify_the_process() {
assert_eq!(
ProcessCategory::classify("obsidian", None, false),
ProcessCategory::Productivity
);
assert_eq!(
ProcessCategory::classify("obs-studio", None, false),
ProcessCategory::Media
);
assert_eq!(
ProcessCategory::classify("python3.11", None, false),
ProcessCategory::AiMl
);
}
#[test]
fn test_classify_unknown() {
assert_eq!(
ProcessCategory::classify("xyzzy_unknown_proc", None, false),
ProcessCategory::Unknown
);
}
#[test]
fn test_classify_case_insensitive() {
assert_eq!(
ProcessCategory::classify("Firefox", None, false),
ProcessCategory::Browser
);
assert_eq!(
ProcessCategory::classify("CHROME", None, false),
ProcessCategory::Browser
);
}
#[test]
fn test_memory_mb() {
let p = make_test_process();
assert!((p.memory_mb() - 512.0).abs() < 0.01);
}
#[test]
fn test_cpu_usage() {
let p = make_test_process();
assert!((p.cpu_usage().unwrap() - 25.5).abs() < 0.01);
}
#[test]
fn test_is_gpu_process() {
let mut p = make_test_process();
assert_eq!(p.is_gpu_process(), Some(false));
p.gpu_indices.get_or_insert_with(Vec::new).push(0);
assert_eq!(p.is_gpu_process(), Some(true));
// Attribution that never ran is unknown, not "no GPU".
p.gpu_indices = None;
assert_eq!(p.is_gpu_process(), None);
assert_eq!(p.gpu_count(), None);
}
/// Without a GPU collection, attribution never runs, so every process reports
/// its GPU use as unknown rather than as none.
#[test]
fn a_monitor_without_gpus_reports_gpu_use_as_unknown() {
let mut monitor = ProcessMonitor::without_gpu().unwrap();
let procs = monitor.processes().unwrap();
assert!(!procs.is_empty());
assert!(procs.iter().all(|p| p.gpu_indices.is_none()));
assert!(procs.iter().all(|p| p.is_gpu_process().is_none()));
}
/// A process no device reported memory for reads back as unknown, and a
/// process measured at zero reads back as zero. NVML declines to report at
/// all under WDDM, so on Windows the first case is every process.
#[test]
fn test_gpu_memory_mb() {
let mut p = make_test_process();
assert_eq!(p.gpu_memory_mb(), None, "nothing reported is not zero MB");
p.total_gpu_memory_bytes = Some(0);
assert_eq!(
p.gpu_memory_mb(),
Some(0.0),
"a device reporting zero is a measurement"
);
p.total_gpu_memory_bytes = Some(1024 * 1024 * 256);
assert!((p.gpu_memory_mb().expect("reported") - 256.0).abs() < 0.01);
}
#[test]
fn test_reclassify() {
let mut p = make_test_process();
p.name = "firefox".to_string();
p.reclassify();
assert_eq!(p.category, ProcessCategory::Browser);
}
#[test]
fn test_process_gpu_type_from_engine_usage() {
assert_eq!(
ProcessGpuType::from_engine_usage(100, 0),
ProcessGpuType::Graphical
);
assert_eq!(
ProcessGpuType::from_engine_usage(0, 100),
ProcessGpuType::Compute
);
assert_eq!(
ProcessGpuType::from_engine_usage(100, 100),
ProcessGpuType::GraphicalCompute
);
assert_eq!(
ProcessGpuType::from_engine_usage(0, 0),
ProcessGpuType::Unknown
);
}
#[test]
fn test_process_gpu_type_display() {
assert_eq!(format!("{}", ProcessGpuType::Graphical), "Graphics");
assert_eq!(format!("{}", ProcessGpuType::Compute), "Compute");
assert_eq!(
format!("{}", ProcessGpuType::GraphicalCompute),
"Gfx+Compute"
);
assert_eq!(format!("{}", ProcessGpuType::Unknown), "Unknown");
}
#[test]
fn test_category_display_name() {
assert_eq!(ProcessCategory::System.display_name(), "System");
assert_eq!(ProcessCategory::Browser.display_name(), "Browsers");
assert_eq!(ProcessCategory::AiMl.display_name(), "AI/ML");
assert_eq!(ProcessCategory::GpuCompute.display_name(), "Using GPU");
}
#[test]
fn test_category_icon() {
assert!(!ProcessCategory::System.icon().is_empty());
assert!(!ProcessCategory::Browser.icon().is_empty());
assert!(!ProcessCategory::Unknown.icon().is_empty());
}
#[test]
fn test_category_all_unique() {
let all = ProcessCategory::all();
let unique: std::collections::HashSet<_> = all.iter().collect();
assert_eq!(all.len(), unique.len());
}
#[test]
fn test_process_gpu_count() {
let mut p = make_test_process();
assert_eq!(p.gpu_count(), Some(0));
p.gpu_indices = Some(vec![0, 1]);
assert_eq!(p.gpu_count(), Some(2));
}
#[test]
fn test_process_category_default() {
assert_eq!(ProcessCategory::default(), ProcessCategory::Unknown);
}
}
#[cfg(test)]
mod cpu_normalisation_tests {
use super::*;
/// The divisor is read once, in one place. Four copies of this expression
/// existed; the risk a shared helper removes is that a later fix reaches
/// only the copy in front of whoever is looking.
#[test]
fn the_logical_cpu_count_is_read_from_one_place() {
// On every platform this crate builds for, the count is readable.
let count = logical_cpu_count().expect("available_parallelism answers here");
assert!(count >= 1.0, "a machine has at least one logical CPU");
assert_eq!(
count,
std::thread::available_parallelism().unwrap().get() as f32
);
}
/// A normalised percentage is a share of the whole machine; an
/// un-normalised one is a share of one core. The accessor is the only way a
/// consumer can tell, because `cpu_percent` carries only the number.
#[test]
fn a_monitor_that_read_the_core_count_reports_normalised_percentages() {
let monitor = ProcessMonitor::new().expect("process monitor constructs here");
assert_eq!(
monitor.cpu_percent_is_normalized(),
monitor.num_logical_cpus.is_some(),
"the accessor must describe the divisor that was actually used"
);
// This machine can read its core count, so the figures are shares of it.
assert!(monitor.cpu_percent_is_normalized());
}
/// The property that a fallback of `1.0` violated: normalising by one is
/// indistinguishable from not normalising, so a saturated core reads as a
/// saturated machine.
#[test]
fn one_is_not_a_neutral_divisor() {
let saturated_single_core = 100.0_f32;
let cpus = logical_cpu_count().unwrap();
if cpus > 1.0 {
assert!(
saturated_single_core / cpus < saturated_single_core,
"dividing by the real count must change the answer, which is \
why falling back to 1.0 was a fabrication rather than a no-op"
);
}
}
}