-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathplugin.cpp
More file actions
4928 lines (4667 loc) · 191 KB
/
plugin.cpp
File metadata and controls
4928 lines (4667 loc) · 191 KB
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
/**
* Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* SPDX-License-Identifier: GPL-2.0-only
*/
#include "plugin.h"
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpointer-arith"
ParserPlugin::ParserPlugin(){
// Inode structure
struct_init(inode);
// Dentry structure and related fields
struct_init(dentry);
field_init(dentry, d_u);
field_init(dentry, d_subdirs);
field_init(dentry, d_children);
field_init(dentry, d_child);
field_init(dentry, d_inode);
field_init(dentry, d_sib);
field_init(dentry, d_iname);
field_init(dentry, d_name);
field_init(dentry, d_sb);
// String structure for dentry names
field_init(qstr, name);
field_init(qstr, len);
// Mount structures (modern and legacy)
field_init(mount, mnt_parent);
field_init(mount, mnt_mountpoint);
field_init(mount, mnt);
field_init(mount, mnt_sb);
field_init(vfsmount, mnt_parent);
field_init(vfsmount, mnt_mountpoint);
field_init(vfsmount, mnt_root);
field_init(vfsmount, mnt_sb);
// Address space for file mapping
struct_init(address_space);
field_init(address_space, host);
field_init(address_space, a_ops);
field_init(address_space, nrpages);
field_init(address_space, i_pages);
field_init(address_space, page_tree);
// Super block structure
field_init(super_block, s_inodes);
field_init(inode, i_sb_list);
// Task structure
struct_init(task_struct);
field_init(task_struct, active_mm);
field_init(task_struct, mm);
field_init(task_struct, tasks);
field_init(task_struct, files);
// File descriptor structures
field_init(files_struct, fdt);
field_init(fdtable, max_fds);
field_init(fdtable, fd);
// Memory management structures
struct_init(mm_struct);
field_init(mm_struct, pgd);
field_init(mm_struct, arg_start);
field_init(mm_struct, arg_end);
field_init(mm_struct, mmap);
field_init(mm_struct, mm_mt);
// Maple tree for VMA management (newer kernels)
field_init(maple_tree, ma_root);
// Virtual memory area structures
struct_init(vm_area_struct);
field_init(vm_area_struct, vm_start);
field_init(vm_area_struct, vm_end);
field_init(vm_area_struct, vm_flags);
field_init(vm_area_struct, vm_next);
// Page structure
struct_init(page);
field_init(page, _mapcount);
field_init(page, freelist);
field_init(page, units);
field_init(page, index);
field_init(page, private);
field_init(page, page_type);
field_init(page, _count);
field_init(page, _refcount);
field_init(page, mapping);
// Generic list structure
struct_init(list_head);
field_init(list_head, prev);
field_init(list_head, next);
// Block device structures
field_init(block_device, bd_disk);
field_init(block_device, bd_list);
field_init(block_device, bd_device);
field_init(bdev_inode, vfs_inode);
field_init(bdev_inode, bdev);
// Driver and device private structures
field_init(driver_private, driver);
field_init(driver_private, klist_devices);
field_init(driver_private, knode_bus);
field_init(device_private, knode_bus);
field_init(device_private, device);
field_init(device_private, knode_driver);
field_init(device_private, knode_class);
// Subsystem private structures
field_init(subsys_private, klist_drivers);
field_init(subsys_private, klist_devices);
field_init(subsys_private, bus);
field_init(subsys_private, subsys);
field_init(subsys_private, class);
// Kernel list and kobject structures
field_init(klist_node, n_node);
field_init(klist, k_list);
field_init(device_driver, p);
field_init(device_driver, name); // Driver name
field_init(device_driver, mod_name); // Module name
field_init(device_driver, probe); // Probe function pointer
field_init(device_driver, of_match_table); // Device tree match table
field_init(device, driver_data);
field_init(device, kobj); // Embedded kobject for sysfs
field_init(device, driver); // Pointer to bound driver
field_init(bus_type, p);
field_init(bus_type, name);
field_init(bus_type, probe);
field_init(class, p);
field_init(class, name);
field_init(kset, kobj);
field_init(kset, list);
field_init(kobject, entry);
field_init(kobject, name); // Device name
field_init(of_device_id,compatible);
// Character device structures
field_init(char_device_struct, next);
field_init(char_device_struct, cdev);
field_init(char_device_struct, name);
field_init(miscdevice, list);
// Handle and probe structures
field_init(handle_parts, pool_index);
field_init(handle_parts, pool_index_plus_1);
field_init(kobj_map, probes);
field_init(probe, data);
field_init(probe, next);
field_init(page_owner,order);
field_init(page_owner,last_migrate_reason);
field_init(page_owner,gfp_mask);
field_init(page_owner,handle);
field_init(page_owner,free_handle);
field_init(page_owner,ts_nsec);
field_init(page_owner,free_ts_nsec);
field_init(page_owner,pid);
field_init(page_owner,tgid);
field_init(page_owner,comm);
field_init(page_owner,free_pid);
field_init(page_owner,free_tgid);
struct_init(page_owner);
field_init(mem_section,page_ext);
field_init(pglist_data,node_page_ext);
field_init(page_ext,flags);
struct_init(page_ext);
field_init(page_ext_operations,offset);
field_init(page_ext_operations,size);
struct_init(page_ext_operations);
field_init(stack_record,next);
field_init(stack_record,size);
field_init(stack_record,handle);
field_init(stack_record,entries);
struct_init(stack_record);
if (BITS64()){
std::string config = get_config_val("CONFIG_ARM64_VA_BITS");
int va_bits = std::stoi(config);
kaddr_mask = GENMASK_ULL((va_bits ? va_bits : 39) - 1, 0);
} else {
kaddr_mask = GENMASK_ULL(32 - 1, 0);
}
if (csymbol_exists("depot_index")){
depot_index = read_int(csymbol_value("depot_index"), "depot_index");
} else if (csymbol_exists("pool_index")){
depot_index = read_int(csymbol_value("pool_index"), "pool_index");
} else if (csymbol_exists("pools_num")){
depot_index = read_int(csymbol_value("pools_num"), "pools_num");
}
if (csymbol_exists("stack_slabs")){
stack_slabs = csymbol_value("stack_slabs");
} else if (csymbol_exists("stack_pools")){ /* 6.3 and later */
stack_slabs = csymbol_value("stack_pools");
}
/* max_pfn */
max_pfn = csymbol_exists("max_pfn") ?
(try_get_symbol_data(TO_CONST_STRING("max_pfn"), sizeof(ulong), &max_pfn), max_pfn) : 0;
/* min_low_pfn */
min_low_pfn = csymbol_exists("min_low_pfn") ?
(try_get_symbol_data(TO_CONST_STRING("min_low_pfn"), sizeof(ulong), &min_low_pfn), min_low_pfn) : 0;
// Get the offset of page_owner within page_ext structure
if (csymbol_exists("page_owner_ops")){
ulong ops_addr = csymbol_value("page_owner_ops");
page_ext_ops_offset = read_ulong(ops_addr + field_offset(page_ext_operations,offset),"page_owner_ops.offset");
LOGD("ops_offset: %zu", page_ext_ops_offset);
}
// Read page extension flag bit positions
PAGE_EXT_OWNER = read_enum_val("PAGE_EXT_OWNER");
PAGE_EXT_OWNER_ALLOCATED = read_enum_val("PAGE_EXT_OWNER_ALLOCATED");
//print_table();
}
/**
* Formats a nanosecond timestamp into a human-readable uptime string
*
* Converts a timestamp in nanoseconds to a formatted string showing days, hours,
* minutes, seconds, and nanoseconds in the format "Xd HH:MM:SS.nnnnnnnnn (uptime)".
* Days are only shown if greater than 0.
*
* @param timestamp_ns The timestamp in nanoseconds to format
* @return A formatted string representation of the uptime
*
* Example outputs:
* - "00:01:30.123456789 (uptime)" for 90.123456789 seconds
* - "1d 02:30:45.987654321 (uptime)" for 1 day, 2 hours, 30 minutes, 45.987654321 seconds
*/
std::string ParserPlugin::formatTimestamp(uint64_t timestamp_ns) {
constexpr uint64_t NS_PER_SEC = 1000000000ULL;
constexpr uint64_t SEC_PER_MIN = 60;
constexpr uint64_t SEC_PER_HOUR = 3600;
constexpr uint64_t SEC_PER_DAY = 86400;
uint64_t total_seconds = timestamp_ns / NS_PER_SEC;
uint64_t ns_part = timestamp_ns % NS_PER_SEC;
uint64_t days = total_seconds / SEC_PER_DAY;
uint64_t remaining_seconds = total_seconds % SEC_PER_DAY;
uint64_t hours = remaining_seconds / SEC_PER_HOUR;
remaining_seconds %= SEC_PER_HOUR;
uint64_t minutes = remaining_seconds / SEC_PER_MIN;
uint64_t seconds = remaining_seconds % SEC_PER_MIN;
std::ostringstream oss;
oss.imbue(std::locale::classic());
if (days > 0) {
oss << days << "d ";
}
oss << std::setfill('0')
<< std::setw(2) << hours << ':'
<< std::setw(2) << minutes << ':'
<< std::setw(2) << seconds << '.'
<< std::setw(9) << ns_part << " (uptime)";
return oss.str();
}
bool ParserPlugin::isNumber(const std::string& str) {
regex_t decimal, hex;
bool result = false;
if (regcomp(&decimal, "^-?[0-9]+$", REG_EXTENDED)) {
LOGE("Could not compile decimal regex\n");
return false;
}
if (regcomp(&hex, "^0[xX][0-9a-fA-F]+$", REG_EXTENDED)) {
LOGE("Could not compile hex regex \n");
regfree(&decimal);
return false;
}
if (!regexec(&decimal, str.c_str(), 0, NULL, 0) || !regexec(&hex, str.c_str(), 0, NULL, 0)) {
result = true;
}
regfree(&decimal);
regfree(&hex);
return result;
}
/**
* Formats a byte size into a human-readable string with appropriate units
*
* Converts a size in bytes to a formatted string using the most appropriate
* unit (B, KB, MB, GB). The function automatically selects the largest unit
* where the value is >= 1, and uses appropriate decimal precision to avoid
* unnecessary decimal places for whole numbers.
*
* @param size The size in bytes to format
* @return A formatted string with the size and appropriate unit
*
* Example outputs:
* - "512B" for 512 bytes
* - "1KB" for 1024 bytes
* - "1.5KB" for 1536 bytes
* - "2MB" for 2097152 bytes
* - "1.25GB" for 1342177280 bytes
*/
std::string ParserPlugin::csize(uint64_t size){
constexpr uint64_t KB = 1024ULL;
constexpr uint64_t MB = KB * 1024ULL;
constexpr uint64_t GB = MB * 1024ULL;
std::ostringstream oss;
oss.imbue(std::locale::classic());
if (size < KB) {
oss << size << " B";
} else if (size < MB) {
double sizeInKB = static_cast<double>(size) / KB;
oss << std::fixed << std::setprecision(sizeInKB == static_cast<uint64_t>(sizeInKB) ? 0 : 2) << sizeInKB << " KB";
} else if (size < GB) {
double sizeInMB = static_cast<double>(size) / MB;
oss << std::fixed << std::setprecision(sizeInMB == static_cast<uint64_t>(sizeInMB) ? 0 : 2) << sizeInMB << " MB";
} else {
double sizeInGB = static_cast<double>(size) / GB;
oss << std::fixed << std::setprecision(sizeInGB == static_cast<uint64_t>(sizeInGB) ? 0 : 2) << sizeInGB << " GB";
}
return oss.str();
}
/**
* Formats a byte size into a human-readable string with specified unit and precision
*
* Converts a size in bytes to a formatted string using the specified unit
* (KB, MB, GB, or B for bytes). Unlike the automatic unit selection version,
* this function forces the output to use the exact unit specified by the caller
* with the given decimal precision.
*
* @param size The size in bytes to format
* @param unit The unit to use for formatting (KB=1024, MB=1048576, GB=1073741824, or other for bytes)
* @param precision The number of decimal places to display
* @return A formatted string with the size in the specified unit
*
* Example outputs:
* - csize(1536, 1024, 2) returns "1.50 KB"
* - csize(2097152, 1048576, 0) returns "2 MB"
* - csize(512, 0, 0) returns "512B"
*/
std::string ParserPlugin::csize(uint64_t size, int unit, int precision){
constexpr uint64_t KB = 1024ULL;
constexpr uint64_t MB = KB * 1024ULL;
constexpr uint64_t GB = MB * 1024ULL;
std::ostringstream oss;
oss.imbue(std::locale::classic());
switch (unit) {
case KB:
oss << std::fixed << std::setprecision(precision) << (static_cast<double>(size) / KB) << " KB";
break;
case MB:
oss << std::fixed << std::setprecision(precision) << (static_cast<double>(size) / MB) << " MB";
break;
case GB:
oss << std::fixed << std::setprecision(precision) << (static_cast<double>(size) / GB) << " GB";
break;
default:
oss << size << "B";
break;
}
return oss.str();
}
/**
* Find a task context by process ID (PID)
*
* This function searches for a task context structure corresponding to the given PID.
* It first attempts to use the task table directly for better performance if the PID
* is within the range of running tasks. If not found there, it falls back to iterating
* through all processes in the system.
*
* @param pid The process ID to search for
* @return Pointer to the task_context structure if found, nullptr if not found or invalid PID
*/
struct task_context* ParserPlugin::find_proc(ulong pid){
if (pid == 0) {
return nullptr;
}
// Check if we can use the task table directly for better performance
if (pid <= RUNNING_TASKS()) {
struct task_context *tc = FIRST_CONTEXT();
for (size_t i = 0; i < RUNNING_TASKS(); i++, tc++) {
if (tc->pid == pid) {
return tc;
}
}
}
// Fallback to process iteration
for(ulong task_addr: for_each_process()){
struct task_context *tc = task_to_context(task_addr);
if (!tc){
continue;
}
if (tc->pid == pid){
return tc;
}
}
return nullptr;
}
/**
* Find a task context by process name (command)
*
* This function searches for a task context structure corresponding to the given process name.
* It first attempts to use the task table directly for better performance if available,
* then falls back to iterating through all processes in the system.
*
* @param name The process name (command) to search for
* @return Pointer to the task_context structure if found, nullptr if not found or empty name
*/
struct task_context* ParserPlugin::find_proc(const std::string& name){
if (name.empty()) {
return nullptr;
}
// Check running tasks first for better performance
struct task_context *tc = FIRST_CONTEXT();
for (size_t i = 0; i < RUNNING_TASKS(); i++, tc++) {
if (tc->comm == name) {
return tc;
}
}
// Fallback to process iteration
for(ulong task_addr: for_each_process()){
struct task_context *tc = task_to_context(task_addr);
if (!tc){
continue;
}
if (tc->comm == name){
return tc;
}
}
return nullptr;
}
/**
* Check if a page is a buddy system page (free page)
*
* This function determines whether a given page is currently managed by the
* kernel's buddy allocator system as a free page. The detection method varies
* based on kernel version due to changes in the page structure fields used
* to track buddy pages.
*
* For kernels >= 4.19.0:
* - Uses the page_type field with specific bit patterns to identify buddy pages
* - Checks if (page_type & 0xf0000080) == 0xf0000000 to detect buddy pages
*
* For older kernels:
* - Uses the _mapcount field with a magic value (0xffffff80) to identify buddy pages
* - This was the traditional method before page_type was introduced
*
* @param page_addr The kernel virtual address of the page structure to check
* @return true if the page is a buddy (free) page, false otherwise
*/
bool ParserPlugin::page_buddy(ulong page_addr){
if (THIS_KERNEL_VERSION >= LINUX(4, 19, 0)){
uint page_type = read_uint(page_addr + field_offset(page,page_type),"page_type");
return ((page_type & 0xf0000080) == 0xf0000000);
}
uint mapcount = read_int(page_addr + field_offset(page,_mapcount),"_mapcount");
return (mapcount == 0xffffff80);
}
/**
* Get the reference count of a page structure
*
* This function retrieves the reference count (usage count) of a page structure,
* which indicates how many references exist to this page. The implementation
* varies based on kernel version due to changes in the page structure fields
* used to track reference counts.
*
* For kernels >= 4.6.0:
* - Uses the _refcount field which replaced the older _count field
* - This change was part of the atomic_t -> refcount_t conversion
*
* For older kernels (< 4.6.0):
* - Uses the legacy _count field for reference counting
* - This was the original field name before the refcount_t introduction
*
* @param page_addr The kernel virtual address of the page structure to check
* @return The reference count of the page (0 means the page is free)
*/
int ParserPlugin::page_count(ulong page_addr){
if (THIS_KERNEL_VERSION < LINUX(4, 6, 0)){
return read_int(page_addr + field_offset(page,_count),"_count");
}
return read_int(page_addr + field_offset(page,_refcount),"_refcount");
}
void ParserPlugin::initialize(void){
cmd_help = new char*[help_str_list.size()+1];
for (size_t i = 0; i < help_str_list.size(); ++i) {
cmd_help[i] = TO_CONST_STRING(help_str_list[i].c_str());
}
cmd_help[help_str_list.size()] = nullptr;
}
/**
* Initialize type information for a structure type
*
* This function creates and stores type information for a given structure type
* in the global type table. It creates a Typeinfo object that contains metadata
* about the structure such as its size and other properties needed for memory
* analysis and field access operations.
*
* @param type The name of the structure type to initialize (e.g., "task_struct", "mm_struct")
*/
void ParserPlugin::type_init(const std::string& type, bool is_anon){
std::string name = type;
typetable[name] = std::make_unique<Typeinfo>(type, is_anon);
}
/**
* Initialize type information for a specific field within a structure type
*
* This function creates and stores type information for a given field within a structure type
* in the global type table. It creates a Typeinfo object that contains metadata about the
* specific field such as its offset within the structure and size, which are needed for
* memory analysis and field access operations.
*
* @param type The name of the structure type containing the field (e.g., "task_struct", "mm_struct")
* @param field The name of the field within the structure (e.g., "pid", "comm", "mm")
*
*/
void ParserPlugin::type_init(const std::string& type,const std::string& field, bool is_anon){
std::string name = type + "@" + field;
typetable[name] = std::make_unique<Typeinfo>(type,field, is_anon);
}
/**
* Get the byte offset of a specific field within a structure type
*
* This function retrieves the byte offset of a field within a structure from
* the global type table. The offset information is essential for accessing
* structure members when reading kernel memory or performing field-based
* operations on kernel data structures.
*
* @param type The name of the structure type containing the field (e.g., "task_struct", "mm_struct")
* @param field The name of the field within the structure (e.g., "pid", "comm", "mm")
* @return The byte offset of the field within the structure, or -1 if the type information is not found
*
*/
int ParserPlugin::type_offset(const std::string& type,const std::string& field){
std::string name = type + "@" + field;
auto it = typetable.find(name);
if (it != typetable.end()) {
return it->second->offset();
} else {
LOGE("Error: Typeinfo not found for %s, pls add field_init(%s,%s)\n",name.c_str(),type.c_str(),field.c_str());
return -1;
}
}
/**
* Get the byte size of a specific field within a structure type
*
* This function retrieves the byte size of a field within a structure from
* the global type table. The size information is essential for memory
* allocation, buffer management, and ensuring proper data type handling
* when working with kernel data structures.
*
* @param type The name of the structure type containing the field (e.g., "task_struct", "mm_struct")
* @param field The name of the field within the structure (e.g., "pid", "comm", "mm")
* @return The byte size of the field, or -1 if the type information is not found
*
*/
int ParserPlugin::type_size(const std::string& type,const std::string& field){
std::string name = type + "@" + field;
auto it = typetable.find(name);
if (it != typetable.end()) {
return it->second->size();
} else {
LOGE("Error: Typeinfo not found for %s, pls add field_size(%s,%s)\n",name.c_str(),type.c_str(),field.c_str());
return -1;
}
}
/**
* Get the byte size of a structure type
*
* This function retrieves the byte size of a structure type from
* the global type table. The size information is essential for memory
* allocation, buffer management, and ensuring proper data type handling
* when working with kernel data structures.
*
* @param type The name of the structure type (e.g., "task_struct", "mm_struct")
* @return The byte size of the structure, or -1 if the type information is not found
*
*/
int ParserPlugin::type_size(const std::string& type){
std::string name = type;
auto it = typetable.find(name);
if (it != typetable.end()) {
return it->second->size();
} else {
LOGE("Error: Typeinfo not found for %s, pls add field_size(%s)\n",name.c_str(),type.c_str());
return -1;
}
}
/**
* Print a backtrace of the current call stack
*
* This function generates and prints a backtrace showing the current call stack
* using the GNU backtrace functionality. It captures up to MAX_FRAMES stack frames
* and prints each frame's symbol information to the output file pointer.
*
* The backtrace includes function names, addresses, and shared library information
* when available. If backtrace generation fails or no frames are available,
* appropriate error messages are printed.
*
*/
void ParserPlugin::print_backtrace(){
constexpr int MAX_FRAMES = 100;
void *buffer[MAX_FRAMES];
int nptrs = backtrace(buffer, MAX_FRAMES);
if (nptrs <= 0) {
LOGE("No backtrace available\n");
return;
}
char **strings = backtrace_symbols(buffer, nptrs);
if (strings == nullptr) {
LOGE("backtrace_symbols failed\n");
return;
}
for (int i = 0; i < nptrs; i++) {
PRINT("%s\n", strings[i]);
}
std::free(strings);
}
/**
* Print a formatted table of all registered type information
*
* This function outputs a formatted table showing all type information stored in the
* global typetable map. For each type/field combination, it displays the name,
* offset within the structure, and size of the field. The output is formatted in
* columns for easy reading.
*
* The table format is:
* - Column 1: Type name or "type@field" (45 characters, left-justified)
* - Column 2: Offset information (15 characters, left-justified)
* - Column 3: Size information
*
*/
void ParserPlugin::print_table(){
char buf[BUFSIZE];
for (const auto& pair : typetable) {
sprintf(buf, "%s", pair.first.c_str());
PRINT("%s",mkstring(buf, 45, LJUST, buf));
sprintf(buf, ": offset:%d", pair.second.get()->m_offset);
PRINT("%s",mkstring(buf, 15, LJUST, buf));
PRINT(" size:%d\n",pair.second.get()->m_size);
}
}
/**
* Generate a vector of all valid page frame numbers (PFNs) in the system
*
* This function creates a vector containing all page frame numbers from min_low_pfn
* to max_pfn, representing the range of physical memory pages managed by the kernel.
* PFNs are used to identify physical memory pages and are essential for memory
* management operations.
*
* The function uses member variables max_pfn and min_low_pfn that are initialized
* in the constructor from kernel symbols. If these symbols don't exist or have
* zero values, an empty vector is returned.
*
* @return Vector of page frame numbers (PFNs) covering the system's physical memory range
* Returns empty vector if kernel symbols are unavailable or invalid
*
*/
std::vector<ulong> ParserPlugin::for_each_pfn(){
std::vector<ulong> res;
// Early return if symbols don't exist
if (!csymbol_exists("max_pfn") || !csymbol_exists("min_low_pfn")) {
return res;
}
// Use member variables that are already initialized in constructor
if (max_pfn == 0 || min_low_pfn == 0) {
return res;
}
// Reserve capacity to avoid reallocations
size_t pfn_count = max_pfn - min_low_pfn;
res.reserve(pfn_count);
// Use more efficient loop
for (ulong pfn = min_low_pfn; pfn < max_pfn; ++pfn) {
res.push_back(pfn);
}
return res;
}
/**
* Retrieve all page addresses associated with a given address_space mapping
*
* This function traverses the page cache of an address_space structure to collect
* all pages that are currently cached for a particular file or mapping. The pages
* are stored in either an xarray (newer kernels) or radix tree (older kernels)
* data structure within the address_space.
*
* The function handles kernel version compatibility by checking for different
* field names used across kernel versions:
* - Modern kernels: uses i_pages field with xarray structure
* - Older kernels: uses page_tree field with radix tree structure
*
* @param i_mapping The kernel virtual address of the address_space structure
* @return Vector of page addresses found in the mapping's page cache
* Returns empty vector if mapping is invalid or no pages found
*
*/
std::vector<ulong> ParserPlugin::for_each_address_space(ulong i_mapping) {
std::vector<ulong> res;
if (!is_kvaddr(i_mapping)) {
return res;
}
int i_pages_offset = field_offset(address_space, i_pages);
if (i_pages_offset == -1) {
i_pages_offset = field_offset(address_space, page_tree);
if (i_pages_offset == -1) {
return res;
}
}
ulong root = i_mapping + i_pages_offset;
std::string i_pages_type = MEMBER_TYPE_NAME(TO_CONST_STRING("address_space"), TO_CONST_STRING("i_pages"));
return (i_pages_type == "xarray") ? for_each_xarray(root) : for_each_radix(root);
}
/**
* Retrieve all inode addresses from file pages in the system
*
* This function traverses all file pages in the system to extract unique inode
* addresses. It validates each page's mapping and ensures the inode is properly
* associated with an address_space structure before including it in the results.
*
* The function performs the following validation steps for each file page:
* 1. Checks if the page has a valid mapping (address_space)
* 2. Verifies the mapping has valid address_space operations (a_ops)
* 3. Ensures the mapping has a valid host inode
* 4. Confirms the inode's i_mapping field points back to the same mapping
* 5. Uses a set for automatic deduplication of inode addresses
*
* @return Vector of unique inode addresses found in the system's file pages
* Returns empty vector if no valid inodes are found
*
*/
std::vector<ulong> ParserPlugin::for_each_inode(){
std::vector<ulong> res;
std::set<ulong> inode_set;
// Reserve capacity based on estimated file pages
res.reserve(1024);
for (const auto& page : for_each_file_page()) {
ulong mapping = read_pointer(page + field_offset(page,mapping),"mapping");
if (!is_kvaddr(mapping)){
continue;
}
ulong ops = read_pointer(mapping + field_offset(address_space,a_ops),"a_ops");
if (!is_kvaddr(ops)){
continue;
}
ulong inode = read_pointer(mapping + field_offset(address_space,host),"host");
if (!is_kvaddr(inode)){
continue;
}
ulong i_mapping = read_pointer(inode + field_offset(inode,i_mapping),"i_mapping");
if (!is_kvaddr(i_mapping) || mapping != i_mapping){
continue;
}
// Use set for O(log n) insertion and automatic deduplication
if (inode_set.insert(inode).second) {
res.push_back(inode);
}
}
return res;
}
/**
* Retrieve all file-backed pages in the system
*
* This function traverses all page frame numbers (PFNs) in the system to identify
* and collect pages that are backed by files (as opposed to anonymous pages).
* File pages are those associated with files in the filesystem and have valid
* address_space mappings.
*
* The function performs the following validation steps for each page:
* 1. Converts PFN to page structure address and validates it
* 2. Skips buddy (free) pages and pages with zero reference count
* 3. Checks if the page has a valid mapping (address_space)
* 4. Filters out anonymous pages by checking the mapping's LSB (bit 0)
* - If bit 0 is set, it's an anonymous page (skipped)
* - If bit 0 is clear, it's a file page (included)
*
* @return Vector of page addresses for all file-backed pages in the system
* Returns empty vector if no file pages are found
*
*/
std::vector<ulong> ParserPlugin::for_each_file_page(){
std::vector<ulong> res;
res.reserve(4096); // Reserve capacity for better performance
for (const auto& pfn : for_each_pfn()) {
ulong page = pfn_to_page(pfn);
if (!is_kvaddr(page)){
continue;
}
if(page_buddy(page) || page_count(page) == 0){
continue;
}
ulong mapping = read_pointer(page + field_offset(page,mapping),"mapping");
if (!is_kvaddr(mapping)){
continue;
}
if((mapping & 0x1) == 1){ // skip anon page
continue;
}
res.push_back(page);
}
return res;
}
/**
* Retrieve all anonymous pages in the system
*
* This function traverses all page frame numbers (PFNs) in the system to identify
* and collect pages that are anonymous (not backed by files). Anonymous pages
* include stack pages, heap pages, and other memory allocations that don't
* correspond to files in the filesystem.
*
* The function performs the following validation steps for each page:
* 1. Converts PFN to page structure address and validates it
* 2. Skips buddy (free) pages and pages with zero reference count
* 3. Checks if the page has a valid mapping (address_space)
* 4. Filters out file pages by checking the mapping's LSB (bit 0)
* - If bit 0 is clear, it's a file page (skipped)
* - If bit 0 is set, it's an anonymous page (included)
*
* @return Vector of page addresses for all anonymous pages in the system
* Returns empty vector if no anonymous pages are found
*
*/
std::vector<ulong> ParserPlugin::for_each_anon_page(){
std::vector<ulong> res;
res.reserve(4096); // Reserve capacity for better performance
for (const auto& pfn : for_each_pfn()) {
ulong page = pfn_to_page(pfn);
if (!is_kvaddr(page)){
continue;
}
if(page_buddy(page) || page_count(page) == 0){
continue;
}
ulong mapping = read_pointer(page + field_offset(page,mapping),"mapping");
if (!is_kvaddr(mapping)){
continue;
}
if((mapping & 0x1) == 0){ // skip file page
continue;
}
res.push_back(page);
}
return res;
}
/**
* Retrieve all entries from a radix tree data structure
*
* This function traverses a radix tree starting from the given root node and
* collects all valid kernel virtual addresses stored within the tree. Radix trees
* are used extensively in the Linux kernel for efficient storage and retrieval
* of data indexed by integer keys (such as page cache lookups by page index).
*
* The function performs a two-pass operation:
* 1. First pass: Count the total number of entries in the radix tree
* 2. Second pass: Gather all the entries into a temporary buffer
* 3. Filter and return only valid kernel virtual addresses
*
* @param root_rnode The kernel virtual address of the radix tree root node
* @return Vector of kernel virtual addresses found in the radix tree
* Returns empty vector if root is invalid or no entries found
*
*/
std::vector<ulong> ParserPlugin::for_each_radix(ulong root_rnode){
std::vector<ulong> res;
if (!is_kvaddr(root_rnode)) {
return res;
}
size_t entry_num = do_radix_tree(root_rnode, RADIX_TREE_COUNT, NULL);
if (entry_num == 0) {
return res;
}
struct list_pair *entry_list = (struct list_pair *)GETBUF((entry_num + 1) * sizeof(struct list_pair));
entry_list[0].index = entry_num;
do_radix_tree(root_rnode, RADIX_TREE_GATHER, entry_list);
res.reserve(entry_num);
for (size_t i = 0; i < entry_num; ++i){
ulong addr = (ulong)entry_list[i].value;
if (is_kvaddr(addr)) {
res.push_back(addr);
}
}
FREEBUF(entry_list);
return res;
}
/**
* Retrieve all entries from a maple tree data structure
*
* This function traverses a maple tree starting from the given root address and
* collects all valid kernel virtual addresses stored within the tree. Maple trees
* are used in modern Linux kernels (6.1+) as a replacement for red-black trees
* in memory management, particularly for storing VMA (Virtual Memory Area) entries.
*
* The function performs a two-pass operation:
* 1. First pass: Count the total number of entries in the maple tree
* 2. Second pass: Gather all the entries into a temporary buffer
* 3. Filter and return only valid kernel virtual addresses
*
* @param maptree_addr The kernel virtual address of the maple tree root
* @return Vector of kernel virtual addresses found in the maple tree
* Returns empty vector if root is invalid or no entries found
*
*/
std::vector<ulong> ParserPlugin::for_each_mptree(ulong maptree_addr){
std::vector<ulong> res;
if (!is_kvaddr(maptree_addr)) {
return res;
}
size_t entry_num = do_maple_tree(maptree_addr, MAPLE_TREE_COUNT, NULL);
if (entry_num == 0) {
return res;
}
struct list_pair *entry_list = (struct list_pair *)GETBUF(entry_num * sizeof(struct list_pair));
do_maple_tree(maptree_addr, MAPLE_TREE_GATHER, entry_list);
res.reserve(entry_num);
for (size_t i = 0; i < entry_num; ++i){
ulong addr = (ulong)entry_list[i].value;
if (is_kvaddr(addr)) {
res.push_back(addr);
}
}
FREEBUF(entry_list);
return res;
}
/**
* Retrieve all entries from an xarray data structure
*
* This function traverses an xarray starting from the given root address and
* collects all valid kernel virtual addresses stored within the array. Xarrays
* are used in modern Linux kernels as a replacement for radix trees in various
* subsystems, particularly for page cache management and other indexed data storage.
*
* The function performs a two-pass operation:
* 1. First pass: Count the total number of entries in the xarray
* 2. Second pass: Gather all the entries into a temporary buffer
* 3. Filter and return only valid kernel virtual addresses
*
* @param xarray_addr The kernel virtual address of the xarray root
* @return Vector of kernel virtual addresses found in the xarray
* Returns empty vector if root is invalid or no entries found
*
*/
std::vector<ulong> ParserPlugin::for_each_xarray(ulong xarray_addr){
std::vector<ulong> res;
if (!is_kvaddr(xarray_addr)) {
return res;
}
size_t entry_num = do_xarray(xarray_addr, XARRAY_COUNT, NULL);
if (entry_num == 0) {
return res;
}
struct list_pair *entry_list = (struct list_pair *)GETBUF(entry_num * sizeof(struct list_pair));
do_xarray(xarray_addr, XARRAY_GATHER, entry_list);
res.reserve(entry_num);
for (size_t i = 0; i < entry_num; ++i) {
ulong addr = (ulong)entry_list[i].value;
if (is_kvaddr(addr)) {
res.push_back(addr);
}
}
FREEBUF(entry_list);
return res;
}
/**
* Retrieve all entries from a red-black tree data structure
*
* This function traverses a red-black tree starting from the given root node and
* collects all valid kernel virtual addresses stored within the tree. Red-black trees
* are used extensively in the Linux kernel for efficient storage and retrieval
* of data with guaranteed O(log n) operations, such as in memory management,
* process scheduling, and file system operations.
*
* The function performs a two-pass operation:
* 1. First pass: Count the total number of entries in the red-black tree