aya_log_common/
lib.rs

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
#![no_std]

use core::{
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
    num::{NonZeroUsize, TryFromIntError},
};

use num_enum::IntoPrimitive;

pub const LOG_BUF_CAPACITY: usize = 8192;

pub const LOG_FIELDS: usize = 6;

pub type LogValueLength = u16;

#[repr(u8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug, Hash, IntoPrimitive)]
pub enum Level {
    /// The "error" level.
    ///
    /// Designates very serious errors.
    Error = 1,
    /// The "warn" level.
    ///
    /// Designates hazardous situations.
    Warn,
    /// The "info" level.
    ///
    /// Designates useful information.
    Info,
    /// The "debug" level.
    ///
    /// Designates lower priority information.
    Debug,
    /// The "trace" level.
    ///
    /// Designates very low priority, often extremely verbose, information.
    Trace,
}

macro_rules! impl_formatter_for_types {
    ($trait:path : { $($type:ty),*}) => {
        $(
            impl $trait for $type {}
        )*
    };
}

pub trait DefaultFormatter {}
impl_formatter_for_types!(
    DefaultFormatter: {
        bool,
        i8, i16, i32, i64, isize,
        u8, u16, u32, u64, usize,
        f32, f64,
        char,
        str,
        &str,
        IpAddr, Ipv4Addr, Ipv6Addr
    }
);

pub trait LowerHexFormatter {}
impl_formatter_for_types!(
    LowerHexFormatter: {
        i8, i16, i32, i64, isize,
        u8, u16, u32, u64, usize,
        &[u8]
    }
);

pub trait UpperHexFormatter {}
impl_formatter_for_types!(
    UpperHexFormatter: {
        i8, i16, i32, i64, isize,
        u8, u16, u32, u64, usize,
        &[u8]
    }
);

pub trait IpFormatter {}
impl IpFormatter for IpAddr {}
impl IpFormatter for Ipv4Addr {}
impl IpFormatter for Ipv6Addr {}
impl IpFormatter for u32 {}
impl IpFormatter for [u8; 4] {}
impl IpFormatter for [u8; 16] {}
impl IpFormatter for [u16; 8] {}

pub trait LowerMacFormatter {}
impl LowerMacFormatter for [u8; 6] {}

pub trait UpperMacFormatter {}
impl UpperMacFormatter for [u8; 6] {}

#[repr(u8)]
#[derive(Copy, Clone, Debug, IntoPrimitive)]
pub enum RecordField {
    Target = 1,
    Level,
    Module,
    File,
    Line,
    NumArgs,
}

/// Types which are supported by aya-log and can be safely sent from eBPF
/// programs to userspace.
#[repr(u8)]
#[derive(Copy, Clone, Debug, IntoPrimitive)]
pub enum Argument {
    DisplayHint,

    I8,
    I16,
    I32,
    I64,
    Isize,

    U8,
    U16,
    U32,
    U64,
    Usize,

    F32,
    F64,

    Ipv4Addr,
    Ipv6Addr,

    /// `[u8; 4]` array which represents an IPv4 address.
    ArrU8Len4,
    /// `[u8; 6]` array which represents a MAC address.
    ArrU8Len6,
    /// `[u8; 16]` array which represents an IPv6 address.
    ArrU8Len16,
    /// `[u16; 8]` array which represents an IPv6 address.
    ArrU16Len8,

    Bytes,
    Str,
}

/// All display hints
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, IntoPrimitive)]
pub enum DisplayHint {
    /// Default string representation.
    Default = 1,
    /// `:x`
    LowerHex,
    /// `:X`
    UpperHex,
    /// `:i`
    Ip,
    /// `:mac`
    LowerMac,
    /// `:MAC`
    UpperMac,
}

// Must be inlined, else the BPF backend emits:
//
// llvm: <unknown>:0:0: in function _ZN14aya_log_common5write17hc9ed05433e23a663E { i64, i64 } (i8, ptr, i64, ptr, i64): only integer returns supported
#[inline(always)]
pub(crate) fn write(tag: u8, value: &[u8], buf: &mut [u8]) -> Option<NonZeroUsize> {
    let wire_len: LogValueLength = match value.len().try_into() {
        Ok(wire_len) => Some(wire_len),
        Err(TryFromIntError { .. }) => None,
    }?;
    let mut size = 0;
    macro_rules! copy_from_slice {
        ($value:expr) => {{
            let buf = buf.get_mut(size..)?;
            let buf = buf.get_mut(..$value.len())?;
            buf.copy_from_slice($value);
            size += $value.len();
        }};
    }
    copy_from_slice!(&[tag]);
    copy_from_slice!(&wire_len.to_ne_bytes());
    copy_from_slice!(value);
    NonZeroUsize::new(size)
}

pub trait WriteToBuf {
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize>;
}

macro_rules! impl_write_to_buf {
    ($type:ident, $arg_type:expr) => {
        impl WriteToBuf for $type {
            // This need not be inlined because the return value is Option<N> where N is
            // mem::size_of<$type>, which is a compile-time constant.
            #[inline(never)]
            fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
                write($arg_type.into(), &self.to_ne_bytes(), buf)
            }
        }
    };
}

impl_write_to_buf!(i8, Argument::I8);
impl_write_to_buf!(i16, Argument::I16);
impl_write_to_buf!(i32, Argument::I32);
impl_write_to_buf!(i64, Argument::I64);
impl_write_to_buf!(isize, Argument::Isize);

impl_write_to_buf!(u8, Argument::U8);
impl_write_to_buf!(u16, Argument::U16);
impl_write_to_buf!(u32, Argument::U32);
impl_write_to_buf!(u64, Argument::U64);
impl_write_to_buf!(usize, Argument::Usize);

impl_write_to_buf!(f32, Argument::F32);
impl_write_to_buf!(f64, Argument::F64);

impl WriteToBuf for IpAddr {
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        match self {
            IpAddr::V4(ipv4_addr) => write(Argument::Ipv4Addr.into(), &ipv4_addr.octets(), buf),
            IpAddr::V6(ipv6_addr) => write(Argument::Ipv6Addr.into(), &ipv6_addr.octets(), buf),
        }
    }
}

impl WriteToBuf for Ipv4Addr {
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        write(Argument::Ipv4Addr.into(), &self.octets(), buf)
    }
}

impl WriteToBuf for [u8; 4] {
    // This need not be inlined because the return value is Option<N> where N is 16, which is a
    // compile-time constant.
    #[inline(never)]
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        write(Argument::ArrU8Len4.into(), &self, buf)
    }
}

impl WriteToBuf for Ipv6Addr {
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        write(Argument::Ipv6Addr.into(), &self.octets(), buf)
    }
}

impl WriteToBuf for [u8; 16] {
    // This need not be inlined because the return value is Option<N> where N is 16, which is a
    // compile-time constant.
    #[inline(never)]
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        write(Argument::ArrU8Len16.into(), &self, buf)
    }
}

impl WriteToBuf for [u16; 8] {
    // This need not be inlined because the return value is Option<N> where N is 16, which is a
    // compile-time constant.
    #[inline(never)]
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        let bytes = unsafe { core::mem::transmute::<[u16; 8], [u8; 16]>(self) };
        write(Argument::ArrU16Len8.into(), &bytes, buf)
    }
}

impl WriteToBuf for [u8; 6] {
    // This need not be inlined because the return value is Option<N> where N is 6, which is a
    // compile-time constant.
    #[inline(never)]
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        write(Argument::ArrU8Len6.into(), &self, buf)
    }
}

impl WriteToBuf for &[u8] {
    // Must be inlined, else the BPF backend emits:
    //
    // llvm: <unknown>:0:0: in function _ZN63_$LT$$RF$$u5b$u8$u5d$$u20$as$u20$aya_log_common..WriteToBuf$GT$5write17h08f30a45f7b9f09dE { i64, i64 } (ptr, i64, ptr, i64): only integer returns supported
    #[inline(always)]
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        write(Argument::Bytes.into(), self, buf)
    }
}

impl WriteToBuf for &str {
    // Must be inlined, else the BPF backend emits:
    //
    // llvm: <unknown>:0:0: in function _ZN54_$LT$$RF$str$u20$as$u20$aya_log_common..WriteToBuf$GT$5write17h7e2d1ccaa758e2b5E { i64, i64 } (ptr, i64, ptr, i64): only integer returns supported
    #[inline(always)]
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        write(Argument::Str.into(), self.as_bytes(), buf)
    }
}

impl WriteToBuf for DisplayHint {
    // This need not be inlined because the return value is Option<N> where N is 1, which is a
    // compile-time constant.
    #[inline(never)]
    fn write(self, buf: &mut [u8]) -> Option<NonZeroUsize> {
        let v: u8 = self.into();
        write(Argument::DisplayHint.into(), &v.to_ne_bytes(), buf)
    }
}

#[doc(hidden)]
#[inline(always)] // This function takes too many arguments to not be inlined.
pub fn write_record_header(
    buf: &mut [u8],
    target: &str,
    level: Level,
    module: &str,
    file: &str,
    line: u32,
    num_args: usize,
) -> Option<NonZeroUsize> {
    let level: u8 = level.into();
    let mut size = 0;
    macro_rules! write {
        ($tag:expr, $value:expr) => {{
            let buf = buf.get_mut(size..)?;
            let len = write($tag.into(), $value, buf)?;
            size += len.get();
        }};
    }
    write!(RecordField::Target, target.as_bytes());
    write!(RecordField::Level, &level.to_ne_bytes());
    write!(RecordField::Module, module.as_bytes());
    write!(RecordField::File, file.as_bytes());
    write!(RecordField::Line, &line.to_ne_bytes());
    write!(RecordField::NumArgs, &num_args.to_ne_bytes());
    NonZeroUsize::new(size)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn log_value_length_sufficient() {
        assert!(
            LOG_BUF_CAPACITY <= LogValueLength::MAX.into(),
            "{} > {}",
            LOG_BUF_CAPACITY,
            LogValueLength::MAX
        );
    }
}