profile-bee-aya 0.13.2

An eBPF library with a focus on developer experience and operability. Fork of aya for profile-bee.
Documentation
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
//! Program links.
use std::{
    ffi::CString,
    io,
    os::fd::{AsFd as _, AsRawFd as _, BorrowedFd, RawFd},
    path::{Path, PathBuf},
};

use aya_obj::{
    InvalidTypeBinding,
    generated::{
        BPF_F_AFTER, BPF_F_ALLOW_MULTI, BPF_F_ALLOW_OVERRIDE, BPF_F_BEFORE, BPF_F_ID, BPF_F_LINK,
        BPF_F_REPLACE, bpf_attach_type, bpf_link_info, bpf_link_type,
    },
};
use hashbrown::hash_set::{Entry, HashSet};
use thiserror::Error;

use crate::{
    pin::PinError,
    programs::{MultiProgLink, MultiProgram, ProgramError, ProgramFd, ProgramId},
    sys::{
        SyscallError, bpf_get_object, bpf_link_get_info_by_fd, bpf_pin_object, bpf_prog_attach,
        bpf_prog_detach,
    },
};

/// A Link.
pub trait Link: std::fmt::Debug + Eq + std::hash::Hash + 'static {
    /// Unique Id
    type Id: std::fmt::Debug + Eq + std::hash::Hash + hashbrown::Equivalent<Self>;

    /// Returns the link id
    fn id(&self) -> Self::Id;

    /// Detaches the `LinkOwnedLink` is gone... but this doesn't work :(
    fn detach(self) -> Result<(), ProgramError>;
}

/// Program attachment mode.
#[derive(Clone, Copy, Debug, Default)]
pub enum CgroupAttachMode {
    /// Allows only one BPF program in the cgroup subtree.
    #[default]
    Single,

    /// Allows the program to be overridden by one in a sub-cgroup.
    AllowOverride,

    /// Allows multiple programs to be run in the cgroup subtree.
    AllowMultiple,
}

impl From<CgroupAttachMode> for u32 {
    fn from(mode: CgroupAttachMode) -> Self {
        match mode {
            CgroupAttachMode::Single => 0,
            CgroupAttachMode::AllowOverride => BPF_F_ALLOW_OVERRIDE,
            CgroupAttachMode::AllowMultiple => BPF_F_ALLOW_MULTI,
        }
    }
}

#[derive(Debug)]
pub(crate) struct Links<T: Link> {
    links: HashSet<T>,
}

impl<T> Links<T>
where
    T: Eq + std::hash::Hash + Link,
    T::Id: hashbrown::Equivalent<T> + Eq + std::hash::Hash,
{
    pub(crate) fn new() -> Self {
        Self {
            links: Default::default(),
        }
    }

    pub(crate) fn insert(&mut self, link: T) -> Result<T::Id, ProgramError> {
        match self.links.entry(link) {
            Entry::Occupied(_entry) => Err(ProgramError::AlreadyAttached),
            Entry::Vacant(entry) => Ok(entry.insert().get().id()),
        }
    }

    pub(crate) fn remove(&mut self, link_id: T::Id) -> Result<(), ProgramError> {
        self.links
            .take(&link_id)
            .ok_or(ProgramError::NotAttached)?
            .detach()
    }

    pub(crate) fn forget(&mut self, link_id: T::Id) -> Result<T, ProgramError> {
        self.links.take(&link_id).ok_or(ProgramError::NotAttached)
    }
}

impl<T: Link> Links<T> {
    pub(crate) fn remove_all(&mut self) -> Result<(), ProgramError> {
        for link in self.links.drain() {
            link.detach()?;
        }
        Ok(())
    }
}

impl<T: Link> Drop for Links<T> {
    fn drop(&mut self) {
        let _unused: Result<(), ProgramError> = self.remove_all();
    }
}

/// Provides metadata information about an eBPF attachment.
#[doc(alias = "bpf_link_info")]
pub struct LinkInfo(bpf_link_info);

impl LinkInfo {
    pub(crate) fn new_from_fd(fd: BorrowedFd<'_>) -> Result<Self, LinkError> {
        let info = bpf_link_get_info_by_fd(fd)?;
        Ok(Self(info))
    }

    /// Returns the link ID.
    pub const fn id(&self) -> u32 {
        self.0.id
    }

    /// Returns the program ID.
    pub const fn program_id(&self) -> u32 {
        self.0.prog_id
    }

    /// Returns the type of the link.
    pub fn link_type(&self) -> Result<LinkType, LinkError> {
        bpf_link_type::try_from(self.0.type_)
            .map_err(|InvalidTypeBinding { value }| LinkError::UnknownLinkType(value))
            .and_then(LinkType::try_from)
    }
}

/// The type of eBPF link.
#[non_exhaustive]
#[doc(alias = "bpf_link_type")]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum LinkType {
    /// An unspecified link type.
    #[doc(alias = "BPF_LINK_TYPE_UNSPEC")]
    Unspecified = bpf_link_type::BPF_LINK_TYPE_UNSPEC as isize,
    /// A Raw Tracepoint link type.
    #[doc(alias = "BPF_LINK_TYPE_RAW_TRACEPOINT")]
    RawTracePoint = bpf_link_type::BPF_LINK_TYPE_RAW_TRACEPOINT as isize,
    /// A Tracing link type.
    #[doc(alias = "BPF_LINK_TYPE_TRACING")]
    Tracing = bpf_link_type::BPF_LINK_TYPE_TRACING as isize,
    /// A Cgroup link type.
    #[doc(alias = "BPF_LINK_TYPE_CGROUP")]
    Cgroup = bpf_link_type::BPF_LINK_TYPE_CGROUP as isize,
    /// An Iterator link type.
    #[doc(alias = "BPF_LINK_TYPE_ITER")]
    Iter = bpf_link_type::BPF_LINK_TYPE_ITER as isize,
    /// A Network Namespace link type.
    #[doc(alias = "BPF_LINK_TYPE_NETNS")]
    Netns = bpf_link_type::BPF_LINK_TYPE_NETNS as isize,
    /// An XDP link type.
    #[doc(alias = "BPF_LINK_TYPE_XDP")]
    Xdp = bpf_link_type::BPF_LINK_TYPE_XDP as isize,
    /// A Perf Event link type.
    #[doc(alias = "BPF_LINK_TYPE_PERF_EVENT")]
    PerfEvent = bpf_link_type::BPF_LINK_TYPE_PERF_EVENT as isize,
    /// A `KProbe` Multi link type.
    #[doc(alias = "BPF_LINK_TYPE_KPROBE_MULTI")]
    KProbeMulti = bpf_link_type::BPF_LINK_TYPE_KPROBE_MULTI as isize,
    /// A `StructOps` link type.
    #[doc(alias = "BPF_LINK_TYPE_STRUCT_OPS")]
    StructOps = bpf_link_type::BPF_LINK_TYPE_STRUCT_OPS as isize,
    /// A Netfilter link type.
    #[doc(alias = "BPF_LINK_TYPE_NETFILTER")]
    Netfilter = bpf_link_type::BPF_LINK_TYPE_NETFILTER as isize,
    /// A Tcx link type.
    #[doc(alias = "BPF_LINK_TYPE_TCX")]
    Tcx = bpf_link_type::BPF_LINK_TYPE_TCX as isize,
    /// A Uprobe Multi link type.
    #[doc(alias = "BPF_LINK_TYPE_UPROBE_MULTI")]
    UProbeMulti = bpf_link_type::BPF_LINK_TYPE_UPROBE_MULTI as isize,
    /// A Netkit link type.
    #[doc(alias = "BPF_LINK_TYPE_NETKIT")]
    Netkit = bpf_link_type::BPF_LINK_TYPE_NETKIT as isize,
}

impl TryFrom<bpf_link_type> for LinkType {
    type Error = LinkError;

    fn try_from(link_type: bpf_link_type) -> Result<Self, Self::Error> {
        match link_type {
            bpf_link_type::BPF_LINK_TYPE_UNSPEC => Ok(Self::Unspecified),
            bpf_link_type::BPF_LINK_TYPE_RAW_TRACEPOINT => Ok(Self::RawTracePoint),
            bpf_link_type::BPF_LINK_TYPE_TRACING => Ok(Self::Tracing),
            bpf_link_type::BPF_LINK_TYPE_CGROUP => Ok(Self::Cgroup),
            bpf_link_type::BPF_LINK_TYPE_ITER => Ok(Self::Iter),
            bpf_link_type::BPF_LINK_TYPE_NETNS => Ok(Self::Netns),
            bpf_link_type::BPF_LINK_TYPE_XDP => Ok(Self::Xdp),
            bpf_link_type::BPF_LINK_TYPE_PERF_EVENT => Ok(Self::PerfEvent),
            bpf_link_type::BPF_LINK_TYPE_KPROBE_MULTI => Ok(Self::KProbeMulti),
            bpf_link_type::BPF_LINK_TYPE_STRUCT_OPS => Ok(Self::StructOps),
            bpf_link_type::BPF_LINK_TYPE_NETFILTER => Ok(Self::Netfilter),
            bpf_link_type::BPF_LINK_TYPE_TCX => Ok(Self::Tcx),
            bpf_link_type::BPF_LINK_TYPE_UPROBE_MULTI => Ok(Self::UProbeMulti),
            bpf_link_type::BPF_LINK_TYPE_NETKIT => Ok(Self::Netkit),
            bpf_link_type::__MAX_BPF_LINK_TYPE => Err(LinkError::UnknownLinkType(link_type as u32)),
        }
    }
}

/// The identifier of an `FdLink`.
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct FdLinkId(pub(crate) RawFd);

/// A file descriptor link.
///
/// Fd links are returned directly when attaching some program types (for
/// instance [`crate::programs::cgroup_skb::CgroupSkb`]), or can be obtained by
/// converting other link types (see the `TryFrom` implementations).
///
/// An important property of fd links is that they can be pinned. Pinning
/// can be used keep a link attached "in background" even after the program
/// that has created the link terminates.
///
/// # Example
///
/// ```no_run
/// # let mut bpf = Ebpf::load_file("ebpf_programs.o")?;
/// use aya::{Ebpf, programs::{links::FdLink, KProbe}};
///
/// let program: &mut KProbe = bpf.program_mut("intercept_wakeups").unwrap().try_into()?;
/// program.load()?;
/// let link_id = program.attach("try_to_wake_up", 0)?;
/// let link = program.take_link(link_id).unwrap();
/// let fd_link: FdLink = link.try_into().unwrap();
/// fd_link.pin("/sys/fs/bpf/intercept_wakeups_link").unwrap();
///
/// # Ok::<(), aya::EbpfError>(())
/// ```
#[derive(Debug)]
pub struct FdLink {
    pub(crate) fd: crate::MockableFd,
}

impl FdLink {
    pub(crate) const fn new(fd: crate::MockableFd) -> Self {
        Self { fd }
    }

    /// Pins the link to a BPF file system.
    ///
    /// When a link is pinned it will remain attached even after the link instance is dropped,
    /// and will only be detached once the pinned file is removed. To unpin, see [`PinnedLink::unpin()`].
    ///
    /// The parent directories in the provided path must already exist before calling this method,
    /// and must be on a BPF file system (bpffs).
    ///
    /// # Example
    /// ```no_run
    /// # use aya::programs::{links::FdLink, Extension};
    /// # use std::convert::TryInto;
    /// # #[derive(thiserror::Error, Debug)]
    /// # enum Error {
    /// #     #[error(transparent)]
    /// #     Ebpf(#[from] aya::EbpfError),
    /// #     #[error(transparent)]
    /// #     Pin(#[from] aya::pin::PinError),
    /// #     #[error(transparent)]
    /// #     Program(#[from] aya::programs::ProgramError)
    /// # }
    /// # let mut bpf = aya::Ebpf::load(&[])?;
    /// # let prog: &mut Extension = bpf.program_mut("example").unwrap().try_into()?;
    /// let link_id = prog.attach()?;
    /// let owned_link = prog.take_link(link_id)?;
    /// let fd_link: FdLink = owned_link.into();
    /// let pinned_link = fd_link.pin("/sys/fs/bpf/example")?;
    /// # Ok::<(), Error>(())
    /// ```
    pub fn pin<P: AsRef<Path>>(self, path: P) -> Result<PinnedLink, PinError> {
        use std::os::unix::ffi::OsStrExt as _;

        let path = path.as_ref();
        let path_string = CString::new(path.as_os_str().as_bytes()).map_err(|error| {
            PinError::InvalidPinPath {
                path: path.into(),
                error,
            }
        })?;
        bpf_pin_object(self.fd.as_fd(), &path_string).map_err(|io_error| SyscallError {
            call: "BPF_OBJ_PIN",
            io_error,
        })?;
        Ok(PinnedLink::new(path.into(), self))
    }

    /// Returns the kernel information about this link.
    pub fn info(&self) -> Result<LinkInfo, LinkError> {
        LinkInfo::new_from_fd(self.fd.as_fd())
    }
}

impl Link for FdLink {
    type Id = FdLinkId;

    fn id(&self) -> Self::Id {
        FdLinkId(self.fd.as_raw_fd())
    }

    fn detach(self) -> Result<(), ProgramError> {
        // detach is a noop since it consumes self. once self is consumed, drop will be triggered
        // and the link will be detached.
        //
        // Other links don't need to do this since they use define_link_wrapper!, but FdLink is a
        // bit special in that it defines a custom ::new() so it can't use the macro.
        Ok(())
    }
}

id_as_key!(FdLink, FdLinkId);

impl From<PinnedLink> for FdLink {
    fn from(p: PinnedLink) -> Self {
        p.inner
    }
}

/// A pinned file descriptor link.
///
/// This link has been pinned to the BPF filesystem. On drop, the file descriptor that backs
/// this link will be closed. Whether or not the program remains attached is dependent
/// on the presence of the file in BPFFS.
#[derive(Debug)]
pub struct PinnedLink {
    inner: FdLink,
    path: PathBuf,
}

impl PinnedLink {
    const fn new(path: PathBuf, link: FdLink) -> Self {
        Self { inner: link, path }
    }

    /// Creates a [`crate::programs::links::PinnedLink`] from a valid path on bpffs.
    pub fn from_pin<P: AsRef<Path>>(path: P) -> Result<Self, LinkError> {
        use std::os::unix::ffi::OsStrExt as _;

        // TODO: avoid this unwrap by adding a new error variant.
        let path_string = CString::new(path.as_ref().as_os_str().as_bytes()).unwrap();
        let fd = bpf_get_object(&path_string).map_err(|io_error| {
            LinkError::SyscallError(SyscallError {
                call: "BPF_OBJ_GET",
                io_error,
            })
        })?;
        Ok(Self::new(path.as_ref().to_path_buf(), FdLink::new(fd)))
    }

    /// Removes the pinned link from the filesystem and returns an [`FdLink`].
    pub fn unpin(self) -> Result<FdLink, io::Error> {
        std::fs::remove_file(self.path)?;
        Ok(self.inner)
    }
}

/// The identifier of a `ProgAttachLink`.
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct ProgAttachLinkId(RawFd, RawFd, bpf_attach_type);

/// The Link type used by programs that are attached with `bpf_prog_attach`.
#[derive(Debug)]
pub struct ProgAttachLink {
    prog_fd: ProgramFd,
    target_fd: crate::MockableFd,
    attach_type: bpf_attach_type,
}

impl ProgAttachLink {
    pub(crate) const fn new(
        prog_fd: ProgramFd,
        target_fd: crate::MockableFd,
        attach_type: bpf_attach_type,
    ) -> Self {
        Self {
            prog_fd,
            target_fd,
            attach_type,
        }
    }

    pub(crate) fn attach(
        prog_fd: BorrowedFd<'_>,
        target_fd: BorrowedFd<'_>,
        attach_type: bpf_attach_type,
        mode: CgroupAttachMode,
    ) -> Result<Self, ProgramError> {
        // The link is going to own this new file descriptor so we are
        // going to need a duplicate whose lifetime we manage. Let's
        // duplicate it prior to attaching it so the new file
        // descriptor is closed at drop in case it fails to attach.
        let prog_fd = prog_fd.try_clone_to_owned()?;
        let prog_fd = crate::MockableFd::from_fd(prog_fd);
        let target_fd = target_fd.try_clone_to_owned()?;
        let target_fd = crate::MockableFd::from_fd(target_fd);
        bpf_prog_attach(prog_fd.as_fd(), target_fd.as_fd(), attach_type, mode.into())?;

        let prog_fd = ProgramFd(prog_fd);
        Ok(Self {
            prog_fd,
            target_fd,
            attach_type,
        })
    }
}

impl Link for ProgAttachLink {
    type Id = ProgAttachLinkId;

    fn id(&self) -> Self::Id {
        ProgAttachLinkId(
            self.prog_fd.as_fd().as_raw_fd(),
            self.target_fd.as_raw_fd(),
            self.attach_type,
        )
    }

    fn detach(self) -> Result<(), ProgramError> {
        bpf_prog_detach(
            self.prog_fd.as_fd(),
            self.target_fd.as_fd(),
            self.attach_type,
        )
        .map_err(Into::into)
    }
}

id_as_key!(ProgAttachLink, ProgAttachLinkId);

macro_rules! id_as_key {
    ($wrapper:ident, $wrapper_id:ident) => {
        impl PartialEq for $wrapper {
            fn eq(&self, other: &Self) -> bool {
                use $crate::programs::links::Link as _;

                self.id() == other.id()
            }
        }

        impl Eq for $wrapper {}

        impl std::hash::Hash for $wrapper {
            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
                use $crate::programs::links::Link as _;

                self.id().hash(state)
            }
        }

        impl hashbrown::Equivalent<$wrapper> for $wrapper_id {
            fn equivalent(&self, key: &$wrapper) -> bool {
                use $crate::programs::links::Link as _;

                *self == key.id()
            }
        }
    };
}

pub(crate) use id_as_key;

macro_rules! define_link_wrapper {
    ($wrapper:ident, $wrapper_id:ident, $base:ident, $base_id:ident, $program:ident $(,)?) => {
        /// The type returned by
        #[doc = concat!("[`", stringify!($program), "::attach`]")]
        /// . Can be passed to
        #[doc = concat!("[`", stringify!($program), "::detach`]")]
        /// .
        #[derive(Debug, Hash, Eq, PartialEq)]
        pub struct $wrapper_id($base_id);

        /// The link used by
        #[doc = concat!("[`", stringify!($program), "`]")]
        /// programs.
        #[derive(Debug)]
        pub struct $wrapper(Option<$base>);

        #[expect(clippy::allow_attributes, reason = "macro")]
        #[allow(dead_code, reason = "macro")]
        // allow dead code since currently XDP/TC are the only consumers of inner and
        // into_inner
        impl $wrapper {
            const fn new(base: $base) -> $wrapper {
                $wrapper(Some(base))
            }

            const fn inner(&self) -> &$base {
                self.0.as_ref().unwrap()
            }

            fn into_inner(mut self) -> $base {
                self.0.take().unwrap()
            }
        }

        impl Drop for $wrapper {
            fn drop(&mut self) {
                use $crate::programs::links::Link as _;

                if let Some(base) = self.0.take() {
                    let _unused: Result<(), ProgramError> = base.detach();
                }
            }
        }

        impl $crate::programs::Link for $wrapper {
            type Id = $wrapper_id;

            fn id(&self) -> Self::Id {
                $wrapper_id(self.0.as_ref().unwrap().id())
            }

            fn detach(mut self) -> Result<(), ProgramError> {
                self.0.take().unwrap().detach()
            }
        }

        $crate::programs::links::id_as_key!($wrapper, $wrapper_id);

        impl From<$base> for $wrapper {
            fn from(b: $base) -> $wrapper {
                $wrapper(Some(b))
            }
        }

        impl From<$wrapper> for $base {
            fn from(mut w: $wrapper) -> $base {
                w.0.take().unwrap()
            }
        }

        impl $program {
            /// Detaches the program.
            ///
            /// See [`Self::attach`].
            pub fn detach(&mut self, link_id: $wrapper_id) -> Result<(), ProgramError> {
                self.data.links.remove(link_id)
            }

            /// Takes ownership of the link referenced by the provided `link_id`.
            ///
            /// The caller takes the responsibility of managing the lifetime of the link. When the
            /// returned
            #[doc = concat!("[`", stringify!($wrapper), "`]")]
            /// is dropped, the link will be detached.
            pub fn take_link(&mut self, link_id: $wrapper_id) -> Result<$wrapper, ProgramError> {
                self.data.links.forget(link_id)
            }
        }
    };
}

pub(crate) use define_link_wrapper;

macro_rules! impl_try_into_fdlink {
    ($wrapper:ident, $inner:ident) => {
        impl TryFrom<$wrapper> for $crate::programs::FdLink {
            type Error = $crate::programs::LinkError;

            fn try_from(value: $wrapper) -> Result<Self, Self::Error> {
                if let $inner::Fd(fd) = value.into_inner() {
                    Ok(fd)
                } else {
                    Err($crate::programs::LinkError::InvalidLink)
                }
            }
        }
    };
}

pub(crate) use impl_try_into_fdlink;

#[derive(Error, Debug)]
/// Errors from operations on links.
pub enum LinkError {
    /// Invalid link.
    #[error("Invalid link")]
    InvalidLink,

    /// The kernel type of this link is not understood by Aya.
    /// Please open an issue on GitHub if you encounter this error.
    #[error("unknown link type {0}")]
    UnknownLinkType(u32),

    /// Syscall failed.
    #[error(transparent)]
    SyscallError(#[from] SyscallError),
}

#[derive(Debug)]
pub(crate) enum LinkRef {
    Id(u32),
    Fd(RawFd),
}

bitflags::bitflags! {
    /// Flags which are use to build a set of MprogOptions.
    #[derive(Clone, Copy, Debug, Default)]
    pub(crate) struct MprogFlags: u32 {
        const REPLACE = BPF_F_REPLACE;
        const BEFORE = BPF_F_BEFORE;
        const AFTER = BPF_F_AFTER;
        const ID = BPF_F_ID;
        const LINK = BPF_F_LINK;
    }
}

/// Arguments required for interacting with the kernel's multi-prog API.
///
/// # Minimum kernel version
///
/// The minimum kernel version required to use this feature is 6.6.0.
///
/// # Example
///
/// ```no_run
/// # let mut bpf = aya::Ebpf::load(&[])?;
/// use aya::programs::{tc, SchedClassifier, TcAttachType, tc::TcAttachOptions, LinkOrder};
///
/// let prog: &mut SchedClassifier = bpf.program_mut("redirect_ingress").unwrap().try_into()?;
/// prog.load()?;
/// let options = TcAttachOptions::TcxOrder(LinkOrder::first());
/// prog.attach_with_options("eth0", TcAttachType::Ingress, options)?;
///
/// # Ok::<(), aya::EbpfError>(())
/// ```
#[derive(Debug)]
pub struct LinkOrder {
    pub(crate) link_ref: LinkRef,
    pub(crate) flags: MprogFlags,
}

/// Ensure that default link ordering is to be attached last.
impl Default for LinkOrder {
    fn default() -> Self {
        Self {
            link_ref: LinkRef::Fd(0),
            flags: MprogFlags::AFTER,
        }
    }
}

impl LinkOrder {
    /// Attach before all other links.
    pub const fn first() -> Self {
        Self {
            link_ref: LinkRef::Id(0),
            flags: MprogFlags::BEFORE,
        }
    }

    /// Attach after all other links.
    pub const fn last() -> Self {
        Self {
            link_ref: LinkRef::Id(0),
            flags: MprogFlags::AFTER,
        }
    }

    /// Attach before the given link.
    pub fn before_link<L: MultiProgLink>(link: &L) -> Result<Self, LinkError> {
        Ok(Self {
            link_ref: LinkRef::Fd(link.fd()?.as_raw_fd()),
            flags: MprogFlags::BEFORE | MprogFlags::LINK,
        })
    }

    /// Attach after the given link.
    pub fn after_link<L: MultiProgLink>(link: &L) -> Result<Self, LinkError> {
        Ok(Self {
            link_ref: LinkRef::Fd(link.fd()?.as_raw_fd()),
            flags: MprogFlags::AFTER | MprogFlags::LINK,
        })
    }

    /// Attach before the given program.
    pub fn before_program<P: MultiProgram>(program: &P) -> Result<Self, ProgramError> {
        Ok(Self {
            link_ref: LinkRef::Fd(program.fd()?.as_raw_fd()),
            flags: MprogFlags::BEFORE,
        })
    }

    /// Attach after the given program.
    pub fn after_program<P: MultiProgram>(program: &P) -> Result<Self, ProgramError> {
        Ok(Self {
            link_ref: LinkRef::Fd(program.fd()?.as_raw_fd()),
            flags: MprogFlags::AFTER,
        })
    }

    /// Attach before the program with the given id.
    pub fn before_program_id(id: ProgramId) -> Self {
        Self {
            link_ref: LinkRef::Id(id.0),
            flags: MprogFlags::BEFORE | MprogFlags::ID,
        }
    }

    /// Attach after the program with the given id.
    pub fn after_program_id(id: ProgramId) -> Self {
        Self {
            link_ref: LinkRef::Id(id.0),
            flags: MprogFlags::AFTER | MprogFlags::ID,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, fs::File, rc::Rc};

    use assert_matches::assert_matches;
    use aya_obj::generated::{BPF_F_ALLOW_MULTI, BPF_F_ALLOW_OVERRIDE};
    use tempfile::tempdir;

    use super::{FdLink, Link, Links};
    use crate::{
        programs::{CgroupAttachMode, ProgramError},
        sys::override_syscall,
    };

    #[derive(Debug, Hash, Eq, PartialEq)]
    struct TestLinkId(u8, u8);

    #[derive(Debug)]
    struct TestLink {
        id: (u8, u8),
        detached: Rc<RefCell<u8>>,
    }

    impl TestLink {
        fn new(a: u8, b: u8) -> Self {
            Self {
                id: (a, b),
                detached: Rc::new(RefCell::new(0)),
            }
        }
    }

    impl Link for TestLink {
        type Id = TestLinkId;

        fn id(&self) -> Self::Id {
            TestLinkId(self.id.0, self.id.1)
        }

        fn detach(self) -> Result<(), ProgramError> {
            *self.detached.borrow_mut() += 1;
            Ok(())
        }
    }

    id_as_key!(TestLink, TestLinkId);

    #[test]
    fn test_link_map() {
        let mut links = Links::new();
        let l1 = TestLink::new(1, 2);
        let l1_detached = Rc::clone(&l1.detached);
        let l2 = TestLink::new(1, 3);
        let l2_detached = Rc::clone(&l2.detached);

        let id1 = links.insert(l1).unwrap();
        let id2 = links.insert(l2).unwrap();

        assert_eq!(*l1_detached.borrow(), 0);
        assert_eq!(*l2_detached.borrow(), 0);

        links.remove(id1).unwrap();
        assert_eq!(*l1_detached.borrow(), 1);
        assert_eq!(*l2_detached.borrow(), 0);

        links.remove(id2).unwrap();
        assert_eq!(*l1_detached.borrow(), 1);
        assert_eq!(*l2_detached.borrow(), 1);
    }

    #[test]
    fn test_already_attached() {
        let mut links = Links::new();

        links.insert(TestLink::new(1, 2)).unwrap();
        assert_matches!(
            links.insert(TestLink::new(1, 2)),
            Err(ProgramError::AlreadyAttached)
        );
    }

    #[test]
    fn test_not_attached() {
        let mut links = Links::new();

        let l1 = TestLink::new(1, 2);
        let l1_id1 = l1.id();
        let l1_id2 = l1.id();
        links.insert(TestLink::new(1, 2)).unwrap();
        links.remove(l1_id1).unwrap();
        assert_matches!(links.remove(l1_id2), Err(ProgramError::NotAttached));
    }

    #[test]
    fn test_drop_detach() {
        let l1 = TestLink::new(1, 2);
        let l1_detached = Rc::clone(&l1.detached);
        let l2 = TestLink::new(1, 3);
        let l2_detached = Rc::clone(&l2.detached);

        {
            let mut links = Links::new();
            let id1 = links.insert(l1).unwrap();
            links.insert(l2).unwrap();
            // manually remove one link
            links.remove(id1).unwrap();
            assert_eq!(*l1_detached.borrow(), 1);
            assert_eq!(*l2_detached.borrow(), 0);
        }
        // remove the other on drop
        assert_eq!(*l1_detached.borrow(), 1);
        assert_eq!(*l2_detached.borrow(), 1);
    }

    #[test]
    fn test_owned_detach() {
        let l1 = TestLink::new(1, 2);
        let l1_detached = Rc::clone(&l1.detached);
        let l2 = TestLink::new(1, 3);
        let l2_detached = Rc::clone(&l2.detached);

        let owned_l1 = {
            let mut links = Links::new();
            let id1 = links.insert(l1).unwrap();
            links.insert(l2).unwrap();
            // manually forget one link
            let owned_l1 = links.forget(id1);
            assert_eq!(*l1_detached.borrow(), 0);
            assert_eq!(*l2_detached.borrow(), 0);
            owned_l1.unwrap()
        };

        // l2 is detached on `Drop`, but l1 is still alive
        assert_eq!(*l1_detached.borrow(), 0);
        assert_eq!(*l2_detached.borrow(), 1);

        // manually detach l1
        owned_l1.detach().unwrap();
        assert_eq!(*l1_detached.borrow(), 1);
        assert_eq!(*l2_detached.borrow(), 1);
    }

    #[test]
    #[cfg_attr(miri, ignore = "`mkdir` not available when isolation is enabled")]
    fn test_pin() {
        let dir = tempdir().unwrap();
        let f1 = File::create(dir.path().join("f1")).expect("unable to create file in tmpdir");
        let fd_link = FdLink::new(f1.into());

        // override syscall to allow for pin to happen in our tmpdir
        override_syscall(|_| Ok(0));
        // create the file that would have happened as a side-effect of a real pin operation
        let pin = dir.path().join("f1-pin");
        File::create(&pin).expect("unable to create file in tmpdir");
        assert!(pin.exists());

        let pinned_link = fd_link.pin(&pin).expect("pin failed");
        pinned_link.unpin().expect("unpin failed");
        assert!(!pin.exists());
    }

    #[test]
    fn test_cgroup_attach_flag() {
        assert_eq!(u32::from(CgroupAttachMode::Single), 0);
        assert_eq!(
            u32::from(CgroupAttachMode::AllowOverride),
            BPF_F_ALLOW_OVERRIDE
        );
        assert_eq!(
            u32::from(CgroupAttachMode::AllowMultiple),
            BPF_F_ALLOW_MULTI
        );
    }
}