bpflint 0.2.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
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
use std::io;
use std::path::Path;

use anyhow::Result;

use crate::LintMatch;
use crate::lines::Lines;


/// Configuration options for terminal reporting.
#[derive(Default, Clone, Debug)]
pub struct Opts {
    /// Extra lines of context to report before and after a match.
    pub extra_lines: (u8, u8),
    /// The struct is non-exhaustive and open to extension.
    #[doc(hidden)]
    pub _non_exhaustive: (),
}


/// Report a lint match in terminal style.
///
/// - `match` is the match to create a report for
/// - `code` is the source code in question, as passed to
///   [`lint`][crate::lint()]
/// - `path` should be the path to the file to which `code` corresponds
///   and is used to enhance the generated report
/// - `writer` is a reference to a [`io::Write`] to which to write the
///   report
///
/// # Example
/// ```text
/// warning: [probe-read] bpf_probe_read() is deprecated and replaced by
///          bpf_probe_user() and bpf_probe_kernel(); refer to bpf-helpers(7)
///   --> example.bpf.c:43:24
///    |
/// 43 |                         bpf_probe_read(event.comm, TASK_COMM_LEN, prev->comm);
///    |                         ^^^^^^^^^^^^^^
///    |
/// ```
pub fn report_terminal(
    r#match: &LintMatch,
    code: &[u8],
    path: &Path,
    writer: &mut dyn io::Write,
) -> Result<()> {
    report_terminal_opts(r#match, code, path, &Opts::default(), writer)
}

/// Report a lint match in terminal style with extra lines for context as configured.
///
/// - `match` is the match to create a report for
/// - `code` is the source code in question, as passed to
///   [`lint`][crate::lint()]
/// - `path` should be the path to the file to which `code` corresponds
///   and is used to enhance the generated report
/// - `opts` specifies the reporting options including context lines
/// - `writer` is a reference to a [`io::Write`] to which to write the
///   report
///
/// # Example
/// ```text
/// warning: [probe-read] bpf_probe_read() is deprecated and replaced by
///          bpf_probe_user() and bpf_probe_kernel(); refer to bpf-helpers(7)
///   --> example.bpf.c:43:24
///    |
/// 41 |     struct task_struct *prev = (struct task_struct *)ctx[1];
/// 42 |     struct event event = {0};
/// 43 |     bpf_probe_read(event.comm, TASK_COMM_LEN, prev->comm);
///    |     ^^^^^^^^^^^^^^
/// 44 |     return 0;
/// 45 | }
///    |
/// ```
pub fn report_terminal_opts(
    r#match: &LintMatch,
    code: &[u8],
    path: &Path,
    opts: &Opts,
    writer: &mut dyn io::Write,
) -> Result<()> {
    let LintMatch {
        lint_name,
        message,
        range,
    } = r#match;

    writeln!(writer, "warning: [{lint_name}] {message}")?;
    let start_row = range.start_point.row;
    let end_row = range.end_point.row;
    let start_col = range.start_point.col;
    let end_col = range.end_point.col;
    writeln!(writer, "  --> {}:{start_row}:{start_col}", path.display())?;
    let width = (end_row + usize::from(opts.extra_lines.1))
        .to_string()
        .len();

    if range.bytes.is_empty() {
        return Ok(())
    }

    // Use the end row here, as it's the largest number, so we end up
    // with a consistent indentation.
    let prefix = format!("{:width$} | ", "");
    writeln!(writer, "{prefix}")?;

    // Print source code context before the actual match. Need to
    // `collect` here, because the `Write` interface we work with forces
    // us to emit data in sequential order, but we necessary have to go
    // backwards from the match.
    // SANITY: It would be a tree-sitter bug the range does not
    //         map to a valid code location.
    let () = Lines::new(code, range.bytes.start)
        .rev()
        // Skip the line of the match.
        .skip(1)
        .take(opts.extra_lines.0.into())
        .collect::<Vec<&[u8]>>()
        .into_iter()
        .enumerate()
        .rev()
        .try_for_each(|(row_sub, line)| {
            let row = start_row - row_sub - 1;
            writeln!(writer, "{row:width$} | {}", String::from_utf8_lossy(line))
        })?;

    // SANITY: It would be a tree-sitter bug the range does not
    //         map to a valid code location.
    let mut lines = Lines::new(code, range.bytes.start);

    if start_row == end_row {
        let lprefix = format!("{start_row:width$} | ");
        // SANITY: `Lines` will always report at least a single
        //          line.
        let line = lines.next().unwrap();
        writeln!(writer, "{lprefix}{}", String::from_utf8_lossy(line))?;
        writeln!(
            writer,
            "{prefix}{:indent$}{:^<width$}",
            "",
            "",
            indent = start_col,
            width = end_col.saturating_sub(start_col)
        )?;
    } else {
        for (idx, row) in (start_row..=end_row).enumerate() {
            let lprefix = format!("{row:width$} | ");
            let c = if idx == 0 { "/" } else { "|" };
            // Our `Lines` logic may not report a trailing newline if it
            // is completely empty, but `tree-sitter` may actually
            // report it. If that's the case just ignore this empty
            // line.
            let Some(line) = lines.next() else { break };
            writeln!(writer, "{lprefix} {c} {}", String::from_utf8_lossy(line))?;
        }
        writeln!(writer, "{prefix} |{:_<width$}^", "", width = end_col)?;
    }

    let () = lines
        .take(opts.extra_lines.1.into())
        .enumerate()
        .try_for_each(|(row_add, line)| {
            let row = end_row + row_add + 1;
            writeln!(writer, "{row:width$} | {}", String::from_utf8_lossy(line))
        })?;

    writeln!(writer, "{prefix}")?;
    Ok(())
}


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

    use indoc::indoc;

    use pretty_assertions::assert_eq;

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


    /// Tests that a match with an empty range includes no code snippet.
    #[test]
    fn empty_range_reporting() {
        let code = indoc! { r#"
            int main() {}
        "# };

        let m = LintMatch {
            lint_name: "bogus-file-extension".to_string(),
            message: "by convention BPF C code should use the file extension '.bpf.c'".to_string(),
            range: Range {
                bytes: 0..0,
                start_point: Point::default(),
                end_point: Point::default(),
            },
        };
        let mut report = Vec::new();
        let () =
            report_terminal(&m, code.as_bytes(), Path::new("./no_bytes.c"), &mut report).unwrap();
        let report = String::from_utf8(report).unwrap();
        let expected = indoc! { r#"
            warning: [bogus-file-extension] by convention BPF C code should use the file extension '.bpf.c'
              --> ./no_bytes.c:0:0
        "# };
        assert_eq!(report, expected);
    }

    /// Make sure that multi-line matches are reported correctly.
    #[test]
    fn multi_line_report() {
        let code = indoc! { r#"
            SEC("tp_btf/sched_switch")
            int handle__sched_switch(u64 *ctx) {
                bpf_probe_read(
                  event.comm,
                  TASK_COMM_LEN,
                  prev->comm);
                return 0;
            }
        "# };

        let m = LintMatch {
            lint_name: "probe-read".to_string(),
            message: "bpf_probe_read() is deprecated".to_string(),
            range: Range {
                bytes: 68..140,
                start_point: Point { row: 2, col: 4 },
                end_point: Point { row: 5, col: 17 },
            },
        };
        let mut report = Vec::new();
        let () = report_terminal(&m, code.as_bytes(), Path::new("<stdin>"), &mut report).unwrap();
        let report = String::from_utf8(report).unwrap();
        let expected = indoc! { r#"
            warning: [probe-read] bpf_probe_read() is deprecated
              --> <stdin>:2:4
              | 
            2 |  /     bpf_probe_read(
            3 |  |       event.comm,
            4 |  |       TASK_COMM_LEN,
            5 |  |       prev->comm);
              |  |_________________^
              | 
        "# };
        assert_eq!(report, expected);
    }

    /// Make sure that multi-line matches that are straddling a power of
    /// ten line number are reported correctly.
    #[test]
    fn multi_line_report_line_numbers() {
        let code = indoc! { r#"
            /* A
             * bunch
             * of
             * filling
             */
            SEC("tp_btf/sched_switch")
            int handle__sched_switch(u64 *ctx) {
                bpf_probe_read(
                  event.comm,
                  TASK_COMM_LEN,
                  prev->comm);
                return 0;
            }
        "# };

        let m = LintMatch {
            lint_name: "probe-read".to_string(),
            message: "bpf_probe_read() is deprecated".to_string(),
            range: Range {
                bytes: 103..175,
                start_point: Point { row: 7, col: 4 },
                end_point: Point { row: 10, col: 17 },
            },
        };
        let mut report = Vec::new();
        let () = report_terminal(&m, code.as_bytes(), Path::new("<stdin>"), &mut report).unwrap();
        let report = String::from_utf8(report).unwrap();
        let expected = indoc! { r#"
            warning: [probe-read] bpf_probe_read() is deprecated
              --> <stdin>:7:4
               | 
             7 |  /     bpf_probe_read(
             8 |  |       event.comm,
             9 |  |       TASK_COMM_LEN,
            10 |  |       prev->comm);
               |  |_________________^
               | 
        "# };
        assert_eq!(report, expected);
    }

    /// Check that we "correctly" report matches effectively spanning
    /// the end of the file.
    ///
    /// This can happen for queries that use `preproc_def`, because it
    /// includes trailing newlines in its match.
    #[test]
    fn multi_line_trailing_line_empty() {
        let code = indoc! { r#"
            #define DONT_ENABLE 1
        "# };
        let m = LintMatch {
            lint_name: "lint".to_string(),
            message: "message".to_string(),
            range: Range {
                bytes: 0..21,
                start_point: Point { row: 0, col: 0 },
                end_point: Point { row: 1, col: 0 },
            },
        };

        let mut report = Vec::new();
        let () = report_terminal(&m, code.as_bytes(), Path::new("<stdin>"), &mut report).unwrap();
        let report = String::from_utf8(report).unwrap();

        // Note that ideally we'd fine a way to just highlight the
        // entire line instead of using the multi-line reporting path
        // here, but it's not trivial to do so.
        let expected = indoc! { r#"
            warning: [lint] message
              --> <stdin>:0:0
              | 
            0 |  / #define DONT_ENABLE 1
              |  |^
              | 
        "# };
        assert_eq!(report, expected);
    }

    /// Check that our "terminal" reporting works as expected.
    #[test]
    fn terminal_reporting() {
        let code = indoc! { r#"
            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 m = LintMatch {
            lint_name: "probe-read".to_string(),
            message: "bpf_probe_read() is deprecated".to_string(),
            range: Range {
                bytes: 160..174,
                start_point: Point { row: 6, col: 4 },
                end_point: Point { row: 6, col: 18 },
            },
        };
        let mut report = Vec::new();
        let () = report_terminal(&m, code.as_bytes(), Path::new("<stdin>"), &mut report).unwrap();
        let report = String::from_utf8(report).unwrap();
        let expected = indoc! { r#"
            warning: [probe-read] bpf_probe_read() is deprecated
              --> <stdin>:6:4
              | 
            6 |     bpf_probe_read(event.comm, TASK_COMM_LEN, prev->comm);
              |     ^^^^^^^^^^^^^^
              | 
        "# };
        assert_eq!(report, expected);
    }

    /// Check that reporting works properly when the match is on the
    /// very first line of input.
    #[test]
    fn report_top_most_line() {
        let code = indoc! { r#"
            SEC("kprobe/test")
            int handle__test(void)
            {
            }
        "# };

        let m = LintMatch {
            lint_name: "unstable-attach-point".to_string(),
            message: "kprobe/kretprobe/fentry/fexit are unstable".to_string(),
            range: Range {
                bytes: 4..17,
                start_point: Point { row: 0, col: 4 },
                end_point: Point { row: 0, col: 17 },
            },
        };
        let mut report = Vec::new();
        let () = report_terminal(&m, code.as_bytes(), Path::new("<stdin>"), &mut report).unwrap();
        let report = String::from_utf8(report).unwrap();
        let expected = indoc! { r#"
            warning: [unstable-attach-point] kprobe/kretprobe/fentry/fexit are unstable
              --> <stdin>:0:4
              | 
            0 | SEC("kprobe/test")
              |     ^^^^^^^^^^^^^
              | 
        "# };
        assert_eq!(report, expected);
    }

    /// Test that `report_terminal_opts` with `Opts::default()` behaves
    /// identically to `report_terminal`.
    #[test]
    fn report_terminal_opts_none_context() {
        let code = indoc! { r#"
            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 m = LintMatch {
            lint_name: "probe-read".to_string(),
            message: "bpf_probe_read() is deprecated".to_string(),
            range: Range {
                bytes: 160..174,
                start_point: Point { row: 5, col: 4 },
                end_point: Point { row: 5, col: 18 },
            },
        };

        let mut report_old = Vec::new();
        let mut report_new = Vec::new();

        let () =
            report_terminal(&m, code.as_bytes(), Path::new("<stdin>"), &mut report_old).unwrap();
        let () = report_terminal_opts(
            &m,
            code.as_bytes(),
            Path::new("<stdin>"),
            &Opts::default(),
            &mut report_new,
        )
        .unwrap();

        assert_eq!(report_old, report_new);
    }

    /// Test `report_terminal_opts` with extra context lines.
    #[test]
    fn report_terminal_opts_with_context() {
        let code = indoc! { r#"
            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 m = LintMatch {
            lint_name: "probe-read".to_string(),
            message: "bpf_probe_read() is deprecated".to_string(),
            range: Range {
                bytes: 160..174,
                start_point: Point { row: 5, col: 4 },
                end_point: Point { row: 5, col: 18 },
            },
        };
        let mut report = Vec::new();
        let () = report_terminal_opts(
            &m,
            code.as_bytes(),
            Path::new("<stdin>"),
            &Opts {
                extra_lines: (2, 1),
                ..Default::default()
            },
            &mut report,
        )
        .unwrap();
        let report = String::from_utf8(report).unwrap();

        let expected = indoc! { r#"
            warning: [probe-read] bpf_probe_read() is deprecated
              --> <stdin>:5:4
              | 
            3 |     struct task_struct *prev = (struct task_struct *)ctx[1];
            4 |     struct event event = {0};
            5 |     bpf_probe_read(event.comm, TASK_COMM_LEN, prev->comm);
              |     ^^^^^^^^^^^^^^
            6 |     return 0;
              | 
        "# };
        assert_eq!(report, expected);
    }

    /// Test context lines with multi-line matches.
    #[test]
    fn report_terminal_opts_multiline_with_context() {
        let code = indoc! { r#"
            SEC("tp_btf/sched_switch")
            int handle__sched_switch(u64 *ctx) {
                bpf_probe_read(
                  event.comm,
                  TASK_COMM_LEN,
                  prev->comm);
                return 0;
            }
        "# };

        let m = LintMatch {
            lint_name: "probe-read".to_string(),
            message: "bpf_probe_read() is deprecated".to_string(),
            range: Range {
                bytes: 68..140,
                start_point: Point { row: 2, col: 4 },
                end_point: Point { row: 5, col: 17 },
            },
        };
        let mut report = Vec::new();
        let () = report_terminal_opts(
            &m,
            code.as_bytes(),
            Path::new("<stdin>"),
            &Opts {
                extra_lines: (1, 1),
                ..Default::default()
            },
            &mut report,
        )
        .unwrap();
        let report = String::from_utf8(report).unwrap();

        let expected = indoc! { r#"
            warning: [probe-read] bpf_probe_read() is deprecated
              --> <stdin>:2:4
              | 
            1 | int handle__sched_switch(u64 *ctx) {
            2 |  /     bpf_probe_read(
            3 |  |       event.comm,
            4 |  |       TASK_COMM_LEN,
            5 |  |       prev->comm);
              |  |_________________^
            6 |     return 0;
              | 
        "# };
        assert_eq!(report, expected);
    }

    /// Test context lines when there aren't enough lines before the error.
    #[test]
    fn report_terminal_opts_insufficient_context_before() {
        let code = indoc! { r#"
            SEC("kprobe/test")
            int handle__test(void)
            {
            }
        "# };

        let m = LintMatch {
            lint_name: "unstable-attach-point".to_string(),
            message: "kprobe/kretprobe/fentry/fexit are unstable".to_string(),
            range: Range {
                bytes: 4..17,
                start_point: Point { row: 0, col: 4 },
                end_point: Point { row: 0, col: 17 },
            },
        };
        let mut report = Vec::new();
        let () = report_terminal_opts(
            &m,
            code.as_bytes(),
            Path::new("<stdin>"),
            &Opts {
                extra_lines: (5, 2),
                ..Default::default()
            },
            &mut report,
        )
        .unwrap();
        let report = String::from_utf8(report).unwrap();

        let expected = indoc! { r#"
            warning: [unstable-attach-point] kprobe/kretprobe/fentry/fexit are unstable
              --> <stdin>:0:4
              | 
            0 | SEC("kprobe/test")
              |     ^^^^^^^^^^^^^
            1 | int handle__test(void)
            2 | {
              | 
        "# };
        assert_eq!(report, expected);
    }

    /// Test context lines when there aren't enough lines after the error.
    #[test]
    fn report_terminal_opts_insufficient_context_after() {
        let code = indoc! { r#"
            SEC("tp_btf/sched_switch")
            int handle__sched_switch(u64 *ctx)
            {
                bpf_probe_read(event.comm, TASK_COMM_LEN, prev->comm);
            }
        "# };

        let m = LintMatch {
            lint_name: "probe-read".to_string(),
            message: "bpf_probe_read() is deprecated".to_string(),
            range: Range {
                bytes: 68..82,
                start_point: Point { row: 3, col: 4 },
                end_point: Point { row: 3, col: 18 },
            },
        };
        let mut report = Vec::new();
        let () = report_terminal_opts(
            &m,
            code.as_bytes(),
            Path::new("<stdin>"),
            &Opts {
                extra_lines: (1, 5),
                ..Default::default()
            },
            &mut report,
        )
        .unwrap();
        let report = String::from_utf8(report).unwrap();

        let expected = indoc! { r#"
            warning: [probe-read] bpf_probe_read() is deprecated
              --> <stdin>:3:4
              | 
            2 | {
            3 |     bpf_probe_read(event.comm, TASK_COMM_LEN, prev->comm);
              |     ^^^^^^^^^^^^^^
            4 | }
              | 
        "# };
        assert_eq!(report, expected);
    }
}