bpflint 0.3.0

Linting functionality for BPF C programs.
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
use std::str;

use anyhow::Context as _;
use anyhow::Result;

use tracing::warn;

use tree_sitter::Node;
use tree_sitter::Parser;
use tree_sitter::Query;
use tree_sitter::QueryCursor;
use tree_sitter::StreamingIterator as _;
use tree_sitter::Tree;
use tree_sitter_bpf_c::LANGUAGE;

use crate::Point;
use crate::Range;
use crate::Version;


mod lints {
    include!(concat!(env!("OUT_DIR"), "/lints.rs"));
}

impl From<tree_sitter::Point> for Point {
    fn from(other: tree_sitter::Point) -> Self {
        let tree_sitter::Point { row, column } = other;
        Self { row, col: column }
    }
}

impl From<tree_sitter::Range> for Range {
    fn from(other: tree_sitter::Range) -> Self {
        let tree_sitter::Range {
            start_byte,
            end_byte,
            start_point,
            end_point,
        } = other;
        Self {
            bytes: start_byte..end_byte,
            start_point: Point::from(start_point),
            end_point: Point::from(end_point),
        }
    }
}


/// The representation of a lint.
#[derive(Clone, Debug)]
pub struct Lint {
    /// The lint's name.
    pub name: String,
    /// The lints source code in the form of a [tree-sitter
    /// query][query].
    ///
    /// [query]: https://tree-sitter.github.io/tree-sitter/using-parsers/queries/
    pub code: String,
    /// The message reported in a [`LintMatch`][LintMatch::message].
    pub message: String,
}

impl AsRef<Lint> for Lint {
    #[inline]
    fn as_ref(&self) -> &Lint {
        self
    }
}

/// Configuration options for lints.
#[derive(Default, Clone, Debug)]
pub struct LintOpts {
    /// The minimum kernel version being targeted.
    pub kernel_version: Option<Version>,
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}


/// Retrieve the list of lints shipped with the library.
pub fn builtin_lints() -> impl ExactSizeIterator<Item = Lint> + DoubleEndedIterator + Clone {
    lints::LINTS.iter().map(|(name, code, message)| Lint {
        name: name.to_string(),
        code: code.to_string(),
        message: message.to_string(),
    })
}


/// Details about a lint match.
#[derive(Clone, Debug)]
pub struct LintMatch {
    /// The name of the lint that matched.
    pub lint_name: String,
    /// The lint's message.
    pub message: String,
    /// The code range that triggered the lint.
    pub range: Range,
}


/// Walk the syntax tree, checking if a comment node that disable the
/// given lint is present.
fn is_lint_disabled(lint_name: &str, mut node: Node, code: &[u8]) -> bool {
    loop {
        // Walk all previous siblings of the current node.
        if let Some(s) = node.prev_sibling() {
            if s.kind() == "comment" {
                let comment = &code[s.start_byte()..s.end_byte()];
                if let Ok(comment) = str::from_utf8(comment) {
                    // The comment node will still contain the actual
                    // comment syntax, unfortunately.
                    let comment = comment.trim_start_matches("//");
                    let comment = comment.trim_start_matches("/*");
                    let comment = comment.trim_end_matches("*/");
                    let comment = comment.trim();

                    if let Some(comment) = comment.strip_prefix("bpflint:") {
                        let directive = comment.trim();
                        match directive.strip_prefix("disable=") {
                            Some("all") => break true,
                            Some(disable) if disable == lint_name => break true,
                            _ => (),
                        }
                    }
                } else {
                    // If it's not valid UTF-8 it can't be a comment for
                    // us to consider.
                    warn!(
                        "encountered invalid UTF-8 in code comment at bytes `{}..{}`",
                        s.start_byte(),
                        s.end_byte()
                    );
                }
            }
        }

        // Move one level up and repeat.
        match node.parent() {
            Some(parent) => node = parent,
            None => break false,
        }
    }
}


fn lint_impl(
    tree: &Tree,
    code: &[u8],
    lint: &Lint,
    lint_opts: &LintOpts,
) -> Result<Vec<LintMatch>> {
    let Lint {
        name: lint_name,
        code: lint_src,
        message: lint_msg,
    } = lint;

    let query =
        Query::new(&LANGUAGE.into(), lint_src).with_context(|| "failed to compile lint query")?;
    let mut query_cursor = QueryCursor::new();
    let mut results = Vec::new();
    let mut matches = query_cursor.matches(&query, tree.root_node(), code);
    while let Some(m) = matches.next() {
        for capture in m.captures {
            if is_lint_disabled(lint_name, capture.node, code) {
                continue;
            }

            let settings = query.property_settings(m.pattern_index);
            let min_kernel_version = settings
                .iter()
                .find(|prop| prop.key.as_ref() == "min_kernel_version")
                .and_then(|prop| prop.value.as_deref());
            let min_kernel_version = min_kernel_version.map(str::parse::<Version>).transpose()?;

            // Check that min kernel version from the lint is less than
            // the user specified kernel version. If no version is specified
            // for the lint, we default to running it.
            if let (Some(min_kernel_version), Some(kernel_version)) =
                (min_kernel_version, lint_opts.kernel_version)
            {
                if kernel_version < min_kernel_version {
                    continue;
                }
            }

            // SANITY: It would be a tree-sitter bug if the capture
            //         index does not map to a valid capture name.
            let capture_name = query.capture_names()[capture.index as usize];
            // Captures starting with double underscore are considered
            // internal to the lint and are not reported.
            if capture_name.starts_with("__") {
                continue
            }

            let r#match = LintMatch {
                lint_name: lint_name.to_string(),
                message: lint_msg.to_string(),
                range: Range::from(capture.node.range()),
            };
            let () = results.push(r#match);
        }
    }

    if query_cursor.did_exceed_match_limit() {
        warn!("query exceeded maximum number of in-progress captures");
    }
    Ok(results)
}


/// Lint code using the provided set of lints.
///
/// Matches are reported in source code order.
///
/// - `code` is the source code in question, for example as read from a
///   file
/// - `lints` the lints to use for linting the provided source code
///
/// # Examples
/// ```rust
/// # use bpflint::builtin_lints;
/// # use bpflint::lint_custom;
/// # use bpflint::Lint;
/// let bpf_printk = Lint {
///     name: "bpf_printk-usage".to_string(),
///     code: r#"
///         (call_expression
///             function: (identifier) @function (#eq? @function "bpf_printk")
///         )
///       "#.to_string(),
///     message: "use bpf_printk only for debugging!".to_string(),
/// };
///
/// let code = br#"
///     SEC("tp_btf/sched_switch")
///     int handle__sched_switch(u64 *ctx) {
///         bpf_printk("context %p\n", ctx);
///         return 0;
///     }
/// "#;
///
/// // We want to include the built-in lints as well, not just our
/// // `bpf_printk` usage flagger.
/// let matches = lint_custom(code, builtin_lints().chain([bpf_printk])).unwrap();
/// assert_eq!(matches.len(), 1);
/// ```
pub fn lint_custom<'l, I, L>(code: &[u8], lints: I) -> Result<Vec<LintMatch>>
where
    I: IntoIterator<Item = L>,
    L: AsRef<Lint> + 'l,
{
    lint_custom_opts(code, lints, &LintOpts::default())
}

/// Lint code using the provided set of lints with custom options.
/// This function behaves the same as [`lint_custom`], but allows for
/// additional configuration via a [`LintOpts`] object.
pub fn lint_custom_opts<'l, I, L>(
    code: &[u8],
    lints: I,
    lint_opts: &LintOpts,
) -> Result<Vec<LintMatch>>
where
    I: IntoIterator<Item = L>,
    L: AsRef<Lint> + 'l,
{
    let mut parser = Parser::new();
    let () = parser
        .set_language(&LANGUAGE.into())
        .context("failed to load BPF C language parser")?;
    let tree = parser
        .parse(code, None)
        .context("failed to provided source code")?;
    let mut results = Vec::new();
    for lint in lints {
        let matches = lint_impl(&tree, code, lint.as_ref(), lint_opts)?;
        let () = results.extend(matches);
    }

    // Sort results to ensure more consistent reporting with ascending
    // lines.
    let () = results.sort_by(|match1, match2| {
        // NB: We use an ad-hoc comparison rather than a proper
        // `PartialOrd` impl for `Range`, because the latter is a bit
        // harder to do correctly.
        match1
            .range
            .start_point
            .cmp(&match2.range.start_point)
            .then_with(|| match1.range.end_point.cmp(&match2.range.end_point))
    });
    Ok(results)
}

/// Lint code using the default ([built-in][builtin_lints]) set of lints.
///
/// Matches are reported in source code order.
///
/// - `code` is the source code in question, for example as read from a
///   file
pub fn lint(code: &[u8]) -> Result<Vec<LintMatch>> {
    lint_custom(code, builtin_lints())
}


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

    use indoc::indoc;

    use crate::Point;


    fn lint_foo() -> Lint {
        Lint {
            name: "foo".to_string(),
            code: indoc! { r#"
                (call_expression
                    function: (identifier) @function (#eq? @function "foo")
                )
            "# }
            .to_string(),
            message: "foo".to_string(),
        }
    }


    /// Make sure that internal captures (named as "__xxx") are not
    /// reported as matches.
    #[test]
    fn internal_capture_reporting() {
        let code = indoc! { r#"
            bar();
        "# };
        let lint = Lint {
            name: "bar".to_string(),
            code: indoc! { r#"
                (call_expression
                    function: (identifier) @__function (#eq? @__function "bar")
                )
            "# }
            .to_string(),
            message: "a message".to_string(),
        };
        let matches = lint_custom(code.as_bytes(), [lint]).unwrap();
        assert!(matches.is_empty(), "{matches:?}");
    }

    /// Check that our built-in lints exhibit the expected set of
    /// properties.
    #[test]
    fn validate_lints() {
        for lint in builtin_lints() {
            let Lint {
                name,
                code,
                message,
            } = lint;
            let query = Query::new(&LANGUAGE.into(), &code).unwrap();
            assert_eq!(
                query.pattern_count(),
                1,
                "lint `{name}` has too many pattern matches: only a single one is supported currently"
            );

            let last = message.chars().last().unwrap();
            assert!(
                !['.', '!', '?', '\n'].contains(&last),
                "`message` property of lint `{name}` should be concise and not a fully blown sentence with punctuation"
            );
        }
    }

    /// Check that some basic linting works as expected.
    #[test]
    fn basic_linting() {
        let code = indoc! { r#"
            /* A handler for something */
            SEC("tp_btf/sched_switch")
            int handle__sched_switch(u64 *ctx)
            {
                struct task_struct *prev = (struct task_struct *)ctx[1];
                struct event event = {0};
                bpf_probe_read(event.comm, TASK_COMM_LEN, prev->comm);
                return 0;
            }
        "# };

        let matches = lint(code.as_bytes()).unwrap();
        assert_eq!(matches.len(), 1);

        let LintMatch {
            lint_name,
            message,
            range,
        } = &matches[0];
        assert_eq!(lint_name, "probe-read");
        assert!(
            message.starts_with("bpf_probe_read() is deprecated"),
            "{message}"
        );
        assert_eq!(&code[range.bytes.clone()], "bpf_probe_read");
        assert_eq!(range.start_point, Point { row: 6, col: 4 });
        assert_eq!(range.end_point, Point { row: 6, col: 18 });
    }

    /// Check that reported matches are sorted by line number.
    #[test]
    fn sorted_match_reporting() {
        let code = indoc! { r#"
            bar();
            foo();
        "# };
        let lint = Lint {
            name: "bar".to_string(),
            code: indoc! { r#"
                (call_expression
                    function: (identifier) @function (#eq? @function "bar")
                )
            "# }
            .to_string(),
            message: "bar".to_string(),
        };
        let matches = lint_custom(code.as_bytes(), [lint_foo(), lint]).unwrap();
        assert_eq!(matches.len(), 2);
        assert_eq!(matches[0].lint_name, "bar");
        assert_eq!(matches[1].lint_name, "foo");
    }

    /// Check that we can disable lints by name for a given statement.
    #[test]
    fn lint_disabling() {
        let code = indoc! { r#"
            /* bpflint: disable=foo */
            foo();
            // bpflint: disable=foo
            foo();
            // bpflint: disable=all
            foo();
        "# };
        let matches = lint_custom(code.as_bytes(), [lint_foo()]).unwrap();
        assert_eq!(matches.len(), 0, "{matches:?}");
    }

    /// Check that we can disable lints by name for a given block.
    #[test]
    fn lint_disabling_recursive() {
        let code = indoc! { r#"
            /* bpflint: disable=foo */
            {
                {
                    foo();
                }
            }
        "# };
        let matches = lint_custom(code.as_bytes(), [lint_foo()]).unwrap();
        assert_eq!(matches.len(), 0, "{matches:?}");

        let code = indoc! { r#"
            /* bpflint: disable=foo */
            void test_fn(void) {
                foo();
            }
        "# };
        let matches = lint_custom(code.as_bytes(), [lint_foo()]).unwrap();
        assert_eq!(matches.len(), 0, "{matches:?}");
    }

    /// Check that erroneous disabling syntax is not accidentally recognized.
    #[test]
    fn lint_invalid_disabling() {
        let code = indoc! { r#"
            /* bpflint: disabled=foo */
            foo();
            /* disabled=foo */
            foo();
            // disabled=foo
            foo();
            // bpflint: foo
            foo();
            // bpflint: disable=bar
            foo();

            void test_fn(void) {
                /* bpflint: disable=foo */
                foobar();
                foo();
            }
        "# };
        let matches = lint_custom(code.as_bytes(), [lint_foo()]).unwrap();
        assert_eq!(matches.len(), 6, "{matches:?}");
    }

    #[test]
    fn kernel_version_out_of_scope() {
        let lint_opts = LintOpts {
            kernel_version: Some(Version(4, 7, 8)),
            ..Default::default()
        };
        let code = indoc! { r#"
            bar();
        "# };
        let lint = Lint {
            name: "bar".to_string(),
            code: indoc! { r#"
                (call_expression
                    function: (identifier) @function (#eq? @function "bar")
                    (#set! "min_kernel_version" "5.2.0")
                )
            "# }
            .to_string(),
            message: "bar".to_string(),
        };
        let matches = lint_custom_opts(code.as_bytes(), [lint], &lint_opts).unwrap();
        assert_eq!(matches.len(), 0);
    }

    #[test]
    fn kernel_version_in_scope() {
        let lint_opts = LintOpts {
            kernel_version: Some(Version(5, 7, 8)),
            ..Default::default()
        };
        let code = indoc! { r#"
            bar();
        "# };
        let lint = Lint {
            name: "bar".to_string(),
            code: indoc! { r#"
                (call_expression
                    function: (identifier) @function (#eq? @function "bar")
                    (#set! "min_kernel_version" "5.2.0")
                )
            "# }
            .to_string(),
            message: "bar".to_string(),
        };
        let matches = lint_custom_opts(code.as_bytes(), [lint], &lint_opts).unwrap();
        assert_eq!(matches.len(), 1);
    }

    #[test]
    fn kernel_version_equals_lint() {
        let lint_opts = LintOpts {
            kernel_version: Some(Version(5, 2, 0)),
            ..Default::default()
        };
        let code = indoc! { r#"
            bar();
        "# };
        let lint = Lint {
            name: "bar".to_string(),
            code: indoc! { r#"
                (call_expression
                    function: (identifier) @function (#eq? @function "bar")
                    (#set! "min_kernel_version" "5.2.0")
                )
            "# }
            .to_string(),
            message: "bar".to_string(),
        };
        let matches = lint_custom_opts(code.as_bytes(), [lint], &lint_opts).unwrap();
        assert_eq!(matches.len(), 1);
    }

    #[test]
    fn kernel_version_not_in_lint() {
        let lint_opts = LintOpts {
            kernel_version: Some(Version(5, 7, 8)),
            ..Default::default()
        };
        let code = indoc! { r#"
            bar();
        "# };
        let lint = Lint {
            name: "bar".to_string(),
            code: indoc! { r#"
                (call_expression
                    function: (identifier) @function (#eq? @function "bar")
                )
            "# }
            .to_string(),
            message: "bar".to_string(),
        };
        let matches = lint_custom_opts(code.as_bytes(), [lint], &lint_opts).unwrap();
        assert_eq!(matches.len(), 1);
    }

    #[test]
    fn kernel_version_default_with_lint_version() {
        let code = indoc! { r#"
            bar();
        "# };
        let lint = Lint {
            name: "bar".to_string(),
            code: indoc! { r#"
                (call_expression
                    function: (identifier) @function (#eq? @function "bar")
                    (#set! "min_kernel_version" "5.2.0")
                )
            "# }
            .to_string(),
            message: "bar".to_string(),
        };
        let matches = lint_custom(code.as_bytes(), [lint]).unwrap();
        assert_eq!(matches.len(), 1);
    }
}