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
pub(crate) mod perf_map_poller;

use std::convert::TryInto;
use std::iter::FusedIterator;
use std::os::raw::{c_long, c_uchar, c_uint, c_ulong, c_ushort};
use std::os::unix::io::RawFd;
use std::ptr::null_mut;
use std::slice;
use std::sync::atomic;
use std::sync::atomic::{AtomicPtr, Ordering};

use nix::errno::errno;

use crate::bpf::constant::bpf_map_type;
use crate::bpf::constant::bpf_map_type::BPF_MAP_TYPE_PROG_ARRAY;
use crate::bpf::syscall::{bpf_map_create, bpf_map_lookup_elem, bpf_map_update_elem};
use crate::bpf::MapConfig;
use crate::error::OxidebpfError;
use crate::perf::constant::perf_event_type;
use crate::perf::syscall::{perf_event_ioc_disable, perf_event_ioc_enable};
use crate::perf::PerfEventAttr;
use slog::info;
use std::fmt::{Debug, Display, Formatter};

use crate::LOGGER;

#[repr(C)]
#[derive(Clone, Copy)]
struct PerfEventHeader {
    type_: c_uint,
    misc: c_ushort,
    size: c_ushort,
}
#[repr(C)]
pub struct PerfEventLostSamples {
    header: PerfEventHeader,
    pub id: u64,
    pub count: u64,
}

#[repr(C)]
pub struct PerfEventSample {
    header: PerfEventHeader,
    pub size: u32,
    pub data: Vec<u8>,
}

pub(crate) fn process_cpu_string(cpu_string: String) -> Result<Vec<i32>, OxidebpfError> {
    let mut cpus = vec![];

    for sublist in cpu_string.trim().split(',') {
        if sublist.contains('-') {
            let pair: Vec<&str> = sublist.split('-').collect();
            if pair.len() != 2 {
                info!(
                    LOGGER.0,
                    "process_cpu_string(); cpu online formatting error: {}", cpu_string
                );
                return Err(OxidebpfError::CpuOnlineFormatError);
            }

            // we checked the length above so indexing is OK
            let from: i32 = pair[0].parse().map_err(|e| {
                info!(
                    LOGGER.0,
                    "process_cpu_string(); cpu online i32 parse error; pair: {:?}; error: {:?}",
                    pair,
                    e
                );
                OxidebpfError::CpuOnlineFormatError
            })?;
            let to: i32 = pair[1].parse().map_err(|e| {
                info!(
                    LOGGER.0,
                    "process_cpu_string(); cpu online i32 parse error; pair: {:?}; error: {:?}",
                    pair,
                    e
                );
                OxidebpfError::CpuOnlineFormatError
            })?;

            cpus.extend(from..=to)
        } else {
            cpus.push(sublist.trim().parse().map_err(|e| {
                info!(
                    LOGGER.0,
                    "process_cpu_string(); sublist number parsing error; sublist: {:?}; error: {:?}", sublist, e
                );
                OxidebpfError::NumberParserError
            })?);
        }
    }

    Ok(cpus)
}

pub(crate) fn get_cpus() -> Result<Vec<i32>, OxidebpfError> {
    let cpu_string = String::from_utf8(std::fs::read("/sys/devices/system/cpu/online").map_err(
        |e| {
            info!(
                LOGGER.0,
                "get_cpus(); could not read /sys/devices/system/cpu/online; error: {:?}", e
            );
            OxidebpfError::FileIOError
        },
    )?)
    .map_err(|e| {
        info!(
            LOGGER.0,
            "get_cpus(); utf8 string conversion error while getting cpus; error: {:?}", e
        );
        OxidebpfError::Utf8StringConversionError
    })?;
    process_cpu_string(cpu_string)
}

pub(crate) enum PerfEvent {
    Sample(PerfEventSample),
    Lost(u64),
}

impl Debug for PerfEvent {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                PerfEvent::Sample(s) => {
                    format!("SAMPLE: {}", s.size)
                }
                PerfEvent::Lost(l) => {
                    format!("LOST: {}", l)
                }
            }
        )
    }
}

#[repr(align(8), C)]
#[derive(Clone, Copy)]
struct PerfMemBitfield {
    field: c_ulong,
}

#[repr(align(8), C)]
union PerfMemCapabilitiesBitfield {
    capabilities: c_ulong,
    bitfield: PerfMemBitfield,
}

impl Debug for PerfMemCapabilitiesBitfield {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "debug not implemented")
    }
}

#[repr(C)]
#[derive(Debug)]
struct PerfMem {
    version: c_uint,
    compat_version: c_uint,
    lock: c_uint,
    index: c_uint,
    offset: c_long,
    time_enabled: c_ulong,
    time_running: c_ulong,
    capabilities: PerfMemCapabilitiesBitfield,
    pmc_width: c_ushort,
    time_shift: c_ushort,
    time_mult: c_uint,
    time_offset: c_ulong,
    time_zero: c_ulong,
    size: c_uint,
    reserved_1: c_uint,
    time_cycles: c_ulong,
    time_mask: c_ulong,
    __reserved: [c_uchar; 928usize],
    data_head: c_ulong,
    data_tail: c_ulong,
    data_offset: c_ulong,
    data_size: c_ulong,
    aux_head: c_ulong,
    aux_tail: c_ulong,
    aux_offset: c_ulong,
    aux_size: c_ulong,
}

pub struct PerfMap {
    pub(crate) name: String,
    base_ptr: AtomicPtr<PerfMem>,
    page_count: usize,
    page_size: usize,
    mmap_size: usize,
    cpuid: i32,
    pub(crate) ev_fd: RawFd,
    ev_name: String,
}

#[derive(Clone, Debug)]
pub(crate) struct ProgMap {
    pub base: Map,
}

#[derive(Clone, Debug)]
pub struct ArrayMap {
    pub base: Map,
}

#[derive(Clone, Debug)]
pub struct BpfHashMap {
    pub base: Map,
}

#[derive(Debug)]
pub struct Map {
    pub name: String,       // The name of the map
    fd: RawFd,              // The file descriptor that represents the map
    map_config: MapConfig,  // The first struct in the bpf_attr union
    map_config_size: usize, // The size of the map_config field in bytes
    loaded: bool,           // Whether or not the map has been loaded
}

impl Clone for Map {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            fd: unsafe { libc::fcntl(self.fd, libc::F_DUPFD_CLOEXEC, 3) },
            map_config: self.map_config,
            map_config_size: self.map_config_size,
            loaded: self.loaded,
        }
    }
}

impl Drop for Map {
    fn drop(&mut self) {
        unsafe {
            libc::close(self.fd);
        }
    }
}

/// This trait specifies a map that can be read from or written to (e.g., array types).
pub trait RWMap<T, U> {
    /// # Safety
    ///
    /// This function should only be called when `std::mem::size_of::<T>()` matches
    /// the value in the map being read from and when `std::mem::size_of::<U>()`
    /// matches the key.
    unsafe fn read(&self, key: U) -> Result<T, OxidebpfError>;

    /// # Safety
    ///
    /// This function should only be called when `std::mem::size_of::<T>()` matches
    /// the value in the map being written to and when `std::mem::size_of::<U>()`
    /// matches the key.
    unsafe fn write(&self, key: U, value: T) -> Result<(), OxidebpfError>;
}

pub trait PerCpu {
    fn cpuid(&self) -> i32;
}

impl ProgMap {
    pub(crate) fn new(map_name: &str, max_entries: u32) -> Result<Self, OxidebpfError> {
        let fd = bpf_map_create(BPF_MAP_TYPE_PROG_ARRAY, 4u32, 4u32, max_entries)?;
        let map = Map {
            name: map_name.to_string(),
            fd,
            map_config: MapConfig::new(bpf_map_type::BPF_MAP_TYPE_PROG_ARRAY, 4, 4, max_entries),
            map_config_size: std::mem::size_of::<MapConfig>(),
            loaded: true,
        };
        Ok(ProgMap { base: map })
    }

    // TODO: these functions are a good candidate for a trait
    pub(crate) fn set_fd(&mut self, fd: RawFd) {
        self.base.fd = fd;
    }

    pub(crate) fn get_fd(&self) -> &RawFd {
        &self.base.fd
    }

    pub(crate) fn is_loaded(&self) -> bool {
        self.base.loaded
    }
}

impl PerfMap {
    // we want cpuid and give back a channel to read from
    pub fn new_group(
        map_name: &str,
        event_attr: PerfEventAttr,
        event_buffer_size: usize,
    ) -> Result<Vec<PerfMap>, OxidebpfError> {
        let page_size = match unsafe { libc::sysconf(libc::_SC_PAGE_SIZE) } {
            size if size < 0 => {
                let e = errno();
                info!(
                    LOGGER.0,
                    "PerfMap::new_group(); perfmap error, size < 0: {}; errno: {}", size, e
                );
                return Err(OxidebpfError::LinuxError(
                    "perf map get PAGE_SIZE".to_string(),
                    nix::errno::from_i32(e),
                ));
            }
            size if size == 0 => {
                info!(
                    LOGGER.0,
                    "PerfMap::new_group(); perfmap error, bad page size (size == 0)"
                );
                return Err(OxidebpfError::BadPageSize);
            }
            size if size > 0 => size as usize,
            size => {
                info!(
                    LOGGER.0,
                    "PerfMap::new_group(); perfmap error, impossible page size: {}", size
                );
                return Err(OxidebpfError::BadPageSize);
            }
        };
        let page_count = (event_buffer_size as f64 / page_size as f64).ceil() as usize;
        if page_count == 0 {
            info!(LOGGER.0, "PerfMap::new_group(); bad page count (0)");
            return Err(OxidebpfError::BadPageCount);
        }

        let page_count = lte_power_of_two(page_count);
        let mmap_size = page_size * (page_count + 1);

        let mut loaded_perfmaps = Vec::<PerfMap>::new();
        for cpuid in get_cpus()?.iter() {
            let fd: RawFd = crate::perf::syscall::perf_event_open(&event_attr, -1, *cpuid, -1, 0)?;
            let base_ptr: *mut _;
            base_ptr = unsafe {
                libc::mmap(
                    null_mut(),
                    mmap_size,
                    libc::PROT_READ | libc::PROT_WRITE,
                    libc::MAP_SHARED,
                    fd,
                    0,
                )
            };
            if base_ptr == libc::MAP_FAILED {
                let mmap_errno = nix::errno::from_i32(errno());
                unsafe {
                    if libc::close(fd) < 0 {
                        let e = errno();
                        info!(
                            LOGGER.0,
                            "PerfMap::new_group(); could not close mmap fd, multiple errors; mmap_errno: {}; errno: {}",
                            mmap_errno,
                            e
                        );
                        return Err(OxidebpfError::MultipleErrors(vec![
                            OxidebpfError::LinuxError(
                                format!("perf_map => mmap(fd={},size={})", fd, mmap_size),
                                mmap_errno,
                            ),
                            OxidebpfError::LinuxError(
                                format!("perf_map cleanup => close({})", fd),
                                nix::errno::from_i32(e),
                            ),
                        ]));
                    }
                };
                info!(
                    LOGGER.0,
                    "PerfMap::new_group(); mmap failed while creating perfmap: {:?}", mmap_errno
                );
                return Err(OxidebpfError::LinuxError(
                    format!("per_event_open => mmap(fd={},size={})", fd, mmap_size),
                    mmap_errno,
                ));
            }
            perf_event_ioc_enable(fd)?;
            loaded_perfmaps.push(PerfMap {
                name: map_name.to_string(),
                base_ptr: AtomicPtr::new(base_ptr as *mut PerfMem),
                page_count,
                page_size,
                mmap_size,
                cpuid: *cpuid,
                ev_fd: fd,
                ev_name: "".to_string(),
            });
        }
        Ok(loaded_perfmaps)
    }

    pub(crate) fn read(&self) -> Result<Option<PerfEvent>, OxidebpfError> {
        let header = self.base_ptr.load(Ordering::SeqCst);
        let raw_size = (self.page_count * self.page_size) as u64;
        let base: *const u8;
        let data_head: u64;
        let data_tail: u64;
        let event: *const PerfEventHeader;
        let start: usize;
        let end: usize;
        unsafe {
            base = (header as *const u8).add(self.page_size);
            data_head = (*header).data_head;
            data_tail = (*header).data_tail;
            start = (data_tail % raw_size) as usize;
            event = base.add(start) as *const PerfEventHeader;
            end = ((data_tail + (*event).size as u64) % raw_size) as usize;
        }
        if data_head == data_tail {
            // common and nonfatal - do not log
            return Err(OxidebpfError::NoPerfData);
        }

        let mut buf = Vec::<u8>::new();

        unsafe {
            if end < start {
                let len = raw_size as usize - start;
                let ptr = base.add(start);
                buf.extend_from_slice(slice::from_raw_parts(ptr, len));

                let len = (*event).size as usize - len;
                let ptr = base;
                buf.extend_from_slice(slice::from_raw_parts(ptr, len));
            } else {
                let ptr = base.add(start);
                let len = (*event).size as usize;
                buf.extend_from_slice(slice::from_raw_parts(ptr, len));
            }

            atomic::fence(Ordering::SeqCst);
            (*header).data_tail += (*event).size as u64;

            match (*event).type_ {
                perf_event_type::PERF_RECORD_SAMPLE => {
                    use std::mem::size_of;

                    let header = {
                        let header_bytes: [u8; size_of::<PerfEventHeader>()] = buf
                            [..size_of::<PerfEventHeader>()]
                            .try_into()
                            .map_err(|_| OxidebpfError::BadPerfSample)?; // infallible, do not log
                        std::ptr::read(header_bytes.as_ptr() as *const _)
                    };

                    let size = {
                        let size_bytes: [u8; size_of::<u32>()] = buf[size_of::<PerfEventHeader>()
                            ..(size_of::<u32>() + size_of::<PerfEventHeader>())]
                            .try_into()
                            .map_err(|_| OxidebpfError::BadPerfSample)?; // infallible, do not log
                        u32::from_ne_bytes(size_bytes)
                    };

                    let data = {
                        // drain the header + len fields; the rest is the data
                        buf.drain(
                            ..(std::mem::size_of::<PerfEventHeader>() + std::mem::size_of::<u32>()),
                        )
                        // might be unnecesary but I like this being explicit
                        .for_each(|_| {});

                        buf
                    };

                    let sample = PerfEventSample { header, size, data };
                    Ok(Some(PerfEvent::Sample(sample)))
                }
                perf_event_type::PERF_RECORD_LOST => {
                    let lost = &*(buf.as_ptr() as *const PerfEventLostSamples);
                    Ok(Some(PerfEvent::Lost(lost.count)))
                }
                _ => Ok(None),
            }
        }
    }

    /// Reads all available events
    ///
    /// Stops reading either on a real error (and propagates it) or on
    /// a OxidebpfError::NoPerfData and returns `None`.
    pub(crate) fn read_all(&self) -> impl Iterator<Item = Result<PerfEvent, OxidebpfError>> + '_ {
        PerfEventIterator {
            map: self,
            is_done: false,
        }
    }
}

struct PerfEventIterator<'a> {
    map: &'a PerfMap,
    is_done: bool,
}

impl<'a> Iterator for PerfEventIterator<'a> {
    type Item = Result<PerfEvent, OxidebpfError>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.is_done {
            return None;
        }

        match self.map.read() {
            Ok(Some(event)) => Some(Ok(event)),
            Ok(None) => self.next(),
            Err(OxidebpfError::NoPerfData) => {
                // we're done reading
                self.is_done = true;
                None
            }
            Err(e) => {
                self.is_done = true;
                Some(Err(e))
            }
        }
    }
}

// after the first `None` we always return `None`
impl<'a> FusedIterator for PerfEventIterator<'a> {}

impl PerCpu for PerfMap {
    fn cpuid(&self) -> i32 {
        self.cpuid
    }
}

impl BpfHashMap {
    /// Create a new BpfHashMap
    ///
    /// Calling new will create a new BPF_MAP_TYPE_HASH map. It stores some meta data
    /// to track it. The array map supports read and write operations to access the
    /// members of the map
    ///
    /// # Safety
    ///
    /// The `value_size` and `key_size` you pass in needs to match exactly with the size of the struct/type
    /// used by any other BPF program that might be using this map. Any `T` or `U` you use in subsequent
    /// `read()` and `write()` calls needs to match exactly (e.g., with `#[repr(C)]`) with the struct/type
    /// used by the BPF program as well. Additionally, `std::mem::size_of::<T>()` must match the given
    /// `value_size` here exactly and `std::mem::size_of::<U>() for the key`. If this conditions are not met,
    /// the `BpfHashMap` behavior is undefined.
    ///
    /// # Examples
    /// ```
    /// use oxidebpf::BpfHashMap;
    /// let map: BpfHashMap = unsafe {BpfHashMap::new(
    ///    "mymap",
    ///    std::mem::size_of::<u64>() as u32,
    ///    std::mem::size_of::<u64>() as u32,
    ///    1024,
    /// ).expect("Failed to create map") };
    /// ```
    pub unsafe fn new(
        map_name: &str,
        key_size: u32,
        value_size: u32,
        max_entries: u32,
    ) -> Result<BpfHashMap, OxidebpfError> {
        // Manpages say that key size must be 4 bytes for BPF_MAP_TYPE_ARRAY
        let fd = bpf_map_create(
            bpf_map_type::BPF_MAP_TYPE_HASH,
            key_size as c_uint,
            value_size as c_uint,
            max_entries,
        )?;
        let map = Map {
            name: map_name.to_string(),
            fd,
            map_config: MapConfig::new(
                bpf_map_type::BPF_MAP_TYPE_HASH,
                key_size,
                value_size,
                max_entries,
            ),
            map_config_size: std::mem::size_of::<MapConfig>(),
            loaded: true,
        };
        Ok(BpfHashMap { base: map })
    }

    pub(crate) fn set_fd(&mut self, fd: RawFd) {
        self.base.fd = fd;
    }

    pub(crate) fn get_fd(&self) -> &RawFd {
        &self.base.fd
    }

    pub(crate) fn is_loaded(&self) -> bool {
        self.base.loaded
    }
}

impl Display for BpfHashMap {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "Name: {}, loaded: {}", self.base.name, self.base.loaded)
    }
}

impl ArrayMap {
    /// Create a new ArrayMap
    ///
    /// Calling new will create a new BPF_MAP_TYPE_ARRAY map. It stores some meta data
    /// to track it. The array map supports read and write operations to access the
    /// members of the map
    ///
    /// # Safety
    ///
    /// The `value_size` you pass in needs to match exactly with the size of the struct/type
    /// used by any other BPF program that might be using this map. Any `T` you use in subsequent
    /// `read()` and `write()` calls needs to match exactly (e.g., with `#[repr(C)]`) with
    /// the struct/type used by the BPF program as well. Additionally, `std::mem::size_of::<T>()`
    /// must match the given `value_size` here exactly. If this conditions are not met, the
    /// `ArrayMap` behavior is undefined.
    ///
    /// # Examples
    /// ```
    /// use oxidebpf::ArrayMap;
    /// let map: ArrayMap = unsafe {ArrayMap::new(
    ///    "mymap",
    ///    std::mem::size_of::<u64>() as u32,
    ///    1024,
    /// ).expect("Failed to create map") };
    /// ```
    pub unsafe fn new(
        map_name: &str,
        value_size: u32,
        max_entries: u32,
    ) -> Result<ArrayMap, OxidebpfError> {
        // Manpages say that key size must be 4 bytes for BPF_MAP_TYPE_ARRAY
        let fd = bpf_map_create(
            bpf_map_type::BPF_MAP_TYPE_ARRAY,
            4,
            value_size as c_uint,
            max_entries,
        )?;
        let map = Map {
            name: map_name.to_string(),
            fd,
            map_config: MapConfig::new(
                bpf_map_type::BPF_MAP_TYPE_ARRAY,
                4,
                value_size,
                max_entries,
            ),
            map_config_size: std::mem::size_of::<MapConfig>(),
            loaded: true,
        };
        Ok(ArrayMap { base: map })
    }

    pub(crate) fn set_fd(&mut self, fd: RawFd) {
        self.base.fd = fd;
    }

    pub(crate) fn get_fd(&self) -> &RawFd {
        &self.base.fd
    }

    pub(crate) fn is_loaded(&self) -> bool {
        self.base.loaded
    }
}

impl Display for ArrayMap {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        write!(f, "Name: {}, loaded: {}", self.base.name, self.base.loaded)
    }
}

impl<T> RWMap<T, c_uint> for ArrayMap {
    /// Reads an index from a map of type BPF_MAP_TYPE_ARRAY
    ///
    /// Initiates a read from `key`. Read verifies that the map has been initialized.
    /// The value returned will be of the same type that was used when the ArrayMap
    /// was created
    ///
    /// NOTE: This method calls will read a certain amount of memory based on what the
    /// size of `T` is. Make sure that `T` matches the type of the value (e.g., with `#[repr(C)]`)
    /// that is being used in the map.
    ///
    /// # Example
    /// ```
    /// use oxidebpf::{ArrayMap, RWMap};
    ///
    /// // this is safe because we are reading and writing a u64, and the value_size we
    /// // pass into new() is a u64
    ///
    /// unsafe {
    ///     let map: ArrayMap = ArrayMap::new(
    ///        "mymap",
    ///        std::mem::size_of::<u64>() as u32,
    ///        1024,
    ///     ).expect("Failed to create map");
    ///     let _ = map.write(0, 12345u64);
    ///     assert_eq!(
    ///         12345u64,
    ///         unsafe { map.read(0).expect("Failed to read value from map") }
    ///     );
    /// }
    /// ```
    unsafe fn read(&self, key: c_uint) -> Result<T, OxidebpfError> {
        if !self.base.loaded {
            info!(
                LOGGER.0,
                "ArrayMap::read(); attempted to read unloaded array map {}", self.base.name
            );
            return Err(OxidebpfError::MapNotLoaded);
        }
        if self.base.fd < 0 {
            info!(
                LOGGER.0,
                "ArrayMap::read(); attempted to read array map with negative fd {}", self.base.name
            );
            return Err(OxidebpfError::MapNotLoaded);
        }
        if std::mem::size_of::<T>() as u32 != self.base.map_config.value_size {
            info!(
                LOGGER.0,
                "ArrayMap::read(); attempted to read array map with incorrect size; gave {}; should be {}",
                std::mem::size_of::<T>(),
                self.base.map_config.value_size
            );
            return Err(OxidebpfError::MapValueSizeMismatch);
        }
        bpf_map_lookup_elem(self.base.fd, key)
    }

    /// Writes an index to and index of a map of type BPF_MAP_TYPE_ARRAY
    ///
    /// Initiates a write to `key` of `value`. The value needs to match the array
    /// type that was used when the map was created
    ///
    /// NOTE: This method calls will write a certain amount of memory based on what the
    /// size of `T` is. Make sure that `T` matches the type of the value (e.g., with `#[repr(C)]`)
    /// that is being used in the map.
    ///
    /// # Example
    /// ```
    /// use oxidebpf::{ArrayMap, RWMap};
    ///
    /// // this is safe because we are reading and writing a u64, and the value_size we
    /// // pass into new() is a u64
    ///
    /// unsafe {
    ///     let map: ArrayMap = ArrayMap::new(
    ///        "mymap",
    ///        std::mem::size_of::<u64>() as u32,
    ///        1024,
    ///     ).expect("Failed to create map");
    ///     let _ = map.write(0, 12345u64);
    ///     assert_eq!(
    ///         12345u64,
    ///         map.read(0).expect("Failed to read value from map")
    ///     );
    /// }
    /// ```
    unsafe fn write(&self, key: c_uint, value: T) -> Result<(), OxidebpfError> {
        if !self.base.loaded {
            info!(
                LOGGER.0,
                "ArrayMap::write(); attempted to write unloaded array map {}", self.base.name
            );
            return Err(OxidebpfError::MapNotLoaded);
        }
        if self.base.fd < 0 {
            info!(
                LOGGER.0,
                "ArrayMap::write(); attempted to write array map with negative fd {}",
                self.base.name
            );
            return Err(OxidebpfError::MapNotLoaded);
        }

        // Try and verify that size of the value type matches the size of the value field in the map
        if std::mem::size_of::<T>() as u32 != self.base.map_config.value_size {
            return Err(OxidebpfError::MapValueSizeMismatch);
        }
        bpf_map_update_elem(self.base.fd, key, value)
    }
}

impl<T, U> RWMap<T, U> for BpfHashMap {
    /// Reads an index from a map of type BPF_MAP_TYPE_HASH
    ///
    /// Initiates a read from `key`. Read verifies that the map has been initialized.
    /// The value returned will be of the same type that was used when the BpfHashMap
    /// was created
    ///
    /// NOTE: This method calls will read a certain amount of memory based on what the
    /// size of `T` and `U` is. Make sure that `T` and `U` matches the type of the value and key
    /// (e.g., with `#[repr(C)]`) that is being used in the map.
    ///
    /// # Example
    /// ```
    /// use oxidebpf::{BpfHashMap, RWMap};
    ///
    /// // this is safe because we are reading and writing a u64, and the value_size we
    /// // pass into new() is a u64
    ///
    /// unsafe {
    ///     let map: BpfHashMap = BpfHashMap::new(
    ///        "mymap",
    ///        std::mem::size_of::<u64>() as u32,
    ///        std::mem::size_of::<u64>() as u32,
    ///        1024,
    ///     ).expect("Failed to create map");
    ///     let _ = map.write(87654321u64, 12345u64);
    ///     assert_eq!(
    ///         12345u64,
    ///         unsafe { map.read(87654321u64).expect("Failed to read value from map") }
    ///     );
    /// }
    /// ```
    unsafe fn read(&self, key: U) -> Result<T, OxidebpfError> {
        if !self.base.loaded {
            info!(
                LOGGER.0,
                "BpfHashMap::read(); attempted to read unloaded bpf hash map {}", self.base.name
            );
            return Err(OxidebpfError::MapNotLoaded);
        }
        if self.base.fd < 0 {
            info!(
                LOGGER.0,
                "BpfHashMap::read(); attempted to read bpf hash map with negative fd {}",
                self.base.name
            );
            return Err(OxidebpfError::MapNotLoaded);
        }
        if std::mem::size_of::<T>() as u32 != self.base.map_config.value_size {
            info!(
                LOGGER.0,
                "BpfHashMap::read(); attempted to read bpf hash map with incorrect value size; gave {}; should be {}",
                std::mem::size_of::<T>(),
                self.base.map_config.value_size
            );
            return Err(OxidebpfError::MapValueSizeMismatch);
        }
        if std::mem::size_of::<U>() as u32 != self.base.map_config.key_size {
            info!(
                LOGGER.0,
                "BpfHashMap::read(); attempted to read bpf hash map with incorrect key size; gave {}; should be {}",
                std::mem::size_of::<U>(),
                self.base.map_config.key_size
            );
            return Err(OxidebpfError::MapKeySizeMismatch);
        }
        bpf_map_lookup_elem(self.base.fd, key)
    }

    /// Writes an index to and index of a map of type BPF_MAP_TYPE_ARRAY
    ///
    /// Initiates a write to `key` of `value`. The value needs to match the array
    /// type that was used when the map was created
    ///
    /// NOTE: This method calls will write a certain amount of memory based on what the
    /// size of `T` is. Make sure that `T` matches the type of the value (e.g., with `#[repr(C)]`)
    /// that is being used in the map.
    ///
    /// # Example
    /// ```
    /// use oxidebpf::{BpfHashMap, RWMap};
    /// use std::process;
    ///
    /// // this is safe because we are reading and writing a u64, and the value_size we
    /// // pass into new() is a u64
    ///
    /// unsafe {
    ///     let map: BpfHashMap = BpfHashMap::new(
    ///        "mymap",
    ///        std::mem::size_of::<u32>() as u32,
    ///        std::mem::size_of::<u64>() as u32,
    ///        1024,
    ///     ).expect("Failed to create map");
    ///     let _ = map.write(process::id(), 12345u64);
    ///     assert_eq!(
    ///         12345u64,
    ///         map.read(process::id()).expect("Failed to read value from map")
    ///     );
    /// }
    /// ```
    unsafe fn write(&self, key: U, value: T) -> Result<(), OxidebpfError> {
        if !self.base.loaded {
            info!(
                LOGGER.0,
                "BpfHashMap::write(); attempted to write unloaded bpf hash map {}", self.base.name
            );
            return Err(OxidebpfError::MapNotLoaded);
        }
        if self.base.fd < 0 {
            info!(
                LOGGER.0,
                "BpfHashMap::write(); attempted to write bpf hash map with negative fd {}",
                self.base.name
            );
            return Err(OxidebpfError::MapNotLoaded);
        }

        // Try and verify that size of the value type matches the size of the value field in the map
        if std::mem::size_of::<T>() as u32 != self.base.map_config.value_size {
            info!(
                LOGGER.0,
                "BpfHashMap::write(); attempted to write bpf hash map with incorrect value size; gave {}; should be {}",
                std::mem::size_of::<T>(),
                self.base.map_config.value_size
            );
            return Err(OxidebpfError::MapValueSizeMismatch);
        }
        if std::mem::size_of::<U>() as u32 != self.base.map_config.key_size {
            info!(
                LOGGER.0,
                "BpfHashMap::write(); attempted to write bpf hash map with incorrect key size; gave {}; should be {}",
                std::mem::size_of::<U>(),
                self.base.map_config.key_size
            );
            return Err(OxidebpfError::MapKeySizeMismatch);
        }
        bpf_map_update_elem(self.base.fd, key, value)
    }
}

impl Drop for PerfMap {
    fn drop(&mut self) {
        // if it doesn't work, we're gonna close it anyway so :shrug:
        #![allow(unused_must_use)]
        perf_event_ioc_disable(self.ev_fd);
        unsafe {
            libc::close(self.ev_fd);
        }
    }
}

impl Drop for ArrayMap {
    fn drop(&mut self) {
        self.base.loaded = false;
    }
}

// returns a power of two that is equal or less than n
fn lte_power_of_two(n: usize) -> usize {
    if n.is_power_of_two() {
        return n;
    }

    match n.checked_next_power_of_two() {
        None => 1 << (usize::BITS - 1),
        Some(x) => x >> 1,
    }
}

#[cfg(test)]
mod map_tests {
    use crate::error::OxidebpfError;
    use crate::maps::process_cpu_string;
    use crate::maps::RWMap;
    use crate::maps::{ArrayMap, BpfHashMap};
    use nix::errno::Errno;

    // Doing the rough equivalent of C's time(NULL);
    fn time_null() -> u64 {
        let start = std::time::SystemTime::now();
        let seed_time = start
            .duration_since(std::time::UNIX_EPOCH)
            .expect("All time is broken!!");
        seed_time.as_millis() as u64
    }

    #[test]
    fn test_cpu_formatter() {
        assert_eq!(vec![0], process_cpu_string("0".to_string()).unwrap());
        assert_eq!(
            vec![0, 1, 2],
            process_cpu_string("0-2".to_string()).unwrap()
        );
        assert_eq!(
            vec![0, 3, 4, 5, 8],
            process_cpu_string("0,3-5,8".to_string()).unwrap()
        );
    }

    // Test the normal behavior of the array map type
    //
    // This test simply writes to all the entries in the map and then tries to read
    // them back. If it successfully reads the values back from the map then it
    // is considered passing
    #[test]
    fn test_map_array() {
        let array_size: u64 = 100;
        let map: ArrayMap = unsafe {
            ArrayMap::new(
                "mymap",
                std::mem::size_of::<u64>() as u32,
                array_size as u32,
            )
            .expect("Failed to create new map")
        };

        // Give it some "randomness"
        let nums: Vec<u64> = (0..array_size)
            .map(|v| (v * time_null() + 71) % 128)
            .collect();

        // Write
        for (idx, num) in nums.iter().enumerate() {
            unsafe { map.write(idx as u32, *num).expect("could not write to map") };
        }
        for (idx, num) in nums.iter().enumerate() {
            assert_eq!(*num, unsafe {
                map.read(idx as u32).expect("Failed to read value from map")
            });
        }

        // Updates the entries and retrieves them again
        let nums: Vec<u64> = nums.iter().map(|v| (v * time_null() + 71) % 128).collect();
        for (idx, num) in nums.iter().enumerate() {
            unsafe { map.write(idx as u32, *num).expect("could not write to map") };
        }
        for (idx, num) in nums.iter().enumerate() {
            assert_eq!(*num, unsafe {
                map.read(idx as u32).expect("Failed to read value from map")
            });
        }
    }

    // Tests a trying to read an element from outside the bounds of the array
    #[test]
    fn test_map_array_bad_index() {
        let array_size: u64 = 10;
        let map: ArrayMap = unsafe {
            ArrayMap::new(
                "mymap",
                std::mem::size_of::<u64>() as u32,
                array_size as u32,
            )
            .expect("Failed to create new map")
        };

        // Give it some "randomness"
        let nums: Vec<u64> = (0..array_size)
            .map(|v| (v * time_null() + 71) % 128)
            .collect();

        for (idx, num) in nums.iter().enumerate() {
            unsafe { map.write(idx as u32, *num).expect("could not write to map") };
        }
        let should_fail: Result<u64, OxidebpfError> = unsafe { map.read(100) };
        assert!(should_fail.is_err());
        match should_fail {
            Err(OxidebpfError::LinuxError(_, errno)) => {
                assert_eq!(errno, Errno::ENOENT)
            }
            _ => {
                panic!("invalid OxidebpfError: {:?}", should_fail);
            }
        }
    }

    // Test writing outside the size of the array
    #[test]
    fn test_map_array_bad_write_index() {
        let array_size: u64 = 10;
        let map: ArrayMap = unsafe {
            ArrayMap::new(
                "mymap",
                std::mem::size_of::<u64>() as u32,
                array_size as u32,
            )
            .expect("Failed to create new map")
        };

        // Give it some "randomness"
        let nums: Vec<u64> = (0..array_size)
            .map(|v| (v * time_null() + 71) % 128)
            .collect();

        for (idx, num) in nums.iter().enumerate() {
            unsafe { map.write(idx as u32, *num).expect("could not write to map") };
        }

        // Should return E2BIG
        let should_fail = unsafe { map.write(100, 12345u64).err().unwrap() };
        match should_fail {
            OxidebpfError::LinuxError(_, errno) => {
                assert_eq!(errno, Errno::E2BIG)
            }
            _ => {
                panic!("invalid OxidebpfError: {:?}", should_fail);
            }
        }
    }

    // Test storing a more complex structure
    #[test]
    fn test_map_array_complex_structure() {
        // A made up structure for this test
        struct TestStructure {
            durp0: u64,
            durp1: String,
            durp2: f64,
            durp3: bool,
        }

        // Create the map and initialize a vector of TestStructure
        let array_size: u64 = 10;
        let map: ArrayMap = unsafe {
            ArrayMap::new(
                "mymap",
                std::mem::size_of::<u64>() as u32,
                array_size as u32,
            )
            .expect("Failed to create new map")
        };

        let data: Vec<TestStructure> = (0..array_size)
            .map(|v| TestStructure {
                durp0: v,
                durp1: format!("Durp {}", v),
                durp2: 0.1234,
                durp3: v % 2 == 0,
            })
            .collect();

        // Write the test structures to the map
        for (i, tmp) in data.iter().enumerate() {
            unsafe { map.write(i as u32, tmp).expect("could not write to map") };
        }

        // Read the test structures from the map and compare with originals
        for (i, item) in data.iter().enumerate() {
            let val: &TestStructure =
                unsafe { map.read(i as u32).expect("Failed to read value from array") };
            assert_eq!(val.durp0, item.durp0);
            assert_eq!(val.durp1, item.durp1);
            assert_eq!(val.durp2, item.durp2);
            assert_eq!(val.durp3, item.durp3);
        }
    }

    #[test]
    fn test_hash_map() {
        let array_size: u64 = 100;

        let map: BpfHashMap = unsafe {
            BpfHashMap::new(
                "mymap",
                std::mem::size_of::<u32>() as u32,
                std::mem::size_of::<u64>() as u32,
                1024,
            )
            .expect("Failed to create new map")
        };
        // Give it some "randomness"
        let nums: Vec<u64> = (0..array_size)
            .map(|v| (v * time_null() + 71) % 128)
            .collect();
        for num in nums.iter() {
            unsafe {
                let _ = map.write(std::process::id(), *num);
                let val: u64 = map
                    .read(std::process::id())
                    .expect("Failed to read value from hashmap");
                assert_eq!(val, *num);
            }
        }
    }

    #[test]
    fn test_hash_map_bad_index() {
        let map: BpfHashMap = unsafe {
            BpfHashMap::new(
                "mymap",
                std::mem::size_of::<u32>() as u32,
                std::mem::size_of::<u64>() as u32,
                1024,
            )
            .expect("Failed to create new map")
        };
        let _ = unsafe { map.write(1234, 1234) };
        let should_fail: Result<u64, OxidebpfError> = unsafe { map.read(4321) };
        assert!(should_fail.is_err());
        match should_fail {
            Err(OxidebpfError::LinuxError(_, errno)) => {
                assert_eq!(errno, Errno::ENOENT)
            }
            _ => {
                panic!("invalid OxidebpfError: {:?}", should_fail);
            }
        }
    }

    #[test]
    fn test_hash_map_complex_key_value() {
        // A made up structure for this test
        #[derive(Clone, Copy)]
        struct TestStructure<'a> {
            durp0: u64,
            durp1: &'a str,
            durp2: f64,
            durp3: bool,
        }

        // Create the map and initialize a vector of TestStructure
        let array_size: u32 = 10;
        let map: BpfHashMap = unsafe {
            BpfHashMap::new(
                "mymap",
                std::mem::size_of::<u32>() as u32,
                std::mem::size_of::<TestStructure>() as u32,
                array_size as u32,
            )
            .expect("Failed to create new map")
        };

        let data: Vec<TestStructure> = (0..array_size)
            .map(|v| TestStructure {
                durp0: v as u64,
                durp1: "Durp",
                durp2: 0.1234,
                durp3: v % 2 == 0,
            })
            .collect();

        // Write the test structures to the map
        for (i, item) in data.iter().enumerate() {
            unsafe {
                map.write(std::process::id() + i as u32, *item)
                    .expect("could not write to map");
            }
            let val: TestStructure = unsafe {
                map.read(std::process::id() + i as u32)
                    .expect("Failed to read value from array")
            };
            assert_eq!(val.durp0, item.durp0);
            assert_eq!(val.durp1, item.durp1);
            assert_eq!(val.durp2, item.durp2);
            assert_eq!(val.durp3, item.durp3);
        }
    }
}