• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Alan-Jowett / ebpf-verifier / 22120002931

17 Feb 2026 11:32PM UTC coverage: 87.654% (+0.5%) from 87.142%
22120002931

Pull #161

github

web-flow
Merge 2680038c5 into 3745b88ec
Pull Request #161: Failure slice

531 of 682 new or added lines in 8 files covered. (77.86%)

1 existing line in 1 file now uncovered.

9975 of 11380 relevant lines covered (87.65%)

2867868.35 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

58.92
/src/printing.cpp
1
// Copyright (c) Prevail Verifier contributors.
2
// SPDX-License-Identifier: MIT
3
#include <algorithm>
4
#include <fstream>
5
#include <iomanip>
6
#include <iostream>
7
#include <variant>
8
#include <vector>
9

10
#include "arith/num_big.hpp"
11
#include "arith/variable.hpp"
12
#include "cfg/cfg.hpp"
13
#include "crab/interval.hpp"
14
#include "crab/type_encoding.hpp"
15
#include "crab/var_registry.hpp"
16
#include "ir/syntax.hpp"
17
#include "platform.hpp"
18
#include "spec/function_prototypes.hpp"
19
#include "verifier.hpp"
20

21
using std::optional;
22
using std::string;
23
using std::vector;
24

25
namespace prevail {
26

27
std::ostream& operator<<(std::ostream& o, const Interval& interval) {
720✔
28
    if (interval.is_bottom()) {
720✔
29
        o << "_|_";
×
30
    } else {
31
        o << "[" << interval._lb << ", " << interval._ub << "]";
720✔
32
    }
33
    return o;
720✔
34
}
35
static std::string int128_to_string(Int128 n) {
314,468✔
36
    if (n == 0) {
314,468✔
37
        return "0";
1,224✔
38
    }
39
    bool negative = false;
313,652✔
40
    if (n < 0) {
313,652✔
41
        negative = true;
420✔
42
        // Handle kInt128Min: negate via unsigned to avoid overflow.
43
        if (n == kInt128Min) {
420✔
44
            // kInt128Min == -170141183460469231731687303715884105728
45
            // Build the string for the absolute value via unsigned arithmetic.
46
            auto u = static_cast<UInt128>(n);
×
47
            // Two's complement: UInt128(kInt128Min) is the correct magnitude.
48
            std::string result;
×
49
            while (u != 0) {
×
50
                result += static_cast<char>('0' + static_cast<int>(u % 10));
×
51
                u /= 10;
×
52
            }
53
            result += '-';
×
54
            std::ranges::reverse(result);
×
55
            return result;
×
56
        }
×
57
        n = -n;
420✔
58
    }
59
    std::string result;
313,652✔
60
    while (n > 0) {
1,567,408✔
61
        result += static_cast<char>('0' + static_cast<int>(n % 10));
1,253,756✔
62
        n /= 10;
1,253,756✔
63
    }
64
    if (negative) {
313,652✔
65
        result += '-';
420✔
66
    }
67
    std::ranges::reverse(result);
313,652✔
68
    return result;
313,652✔
69
}
313,652✔
70

71
std::ostream& operator<<(std::ostream& o, const Number& z) { return o << z.to_string(); }
314,468✔
72

73
std::string Number::to_string() const { return int128_to_string(_n); }
314,468✔
74

75
std::string Interval::to_string() const {
×
76
    std::ostringstream s;
×
77
    s << *this;
×
78
    return s.str();
×
79
}
×
80

81
std::ostream& operator<<(std::ostream& os, const Label& label) {
1,650✔
82
    if (label == Label::entry) {
1,650✔
83
        return os << "entry";
6✔
84
    }
85
    if (label == Label::exit) {
1,644✔
86
        return os << "exit";
10✔
87
    }
88
    if (!label.stack_frame_prefix.empty()) {
1,634✔
89
        os << label.stack_frame_prefix << STACK_FRAME_DELIMITER;
330✔
90
    }
91
    os << label.from;
1,634✔
92
    if (label.to != -1) {
1,634✔
93
        os << ":" << label.to;
50✔
94
    }
95
    if (!label.special_label.empty()) {
1,634✔
96
        os << " (" << label.special_label << ")";
22✔
97
    }
98
    return os;
817✔
99
}
100

101
string to_string(Label const& label) {
1,270✔
102
    std::stringstream str;
1,270✔
103
    str << label;
1,270✔
104
    return str.str();
2,540✔
105
}
1,270✔
106

107
struct LineInfoPrinter {
1✔
108
    std::ostream& os;
109
    std::string previous_source_line;
110

111
    void print_line_info(const Label& label) {
6✔
112
        if (thread_local_options.verbosity_opts.print_line_info) {
6✔
113
            const auto& line_info_map = thread_local_program_info.get().line_info;
×
114
            const auto& line_info = line_info_map.find(label.from);
×
115
            // Print line info only once.
116
            if (line_info != line_info_map.end() && line_info->second.source_line != previous_source_line) {
×
117
                os << "\n" << line_info->second << "\n";
×
118
                previous_source_line = line_info->second.source_line;
×
119
            }
120
        }
121
    }
6✔
122
};
123

124
struct DetailedPrinter : LineInfoPrinter {
125
    const Program& prog;
126

127
    DetailedPrinter(std::ostream& os, const Program& prog) : LineInfoPrinter{os}, prog(prog) {}
2✔
128

129
    void print_labels(const std::string& direction, const std::set<Label>& labels) {
6✔
130
        auto [it, et] = std::pair{labels.begin(), labels.end()};
6✔
131
        if (it != et) {
6✔
132
            os << "  " << direction << " ";
6✔
133
            while (it != et) {
12✔
134
                os << *it;
6✔
135
                ++it;
6✔
136
                if (it == et) {
6✔
137
                    os << ";";
6✔
138
                } else {
139
                    os << ",";
×
140
                }
141
            }
142
        }
143
        os << "\n";
6✔
144
    }
6✔
145

146
    void print_jump(const std::string& direction, const Label& label) {
6✔
147
        print_labels(direction, direction == "from" ? prog.cfg().parents_of(label) : prog.cfg().children_of(label));
6✔
148
    }
6✔
149

150
    void print_instruction(const Program& prog, const Label& label) {
×
151
        for (const auto& pre : prog.assertions_at(label)) {
×
152
            os << "  " << "assert " << pre << ";\n";
×
153
        }
×
154
        os << "  " << prog.instruction_at(label) << ";\n";
×
155
    }
×
156
};
157

158
void print_program(const Program& prog, std::ostream& os, const bool simplify) {
×
159
    DetailedPrinter printer{os, prog};
×
160
    for (const BasicBlock& bb : BasicBlock::collect_basic_blocks(prog.cfg(), simplify)) {
×
161
        printer.print_jump("from", bb.first_label());
×
162
        os << bb.first_label() << ":\n";
×
163
        for (const Label& label : bb) {
×
164
            printer.print_line_info(label);
×
165
            printer.print_instruction(prog, label);
×
166
        }
167
        printer.print_jump("goto", bb.last_label());
×
168
    }
×
169
    os << "\n";
×
170
}
×
171

172
void print_invariants(std::ostream& os, const Program& prog, const bool simplify, const AnalysisResult& result) {
×
173
    DetailedPrinter printer{os, prog};
×
174
    for (const BasicBlock& bb : BasicBlock::collect_basic_blocks(prog.cfg(), simplify)) {
×
175
        if (result.invariants.at(bb.first_label()).pre.is_bottom()) {
×
176
            continue;
×
177
        }
178
        os << "\nPre-invariant : " << result.invariants.at(bb.first_label()).pre << "\n";
×
179
        printer.print_jump("from", bb.first_label());
×
180
        os << bb.first_label() << ":\n";
×
181
        Label last_label = bb.first_label();
×
182
        for (const Label& label : bb) {
×
183
            printer.print_line_info(label);
×
184
            printer.print_instruction(prog, label);
×
185
            last_label = label;
×
186

187
            const auto& current = result.invariants.at(last_label);
×
188
            if (current.error) {
×
189
                os << "\nVerification error:\n";
×
190
                if (label != bb.last_label()) {
×
191
                    os << "After " << current.pre << "\n";
×
192
                }
193
                print_error(os, *current.error);
×
194
                os << "\n";
×
195
                return;
×
196
            }
197
        }
198
        const auto& current = result.invariants.at(last_label);
×
199
        if (!current.post.is_bottom()) {
×
200
            printer.print_jump("goto", last_label);
×
201
            os << "\nPost-invariant : " << current.post << "\n";
×
202
        }
203
    }
×
204
    os << "\n";
×
205
}
×
206

207
void print_dot(const Program& prog, std::ostream& out) {
×
208
    out << "digraph program {\n";
×
209
    out << "    node [shape = rectangle];\n";
×
210
    for (const auto& label : prog.labels()) {
×
211
        out << "    \"" << label << "\"[xlabel=\"" << label << "\",label=\"";
×
212

213
        for (const auto& pre : prog.assertions_at(label)) {
×
214
            out << "assert " << pre << "\\l";
×
215
        }
×
216
        out << prog.instruction_at(label) << "\\l";
×
217

218
        out << "\"];\n";
×
219
        for (const Label& next : prog.cfg().children_of(label)) {
×
220
            out << "    \"" << label << "\" -> \"" << next << "\";\n";
×
221
        }
222
        out << "\n";
×
223
    }
224
    out << "}\n";
×
225
}
×
226

227
void print_dot(const Program& prog, const std::string& outfile) {
×
228
    std::ofstream out{outfile};
×
229
    if (out.fail()) {
×
230
        throw std::runtime_error(std::string("Could not open file ") + outfile);
×
231
    }
232
    print_dot(prog, out);
×
233
}
×
234

235
void print_unreachable(std::ostream& os, const Program& prog, const AnalysisResult& result) {
×
236
    for (const auto& [label, notes] : result.find_unreachable(prog)) {
×
237
        for (const auto& msg : notes) {
×
238
            os << label << ": " << msg << "\n";
×
239
        }
240
    }
×
241
    os << "\n";
×
242
}
×
243

244
std::string to_string(const VerificationError& error) {
316✔
245
    std::stringstream ss;
316✔
246
    if (const auto& label = error.where) {
316✔
247
        ss << *label << ": ";
316✔
248
    }
249
    ss << error.what();
316✔
250
    return ss.str();
632✔
251
}
316✔
252

253
void print_error(std::ostream& os, const VerificationError& error) {
2✔
254
    LineInfoPrinter printer{os};
2✔
255
    if (const auto& label = error.where) {
2✔
256
        printer.print_line_info(*label);
2✔
257
        os << *label << ": ";
2✔
258
    }
259
    os << error.what() << "\n";
2✔
260
    os << "\n";
2✔
261
}
2✔
262

263
std::ostream& operator<<(std::ostream& os, const ArgSingle::Kind kind) {
74✔
264
    switch (kind) {
74✔
265
    case ArgSingle::Kind::ANYTHING: return os << "uint64_t";
14✔
266
    case ArgSingle::Kind::PTR_TO_CTX: return os << "ctx";
4✔
267
    case ArgSingle::Kind::PTR_TO_STACK: return os << "stack";
×
268
    case ArgSingle::Kind::MAP_FD: return os << "map_fd";
24✔
269
    case ArgSingle::Kind::MAP_FD_PROGRAMS: return os << "map_fd_programs";
×
270
    case ArgSingle::Kind::PTR_TO_MAP_KEY: return os << "map_key";
24✔
271
    case ArgSingle::Kind::PTR_TO_MAP_VALUE: return os << "map_value";
8✔
272
    }
273
    assert(false);
274
    return os;
275
}
276

277
std::ostream& operator<<(std::ostream& os, const ArgPair::Kind kind) {
×
278
    switch (kind) {
×
279
    case ArgPair::Kind::PTR_TO_READABLE_MEM: return os << "mem";
×
280
    case ArgPair::Kind::PTR_TO_WRITABLE_MEM: return os << "out";
×
281
    }
282
    assert(false);
283
    return os;
284
}
285

286
std::ostream& operator<<(std::ostream& os, const ArgSingle arg) {
74✔
287
    os << arg.kind;
74✔
288
    if (arg.or_null) {
74✔
289
        os << "?";
×
290
    }
291
    os << " " << arg.reg;
74✔
292
    return os;
74✔
293
}
294

295
std::ostream& operator<<(std::ostream& os, const ArgPair arg) {
×
296
    os << arg.kind;
×
297
    if (arg.or_null) {
×
298
        os << "?";
×
299
    }
300
    os << " " << arg.mem << "[" << arg.size;
×
301
    if (arg.can_be_zero) {
×
302
        os << "?";
×
303
    }
304
    os << "], uint64_t " << arg.size;
×
305
    return os;
×
306
}
307

308
std::ostream& operator<<(std::ostream& os, const Bin::Op op) {
280✔
309
    using Op = Bin::Op;
140✔
310
    switch (op) {
280✔
311
    case Op::MOV: return os;
81✔
312
    case Op::MOVSX8: return os << "s8";
×
313
    case Op::MOVSX16: return os << "s16";
×
314
    case Op::MOVSX32: return os << "s32";
×
315
    case Op::ADD: return os << "+";
72✔
316
    case Op::SUB: return os << "-";
×
317
    case Op::MUL: return os << "*";
×
318
    case Op::UDIV: return os << "/";
×
319
    case Op::SDIV: return os << "s/";
×
320
    case Op::UMOD: return os << "%";
×
321
    case Op::SMOD: return os << "s%";
×
322
    case Op::OR: return os << "|";
×
323
    case Op::AND: return os << "&";
30✔
324
    case Op::LSH: return os << "<<";
12✔
325
    case Op::RSH: return os << ">>";
×
326
    case Op::ARSH: return os << ">>>";
2✔
327
    case Op::XOR: return os << "^";
2✔
328
    }
329
    assert(false);
330
    return os;
331
}
332

333
std::ostream& operator<<(std::ostream& os, const Condition::Op op) {
222✔
334
    using Op = Condition::Op;
111✔
335
    switch (op) {
222✔
336
    case Op::EQ: return os << "==";
38✔
337
    case Op::NE: return os << "!=";
10✔
338
    case Op::SET: return os << "&==";
×
339
    case Op::NSET: return os << "&!="; // not in ebpf
×
340
    case Op::LT: return os << "<";     // TODO: os << "u<";
124✔
341
    case Op::LE: return os << "<=";    // TODO: os << "u<=";
12✔
342
    case Op::GT: return os << ">";     // TODO: os << "u>";
22✔
343
    case Op::GE: return os << ">=";    // TODO: os << "u>=";
6✔
344
    case Op::SLT: return os << "s<";
4✔
345
    case Op::SLE: return os << "s<=";
×
346
    case Op::SGT: return os << "s>";
4✔
347
    case Op::SGE: return os << "s>=";
2✔
348
    }
349
    assert(false);
350
    return os;
351
}
352

353
static string size(const int w, const bool is_signed = false) {
184✔
354
    return string(is_signed ? "s" : "u") + std::to_string(w * 8);
552✔
355
}
356

357
// ReSharper disable CppMemberFunctionMayBeConst
358
struct AssertionPrinterVisitor {
359
    std::ostream& _os;
360

361
    void operator()(ValidStore const& a) {
2✔
362
        _os << a.mem << ".type != stack -> " << TypeConstraint{a.val, TypeGroup::number};
2✔
363
    }
2✔
364

365
    void operator()(ValidAccess const& a) {
318✔
366
        if (a.or_null) {
318✔
367
            _os << "(" << TypeConstraint{a.reg, TypeGroup::number} << " and " << a.reg << ".value == 0) or ";
4✔
368
        }
369
        _os << "valid_access(" << a.reg << ".offset";
318✔
370
        if (a.offset > 0) {
318✔
371
            _os << "+" << a.offset;
46✔
372
        } else if (a.offset < 0) {
272✔
373
            _os << a.offset;
6✔
374
        }
375

376
        if (a.width == Value{Imm{0}}) {
318✔
377
            // a.width == 0, meaning we only care it's an in-bound pointer,
378
            // so it can be compared with another pointer to the same region.
379
            _os << ") for comparison/subtraction";
4✔
380
        } else {
381
            _os << ", width=" << a.width << ") for ";
314✔
382
            if (a.access_type == AccessType::read) {
314✔
383
                _os << "read";
278✔
384
            } else {
385
                _os << "write";
36✔
386
            }
387
        }
388
    }
318✔
389

390
    void operator()(const BoundedLoopCount& a) {
22✔
391
        _os << variable_registry->loop_counter(to_string(a.name)) << " < " << BoundedLoopCount::limit;
22✔
392
    }
22✔
393

394
    void operator()(ValidSize const& a) {
2✔
395
        const auto op = a.can_be_zero ? " >= " : " > ";
2✔
396
        _os << a.reg << ".value" << op << 0;
2✔
397
    }
2✔
398

399
    void operator()(ValidCall const& a) {
2✔
400
        const EbpfHelperPrototype proto = thread_local_program_info->platform->get_helper_prototype(a.func);
2✔
401
        _os << "valid call(" << proto.name << ")";
2✔
402
    }
2✔
403

404
    void operator()(ValidMapKeyValue const& a) {
42✔
405
        _os << "within(" << a.access_reg << ":" << (a.key ? "key_size" : "value_size") << "(" << a.map_fd_reg << "))";
51✔
406
    }
42✔
407

408
    void operator()(ZeroCtxOffset const& a) {
2✔
409
        _os << variable_registry->reg(DataKind::ctx_offsets, a.reg.v) << " == 0";
2✔
410
    }
2✔
411

412
    void operator()(Comparable const& a) {
10✔
413
        if (a.or_r2_is_number) {
10✔
414
            _os << TypeConstraint{a.r2, TypeGroup::number} << " or ";
15✔
415
        }
416
        _os << variable_registry->type_reg(a.r1.v) << " == " << variable_registry->type_reg(a.r2.v) << " in "
10✔
417
            << TypeGroup::singleton_ptr;
10✔
418
    }
10✔
419

420
    void operator()(Addable const& a) {
2✔
421
        _os << TypeConstraint{a.ptr, TypeGroup::pointer} << " -> " << TypeConstraint{a.num, TypeGroup::number};
4✔
422
    }
2✔
423

424
    void operator()(ValidDivisor const& a) { _os << a.reg << " != 0"; }
76✔
425

426
    void operator()(TypeConstraint const& tc) {
220✔
427
        const string cmp_op = is_singleton_type(tc.types) ? "==" : "in";
239✔
428
        _os << variable_registry->type_reg(tc.reg.v) << " " << cmp_op << " " << tc.types;
220✔
429
    }
220✔
430

431
    void operator()(FuncConstraint const& fc) { _os << variable_registry->type_reg(fc.reg.v) << " is helper"; }
6✔
432
};
433

434
// ReSharper disable CppMemberFunctionMayBeConst
435
struct CommandPrinterVisitor {
436
    std::ostream& os_;
437

438
    void visit(const auto& item) { std::visit(*this, item); }
439

440
    void operator()(Undefined const& a) { os_ << "Undefined{" << a.opcode << "}"; }
×
441

442
    void operator()(LoadMapFd const& b) { os_ << b.dst << " = map_fd " << b.mapfd; }
26✔
443

444
    void operator()(LoadMapAddress const& b) { os_ << b.dst << " = map_val(" << b.mapfd << ") + " << b.offset; }
×
445

446
    void operator()(LoadPseudo const& b) {
×
447
        os_ << b.dst << " = ";
×
448
        switch (b.addr.kind) {
×
449
        case PseudoAddress::Kind::VARIABLE_ADDR: os_ << "variable_addr(" << b.addr.imm << ")"; break;
×
450
        case PseudoAddress::Kind::CODE_ADDR: os_ << "code_addr(" << b.addr.imm << ")"; break;
×
451
        case PseudoAddress::Kind::MAP_BY_IDX: os_ << "map_by_idx(" << b.addr.imm << ")"; break;
×
452
        case PseudoAddress::Kind::MAP_VALUE_BY_IDX:
×
453
            os_ << "mva(map_by_idx(" << b.addr.imm << ")) + " << b.addr.next_imm;
×
454
            break;
×
455
        }
456
    }
×
457

458
    // llvm-objdump uses "w<number>" for 32-bit operations and "r<number>" for 64-bit operations.
459
    // We use the same convention here for consistency.
460
    static std::string reg_name(Reg const& a, const bool is64) { return ((is64) ? "r" : "w") + std::to_string(a.v); }
420✔
461

462
    void operator()(Bin const& b) {
280✔
463
        os_ << reg_name(b.dst, b.is64) << " " << b.op << "= " << b.v;
420✔
464
        if (b.lddw) {
280✔
465
            os_ << " ll";
2✔
466
        }
467
    }
280✔
468

469
    void operator()(Un const& b) {
12✔
470
        os_ << b.dst << " = ";
12✔
471
        switch (b.op) {
12✔
472
        case Un::Op::BE16: os_ << "be16 "; break;
2✔
473
        case Un::Op::BE32: os_ << "be32 "; break;
2✔
474
        case Un::Op::BE64: os_ << "be64 "; break;
2✔
475
        case Un::Op::LE16: os_ << "le16 "; break;
2✔
476
        case Un::Op::LE32: os_ << "le32 "; break;
2✔
477
        case Un::Op::LE64: os_ << "le64 "; break;
2✔
478
        case Un::Op::SWAP16: os_ << "swap16 "; break;
×
479
        case Un::Op::SWAP32: os_ << "swap32 "; break;
×
480
        case Un::Op::SWAP64: os_ << "swap64 "; break;
×
481
        case Un::Op::NEG: os_ << "-"; break;
×
482
        }
483
        os_ << b.dst;
12✔
484
    }
12✔
485

486
    void operator()(Call const& call) {
70✔
487
        os_ << "r0 = " << call.name << ":" << call.func << "(";
70✔
488
        for (uint8_t r = 1; r <= 5; r++) {
144✔
489
            // Look for a singleton.
490
            auto single = std::ranges::find_if(call.singles, [r](const ArgSingle arg) { return arg.reg.v == r; });
372✔
491
            if (single != call.singles.end()) {
144✔
492
                if (r > 1) {
74✔
493
                    os_ << ", ";
48✔
494
                }
495
                os_ << *single;
74✔
496
                continue;
74✔
497
            }
498

499
            // Look for the start of a pair.
500
            auto pair = std::ranges::find_if(call.pairs, [r](const ArgPair arg) { return arg.mem.v == r; });
70✔
501
            if (pair != call.pairs.end()) {
70✔
502
                if (r > 1) {
×
503
                    os_ << ", ";
×
504
                }
505
                os_ << *pair;
×
506
                r++;
×
507
                continue;
×
508
            }
509

510
            // Not found.
511
            break;
70✔
512
        }
513
        os_ << ")";
70✔
514
    }
70✔
515

516
    void operator()(CallLocal const& call) { os_ << "call <" << to_string(call.target) << ">"; }
×
517

518
    void operator()(Callx const& callx) { os_ << "callx " << callx.func; }
×
519

520
    void operator()(CallBtf const& call) { os_ << "call_btf " << call.btf_id; }
×
521

522
    void operator()(Exit const& b) { os_ << "exit"; }
50✔
523

524
    void operator()(Jmp const& b) {
×
525
        // A "standalone" jump Instruction.
526
        // Print the label without offset calculations.
527
        if (b.cond) {
×
528
            os_ << "if ";
×
529
            print(*b.cond);
×
530
            os_ << " ";
×
531
        }
532
        os_ << "goto label <" << to_string(b.target) << ">";
×
533
    }
×
534

535
    void operator()(Jmp const& b, const int offset) {
54✔
536
        const string sign = offset > 0 ? "+" : "";
54✔
537
        const string target = sign + std::to_string(offset) + " <" + to_string(b.target) + ">";
108✔
538

539
        if (b.cond) {
54✔
540
            os_ << "if ";
40✔
541
            print(*b.cond);
40✔
542
            os_ << " ";
40✔
543
        }
544
        os_ << "goto " << target;
54✔
545
    }
54✔
546

547
    void operator()(Packet const& b) {
×
548
        /* Direct packet access, R0 = *(uint *) (skb->data + imm32) */
549
        /* Indirect packet access, R0 = *(uint *) (skb->data + src_reg + imm32) */
550
        const string s = size(b.width);
×
551
        os_ << "r0 = ";
×
552
        os_ << "*(" << s << " *)skb[";
×
553
        if (b.regoffset) {
×
554
            os_ << *b.regoffset;
×
555
        }
556
        if (b.offset != 0) {
×
557
            if (b.regoffset) {
×
558
                os_ << " + ";
×
559
            }
560
            os_ << b.offset;
×
561
        }
562
        os_ << "]";
×
563
    }
×
564

565
    void print(Deref const& access) {
184✔
566
        const string sign = access.offset < 0 ? " - " : " + ";
212✔
567
        const int offset = std::abs(access.offset); // what about INT_MIN?
184✔
568
        os_ << "*(" << size(access.width) << " *)";
276✔
569
        os_ << "(" << access.basereg << sign << offset << ")";
184✔
570
    }
184✔
571

572
    void print(Condition const& cond) {
222✔
573
        os_ << cond.left << " " << ((!cond.is64) ? "w" : "") << cond.op << " " << cond.right;
261✔
574
    }
222✔
575

576
    void operator()(Mem const& b) {
184✔
577
        if (b.is_load) {
184✔
578
            os_ << b.value << " = ";
44✔
579
        }
580
        if (b.is_load && b.is_signed) {
184✔
581
            const string sign = b.access.offset < 0 ? " - " : " + ";
×
582
            const int offset = std::abs(b.access.offset);
×
583
            os_ << "*(" << size(b.access.width, true) << " *)";
×
584
            os_ << "(" << b.access.basereg << sign << offset << ")";
×
585
        } else {
×
586
            print(b.access);
184✔
587
        }
588
        if (!b.is_load) {
184✔
589
            os_ << " = " << b.value;
140✔
590
        }
591
    }
184✔
592

593
    void operator()(Atomic const& b) {
×
594
        os_ << "lock ";
×
595
        print(b.access);
×
596
        os_ << " ";
×
597
        bool showfetch = true;
×
598
        switch (b.op) {
×
599
        case Atomic::Op::ADD: os_ << "+"; break;
×
600
        case Atomic::Op::OR: os_ << "|"; break;
×
601
        case Atomic::Op::AND: os_ << "&"; break;
×
602
        case Atomic::Op::XOR: os_ << "^"; break;
×
603
        case Atomic::Op::XCHG:
×
604
            os_ << "x";
×
605
            showfetch = false;
×
606
            break;
×
607
        case Atomic::Op::CMPXCHG:
×
608
            os_ << "cx";
×
609
            showfetch = false;
×
610
            break;
×
611
        }
612
        os_ << "= " << b.valreg;
×
613

614
        if (showfetch && b.fetch) {
×
615
            os_ << " fetch";
×
616
        }
617
    }
×
618

619
    void operator()(Assume const& b) {
182✔
620
        os_ << "assume ";
182✔
621
        print(b.cond);
182✔
622
    }
182✔
623

624
    void operator()(IncrementLoopCounter const& a) {
×
625
        os_ << variable_registry->loop_counter(to_string(a.name)) << "++";
×
626
    }
×
627
};
628
// ReSharper restore CppMemberFunctionMayBeConst
629

630
std::ostream& operator<<(std::ostream& os, Instruction const& ins) {
188✔
631
    std::visit(CommandPrinterVisitor{os}, ins);
94✔
632
    return os;
94✔
633
}
634

635
string to_string(Instruction const& ins) {
184✔
636
    std::stringstream str;
184✔
637
    str << ins;
184✔
638
    return str.str();
368✔
639
}
184✔
640

641
std::ostream& operator<<(std::ostream& os, const Assertion& a) {
704✔
642
    std::visit(AssertionPrinterVisitor{os}, a);
361✔
643
    return os;
361✔
644
}
645

646
string to_string(Assertion const& constraint) {
684✔
647
    std::stringstream str;
684✔
648
    str << constraint;
684✔
649
    return str.str();
1,368✔
650
}
684✔
651

652
auto get_labels(const InstructionSeq& insts) {
38✔
653
    Pc pc = 0;
38✔
654
    std::map<Label, Pc> pc_of_label;
38✔
655
    for (const auto& [label, inst, _] : insts) {
708✔
656
        pc_of_label[label] = pc;
670✔
657
        pc += size(inst);
670✔
658
    }
659
    return pc_of_label;
38✔
660
}
×
661

662
void print(const InstructionSeq& insts, std::ostream& out, const std::optional<const Label>& label_to_print,
38✔
663
           const bool print_line_info) {
664
    const auto pc_of_label = get_labels(insts);
38✔
665
    Pc pc = 0;
38✔
666
    std::string previous_source;
38✔
667
    CommandPrinterVisitor visitor{out};
38✔
668
    for (const LabeledInstruction& labeled_inst : insts) {
708✔
669
        const auto& [label, ins, line_info] = labeled_inst;
670✔
670
        if (!label_to_print.has_value() || label == label_to_print) {
670✔
671
            if (line_info.has_value() && print_line_info) {
670✔
672
                auto& [file, source, line, column] = line_info.value();
×
673
                // Only decorate the first instruction associated with a source line.
674
                if (source != previous_source) {
×
675
                    out << line_info.value();
×
676
                    previous_source = source;
×
677
                }
678
            }
679
            if (label.isjump()) {
670✔
680
                out << "\n";
×
681
                out << label << ":\n";
×
682
            }
683
            if (label_to_print.has_value()) {
670✔
684
                out << pc << ": ";
×
685
            } else {
686
                out << std::setw(8) << pc << ":\t";
670✔
687
            }
688
            if (const auto jmp = std::get_if<Jmp>(&ins)) {
670✔
689
                if (!pc_of_label.contains(jmp->target)) {
54✔
690
                    throw std::runtime_error(string("Cannot find label ") + to_string(jmp->target));
×
691
                }
692
                const Pc target_pc = pc_of_label.at(jmp->target);
54✔
693
                visitor(*jmp, gsl::narrow<int>(target_pc) - static_cast<int>(pc) - 1);
54✔
694
            } else {
695
                std::visit(visitor, ins);
616✔
696
            }
697
            out << "\n";
670✔
698
        }
699
        pc += size(ins);
670✔
700
    }
701
}
38✔
702

703
std::ostream& operator<<(std::ostream& o, const EbpfMapDescriptor& desc) {
28✔
704
    return o << "(" << "original_fd = " << desc.original_fd << ", " << "inner_map_fd = " << desc.inner_map_fd << ", "
28✔
705
             << "type = " << desc.type << ", " << "max_entries = " << desc.max_entries << ", "
28✔
706
             << "value_size = " << desc.value_size << ", " << "key_size = " << desc.key_size << ")";
28✔
707
}
708

709
void print_map_descriptors(const std::vector<EbpfMapDescriptor>& descriptors, std::ostream& o) {
38✔
710
    int i = 0;
38✔
711
    for (const auto& desc : descriptors) {
66✔
712
        o << "map " << i << ":" << desc << "\n";
28✔
713
        i++;
28✔
714
    }
715
}
38✔
716

717
std::ostream& operator<<(std::ostream& os, const btf_line_info_t& line_info) {
×
718
    os << "; " << line_info.file_name << ":" << line_info.line_number << "\n";
×
719
    os << "; " << line_info.source_line << "\n";
×
720
    return os;
×
721
}
722

723
void print_invariants_filtered(std::ostream& os, const Program& prog, const bool simplify, const AnalysisResult& result,
2✔
724
                               const std::set<Label>& filter, const bool compact,
725
                               const std::map<Label, RelevantState>* relevance) {
726
    DetailedPrinter printer{os, prog};
2✔
727
    const auto basic_blocks = BasicBlock::collect_basic_blocks(prog.cfg(), simplify);
2✔
728

729
    // Build a mapping from each label in a basic block to the block's first label.
730
    // Needed to look up post-invariants for mid-block predecessor labels at join points.
731
    std::map<Label, Label> label_to_block_leader;
2✔
732
    for (const BasicBlock& bb : basic_blocks) {
28✔
733
        for (const Label& label : bb) {
52✔
734
            label_to_block_leader.insert({label, bb.first_label()});
52✔
735
        }
736
    }
737

738
    // Helper to look up the post-invariant for a predecessor label.
739
    // Mid-block labels don't have direct invariant entries, so we map
740
    // through the block leader to find the containing block's post-state.
741
    // Note: when simplify=true, the block leader's post represents the
742
    // entire collapsed block, which is correct for the last instruction
743
    // but approximate for mid-block predecessors. Failure slicing defaults
744
    // to simplify=false, so this approximation is rarely triggered.
745
    auto get_parent_post_invariant = [&](const Label& parent) -> const EbpfDomain* {
1✔
NEW
746
        const auto leader_it = label_to_block_leader.find(parent);
×
NEW
747
        const Label& lookup_label = (leader_it != label_to_block_leader.end()) ? leader_it->second : parent;
×
NEW
748
        const auto inv_it = result.invariants.find(lookup_label);
×
NEW
749
        if (inv_it != result.invariants.end() && !inv_it->second.post.is_bottom()) {
×
750
            return &inv_it->second.post;
751
        }
752
        return nullptr;
753
    };
2✔
754

755
    for (const BasicBlock& bb : basic_blocks) {
28✔
756
        // Check if any label in this basic block is in the filter
757
        bool bb_has_filtered_label = false;
26✔
758
        for (const Label& label : bb) {
48✔
759
            if (filter.contains(label)) {
26✔
760
                bb_has_filtered_label = true;
2✔
761
                break;
2✔
762
            }
763
        }
764
        if (!bb_has_filtered_label) {
26✔
765
            continue;
22✔
766
        }
767

768
        // Find the first filtered label in this block to use as the block header
769
        Label first_filtered_label = bb.first_label();
4✔
770
        for (const Label& label : bb) {
4✔
771
            if (filter.contains(label)) {
4✔
772
                first_filtered_label = label;
4✔
773
                break;
2✔
774
            }
775
        }
776

777
        // Use bb.first_label() for reachability check: if the block's entry is unreachable,
778
        // skip the entire block. The filtered label's pre-invariant is printed below.
779
        if (result.invariants.at(bb.first_label()).pre.is_bottom()) {
6✔
NEW
780
            continue;
×
781
        }
782

783
        // Print pre-invariant for first filtered label in block (unless compact)
784
        if (!compact) {
4✔
785
            // Set invariant filter if we have relevance info for this label
786
            const auto* label_relevance =
2✔
787
                relevance ? (relevance->contains(first_filtered_label) ? &relevance->at(first_filtered_label) : nullptr)
4✔
788
                          : nullptr;
4✔
789
            os << invariant_filter(label_relevance);
4✔
790
            os << "\nPre-invariant : " << result.invariants.at(first_filtered_label).pre << "\n";
4✔
791
            os << invariant_filter(nullptr); // Clear filter
4✔
792
        }
793

794
        // Print the jump and block header anchored to the basic block entry label
795
        // for correct CFG structure representation.
796
        printer.print_jump("from", bb.first_label());
10✔
797
        os << bb.first_label() << ":\n";
4✔
798

799
        // R3: Show per-predecessor invariants at join points.
800
        // When multiple predecessors exist and at least 2 are in the slice,
801
        // show what each incoming edge contributed to help diagnose lost correlations.
802
        if (!compact && relevance) {
4✔
803
            const auto parents = prog.cfg().parents_of(bb.first_label());
4✔
804
            std::vector<Label> in_slice_parents;
4✔
805
            for (const auto& parent : parents) {
8✔
806
                if (filter.contains(parent)) {
4✔
807
                    in_slice_parents.push_back(parent);
2✔
808
                }
809
            }
810
            if (in_slice_parents.size() >= 2) {
4✔
811
                // Build the union of relevant registers from this label and all in-slice parents
NEW
812
                RelevantState join_relevance;
×
NEW
813
                if (relevance->contains(first_filtered_label)) {
×
NEW
814
                    const auto& fl = relevance->at(first_filtered_label);
×
NEW
815
                    join_relevance.registers.insert(fl.registers.begin(), fl.registers.end());
×
NEW
816
                    join_relevance.stack_offsets.insert(fl.stack_offsets.begin(), fl.stack_offsets.end());
×
817
                }
NEW
818
                for (const auto& parent : in_slice_parents) {
×
NEW
819
                    if (relevance->contains(parent)) {
×
NEW
820
                        const auto& pr = relevance->at(parent);
×
NEW
821
                        join_relevance.registers.insert(pr.registers.begin(), pr.registers.end());
×
NEW
822
                        join_relevance.stack_offsets.insert(pr.stack_offsets.begin(), pr.stack_offsets.end());
×
823
                    }
824
                }
825

NEW
826
                os << "  --- join point: per-predecessor state ---\n";
×
NEW
827
                for (const auto& parent : in_slice_parents) {
×
NEW
828
                    const auto* post = get_parent_post_invariant(parent);
×
NEW
829
                    if (post) {
×
NEW
830
                        os << invariant_filter(&join_relevance);
×
NEW
831
                        os << "  from " << parent << ": " << *post << "\n";
×
NEW
832
                        os << invariant_filter(nullptr);
×
833
                    }
834
                }
NEW
835
                os << "  --- end join point ---\n";
×
NEW
836
            }
×
837
        }
4✔
838

839
        if (first_filtered_label != bb.first_label()) {
6✔
840
            // Indicate that some labels/instructions were skipped due to filtering.
NEW
841
            os << "  ... skipped ...\n";
×
842
        }
843

844
        Label last_label = bb.first_label();
4✔
845
        Label prev_filtered_label = bb.first_label();
4✔
846
        bool has_prev_filtered = false;
4✔
847
        for (const Label& label : bb) {
8✔
848
            if (!filter.contains(label)) {
4✔
NEW
849
                continue;
×
850
            }
851

852
            // If there was a gap since the previous filtered label in this block,
853
            // close the previous label's output and show a skip indicator.
854
            if (has_prev_filtered && prev_filtered_label != label) {
4✔
855
                // Print post-invariant and goto for the previous filtered label
NEW
856
                if (!compact) {
×
NEW
857
                    const auto& prev_current = result.invariants.at(prev_filtered_label);
×
NEW
858
                    if (!prev_current.post.is_bottom()) {
×
859
                        const auto* prev_label_relevance =
NEW
860
                            relevance ? (relevance->contains(prev_filtered_label) ? &relevance->at(prev_filtered_label)
×
861
                                                                                  : nullptr)
NEW
862
                                      : nullptr;
×
NEW
863
                        os << invariant_filter(prev_label_relevance);
×
NEW
864
                        printer.print_jump("goto", prev_filtered_label);
×
NEW
865
                        os << "\nPost-invariant : " << prev_current.post << "\n";
×
NEW
866
                        os << invariant_filter(nullptr);
×
867
                    }
868
                }
869
                // Check if there are skipped labels between prev and current
NEW
870
                bool has_gap = false;
×
NEW
871
                for (const Label& mid : bb) {
×
NEW
872
                    if (mid <= prev_filtered_label) {
×
NEW
873
                        continue;
×
874
                    }
NEW
875
                    if (mid >= label) {
×
876
                        break;
877
                    }
NEW
878
                    has_gap = true;
×
NEW
879
                    break;
×
880
                }
NEW
881
                if (has_gap) {
×
NEW
882
                    os << "  ... skipped ...\n";
×
883
                }
884
                // Print pre-invariant for this label
NEW
885
                if (!compact) {
×
886
                    const auto* label_rel =
NEW
887
                        relevance ? (relevance->contains(label) ? &relevance->at(label) : nullptr) : nullptr;
×
NEW
888
                    os << invariant_filter(label_rel);
×
NEW
889
                    os << "\nPre-invariant : " << result.invariants.at(label).pre << "\n";
×
NEW
890
                    os << invariant_filter(nullptr);
×
NEW
891
                    printer.print_jump("from", label);
×
892
                }
893
            }
894

895
            printer.print_line_info(label);
4✔
896

897
            // Print assertions, filtered by relevance if provided
898
            const auto* label_relevance =
2✔
899
                relevance ? (relevance->contains(label) ? &relevance->at(label) : nullptr) : nullptr;
4✔
900
            for (const auto& assertion : prog.assertions_at(label)) {
6✔
901
                // If we have relevance info, only print assertions involving relevant registers.
902
                // Assertions with no register deps (e.g., ValidCall, BoundedLoopCount) are always
903
                // printed to avoid hiding the failing assertion from the slice output.
904
                if (label_relevance) {
2✔
905
                    auto assertion_regs = extract_assertion_registers(assertion);
2✔
906
                    if (!assertion_regs.empty()) {
2✔
907
                        bool is_relevant = false;
2✔
908
                        for (const auto& reg : assertion_regs) {
2✔
909
                            if (label_relevance->registers.contains(reg)) {
2✔
910
                                is_relevant = true;
1✔
911
                                break;
1✔
912
                            }
913
                        }
914
                        if (!is_relevant) {
2✔
NEW
915
                            continue; // Skip this assertion
×
916
                        }
917
                    }
918
                }
2✔
919
                os << "  assert " << assertion << ";\n";
2✔
920
            }
4✔
921
            os << "  " << prog.instruction_at(label) << ";\n";
4✔
922

923
            last_label = label;
4✔
924
            prev_filtered_label = label;
4✔
925
            has_prev_filtered = true;
4✔
926

927
            const auto& current = result.invariants.at(label);
4✔
928
            if (current.error) {
4✔
929
                os << "\nVerification error:\n";
2✔
930
                print_error(os, *current.error);
2✔
931
                os << "\n";
2✔
932
            }
933
        }
934

935
        // Print post-invariant (unless compact)
936
        if (!compact) {
4✔
937
            const auto& current = result.invariants.at(last_label);
4✔
938
            if (!current.post.is_bottom()) {
4✔
939
                // Set invariant filter for post-invariant
940
                const auto* label_relevance =
1✔
941
                    relevance ? (relevance->contains(last_label) ? &relevance->at(last_label) : nullptr) : nullptr;
2✔
942
                os << invariant_filter(label_relevance);
2✔
943
                printer.print_jump("goto", last_label);
2✔
944
                os << "\nPost-invariant : " << current.post << "\n";
2✔
945
                os << invariant_filter(nullptr); // Clear filter
2✔
946
            }
947
        }
948
    }
8✔
949
    os << "\n";
2✔
950
}
2✔
951

952
void print_failure_slices(std::ostream& os, const Program& prog, const bool simplify, const AnalysisResult& result,
2✔
953
                          const std::vector<FailureSlice>& slices, const bool compact) {
954
    if (slices.empty()) {
2✔
NEW
955
        os << "No verification failures found.\n";
×
NEW
956
        return;
×
957
    }
958

959
    for (size_t i = 0; i < slices.size(); ++i) {
4✔
960
        const auto& slice = slices[i];
2✔
961

962
        os << "=== Failure Slice " << (i + 1) << " of " << slices.size() << " ===\n\n";
2✔
963

964
        // Print error summary
965
        os << "[ERROR] " << slice.error.what() << "\n";
2✔
966
        os << "[LOCATION] " << slice.failing_label << "\n";
2✔
967

968
        // Print relevant registers at failure point
969
        const auto it = slice.relevance.find(slice.failing_label);
2✔
970
        if (it != slice.relevance.end()) {
2✔
971
            os << "[RELEVANT REGISTERS] ";
2✔
972
            bool first = true;
2✔
973
            for (const auto& reg : it->second.registers) {
4✔
974
                if (!first) {
2✔
NEW
975
                    os << ", ";
×
976
                }
977
                os << "r" << static_cast<int>(reg.v);
2✔
978
                first = false;
2✔
979
            }
980
            if (!it->second.stack_offsets.empty()) {
2✔
NEW
981
                for (const auto& offset : it->second.stack_offsets) {
×
NEW
982
                    if (!first) {
×
NEW
983
                        os << ", ";
×
984
                    }
NEW
985
                    os << "stack[" << offset << "]";
×
NEW
986
                    first = false;
×
987
                }
988
            }
989
            os << "\n";
2✔
990
        }
991

992
        os << "[SLICE SIZE] " << slice.relevance.size() << " program points\n\n";
2✔
993

994
        // Print a compact control-flow summary showing the branch-path skeleton
995
        // through the slice. Lists labels in order with Assume/Jmp annotations.
996
        // At join points (labels with ≥2 in-slice predecessors), the converging
997
        // predecessors are grouped as {pred1 | pred2} → join_label.
998
        {
1✔
999
            os << "[CONTROL FLOW] ";
2✔
1000
            // Collect and sort impacted labels
1001
            auto labels = slice.impacted_labels();
2✔
1002

1003
            // Build a map: join_label → set of in-slice predecessors
1004
            // Also collect which labels are convergence predecessors (to skip them in linear output)
1005
            std::map<Label, std::vector<Label>> join_predecessors;
2✔
1006
            for (const auto& lbl : labels) {
6✔
1007
                const auto& parents = prog.cfg().parents_of(lbl);
4✔
1008
                std::vector<Label> in_slice_parents;
4✔
1009
                for (const auto& p : parents) {
8✔
1010
                    if (labels.contains(p)) {
4✔
1011
                        in_slice_parents.push_back(p);
2✔
1012
                    }
1013
                }
1014
                if (in_slice_parents.size() >= 2) {
4✔
NEW
1015
                    join_predecessors[lbl] = in_slice_parents;
×
1016
                }
1017
            }
4✔
1018
            // Labels consumed by a {..|..} group are skipped in linear output,
1019
            // unless they are themselves join points (nested joins).
1020
            std::set<Label> convergence_members;
2✔
1021
            for (const auto& [join_lbl, preds] : join_predecessors) {
2✔
NEW
1022
                for (const auto& p : preds) {
×
NEW
1023
                    if (!join_predecessors.contains(p)) {
×
NEW
1024
                        convergence_members.insert(p);
×
1025
                    }
1026
                }
1027
            }
1028

1029
            // Helper to annotate a label with its instruction type
1030
            auto annotate_label = [&](const Label& lbl) {
5✔
1031
                os << lbl;
4✔
1032
                const auto& ins = prog.instruction_at(lbl);
4✔
1033
                if (const auto* assume = std::get_if<Assume>(&ins)) {
4✔
NEW
1034
                    os << " (assume " << assume->cond.left << " " << assume->cond.op << " " << assume->cond.right
×
NEW
1035
                       << ")";
×
1036
                } else if (const auto* jmp = std::get_if<Jmp>(&ins)) {
4✔
NEW
1037
                    if (jmp->cond) {
×
NEW
1038
                        os << " (if " << jmp->cond->left << " " << jmp->cond->op << " " << jmp->cond->right << ")";
×
1039
                    }
1040
                }
1041
            };
6✔
1042

1043
            bool first_cf = true;
2✔
1044
            for (const auto& lbl : labels) {
6✔
1045
                // Skip labels that are part of a convergence group (printed with their join)
1046
                if (convergence_members.contains(lbl)) {
4✔
NEW
1047
                    continue;
×
1048
                }
1049

1050
                if (!first_cf) {
4✔
1051
                    os << ", ";
2✔
1052
                }
1053
                first_cf = false;
4✔
1054

1055
                // If this label is a join point, print {pred1 | pred2} → lbl
1056
                if (join_predecessors.contains(lbl)) {
4✔
NEW
1057
                    os << "{";
×
NEW
1058
                    bool first_pred = true;
×
NEW
1059
                    for (const auto& pred : join_predecessors.at(lbl)) {
×
NEW
1060
                        if (!first_pred) {
×
NEW
1061
                            os << " | ";
×
1062
                        }
NEW
1063
                        first_pred = false;
×
NEW
1064
                        annotate_label(pred);
×
1065
                    }
NEW
1066
                    os << "} -> ";
×
1067
                }
1068

1069
                annotate_label(lbl);
4✔
1070
            }
1071
            if (labels.contains(slice.failing_label)) {
2✔
1072
                os << " FAIL";
2✔
1073
            }
1074
            os << "\n\n";
2✔
1075
        }
2✔
1076

1077
        // Print the filtered CFG with assertion filtering based on relevance
1078
        os << "[CAUSAL TRACE]\n";
2✔
1079
        print_invariants_filtered(os, prog, simplify, result, slice.impacted_labels(), compact, &slice.relevance);
2✔
1080

1081
        if (i + 1 < slices.size()) {
2✔
NEW
1082
            os << "\n";
×
1083
        }
1084
    }
1085
}
1086

1087
} // namespace prevail
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc