Branch data Line data Source code
1 : : /* SPDX-License-Identifier: GPL-2.0-only */
2 : : /*
3 : : * Copyright (c) 2022 Meta Platforms, Inc. and affiliates.
4 : : */
5 : :
6 : : #include "bpfilter/dump.h"
7 : :
8 : : #include <stddef.h>
9 : : #include <stdio.h>
10 : : #include <string.h>
11 : :
12 : : #define BF_DUMP_HEXDUMP_LEN 8
13 : : #define BF_DUMP_TOKEN_LEN 5
14 : :
15 : 522 : void bf_dump_prefix_push(prefix_t *prefix)
16 : : {
17 : : char *_prefix;
18 : : size_t len;
19 : :
20 : : assert(prefix);
21 : :
22 : : _prefix = *prefix;
23 : 522 : len = strlen(_prefix);
24 : :
25 [ + + ]: 522 : if (len) {
26 : : /* If the prefix string is not empty, then we need to either
27 : : * continue the previous branch (with a pipe), or remove
28 : : * it altogether if it stopped. */
29 [ + + ]: 415 : strncpy(&_prefix[len - 4], _prefix[len - 4] == '`' ? " " : "| ",
30 : : BF_DUMP_TOKEN_LEN);
31 : : }
32 : :
33 [ + + ]: 415 : if (len + BF_DUMP_TOKEN_LEN > DUMP_PREFIX_LEN)
34 : : return;
35 : :
36 : 473 : strncpy(&_prefix[len], "|-- ", BF_DUMP_TOKEN_LEN);
37 : : }
38 : :
39 : 211 : prefix_t *bf_dump_prefix_last(prefix_t *prefix)
40 : : {
41 : : char *_prefix;
42 : : size_t len;
43 : :
44 : : assert(prefix);
45 : :
46 : : _prefix = *prefix;
47 : 211 : len = strlen(_prefix);
48 : :
49 [ + + ]: 211 : if (len)
50 : 208 : strncpy(&_prefix[len - 4], "`-- ", BF_DUMP_TOKEN_LEN);
51 : :
52 : 211 : return prefix;
53 : : }
54 : :
55 : 459 : void bf_dump_prefix_pop(prefix_t *prefix)
56 : : {
57 : : char *_prefix;
58 : : size_t len;
59 : :
60 : : assert(prefix);
61 : :
62 : : _prefix = *prefix;
63 : 459 : len = strlen(_prefix);
64 : :
65 [ + + ]: 459 : if (!len)
66 : : return;
67 : :
68 : 458 : _prefix[len - 4] = '\0';
69 : :
70 : : // Ensure we have a branch to the next item.
71 [ + + ]: 458 : if (len - 4)
72 : 352 : strncpy(&_prefix[len - 8], "|-- ", BF_DUMP_TOKEN_LEN);
73 : : }
74 : :
75 : 106 : void bf_dump_hex(prefix_t *prefix, const void *data, size_t len)
76 : : {
77 : : // 5 characters per byte (0x%02x) + 1 for the null terminator.
78 : : char buf[(BF_DUMP_HEXDUMP_LEN * BF_DUMP_TOKEN_LEN) + 1];
79 : 106 : const void *end = data + len;
80 : :
81 : : assert(prefix);
82 : : assert(data);
83 : :
84 [ + + ]: 390 : while (data < end) {
85 : : char *line = buf;
86 [ + + ]: 2201 : for (size_t i = 0; i < BF_DUMP_HEXDUMP_LEN && data < end; ++i, ++data)
87 : 1917 : line += sprintf(line, "0x%02x ", *(unsigned char *)data);
88 : :
89 [ + + + + ]: 284 : DUMP((data == end ? bf_dump_prefix_last(prefix) : prefix), "%s", buf);
90 : : }
91 : 106 : }
|