forked from bpftrace/bpftrace
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbpfbytecode.cpp
More file actions
401 lines (347 loc) · 12.2 KB
/
Copy pathbpfbytecode.cpp
File metadata and controls
401 lines (347 loc) · 12.2 KB
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
#include "bpfbytecode.h"
#include <algorithm>
#include <cstring>
#include <stdexcept>
#include "ast/passes/named_param.h"
#include "bpftrace.h"
#include "globalvars.h"
#include "log.h"
#include "util/bpf_names.h"
#include "util/exceptions.h"
#include "util/wildcard.h"
#include <bpf/bpf.h>
#include <bpf/btf.h>
#include <elf.h>
namespace bpftrace {
char BpfLoadError::ID;
void BpfLoadError::log(llvm::raw_ostream &OS) const
{
OS << msg_;
}
char HelperVerifierError::ID;
void HelperVerifierError::log(llvm::raw_ostream &OS) const
{
OS << msg_;
}
BpfBytecode::BpfBytecode(std::span<uint8_t> elf)
: BpfBytecode(std::as_bytes(elf))
{
}
BpfBytecode::BpfBytecode(std::span<char> elf) : BpfBytecode(std::as_bytes(elf))
{
}
static std::optional<std::string> get_global_var_section_name(
std::string_view map_name,
const std::unordered_set<std::string> §ion_names)
{
for (const auto §ion_name : section_names) {
// there are some random chars in the beginning of the map name
if (std::string_view::npos != map_name.find(section_name))
return section_name;
}
return std::nullopt;
}
BpfBytecode::BpfBytecode(std::span<const std::byte> elf)
{
int log_level = 0;
// In debug mode, show full verifier log.
// In verbose mode, only show verifier log for failures.
if (bt_debug.contains(DebugStage::Verifier))
log_level = 15;
else if (bt_verbose)
log_level = 1;
DECLARE_LIBBPF_OPTS(bpf_object_open_opts, opts);
opts.kernel_log_level = static_cast<__u32>(log_level);
bpf_object_ = std::unique_ptr<struct bpf_object, bpf_object_deleter>(
bpf_object__open_mem(elf.data(), elf.size(), &opts));
if (!bpf_object_)
LOG(BUG) << "The produced ELF is not a valid BPF object: "
<< std::strerror(errno);
const auto section_names = globalvars::get_section_names();
// Discover maps
struct bpf_map *m;
bpf_map__for_each (m, bpf_object_.get()) {
std::string_view name = bpf_map__name(m);
if (auto global_var_section_name_opt = get_global_var_section_name(
name, section_names)) {
section_names_to_global_vars_map_[std::move(
*global_var_section_name_opt)] = m;
continue;
}
maps_.emplace(bpftrace_map_name(bpf_map__name(m)), m);
}
// Discover programs
struct bpf_program *p;
bpf_object__for_each_program (p, bpf_object_.get()) {
programs_.emplace(bpf_program__name(p), BpfProgram(p));
}
}
const BpfProgram &BpfBytecode::getProgramForProbe(const Probe &probe) const
{
auto prog = programs_.find(
util::get_function_name_for_probe(probe.name, probe.index));
if (prog == programs_.end()) {
throw std::runtime_error("Code not generated for probe: " + probe.name);
}
return prog->second;
}
BpfProgram &BpfBytecode::getProgramForProbe(const Probe &probe)
{
return const_cast<BpfProgram &>(
const_cast<const BpfBytecode *>(this)->getProgramForProbe(probe));
}
void BpfBytecode::update_global_vars(BPFtrace &bpftrace,
globalvars::GlobalVarMap &&global_var_vals)
{
bpftrace.resources.global_vars.update_global_vars(
bpf_object_.get(),
section_names_to_global_vars_map_,
std::move(global_var_vals),
bpftrace.ncpus_,
bpftrace.max_cpu_id_,
bpftrace.child_ ? std::make_optional<pid_t>(bpftrace.child_->pid())
: std::nullopt);
}
uint64_t BpfBytecode::get_event_loss_counter(BPFtrace &bpftrace, int max_cpu_id)
{
auto *current_values = bpftrace.resources.global_vars.get_global_var(
bpf_object_.get(),
globalvars::EVENT_LOSS_COUNTER_SECTION_NAME,
section_names_to_global_vars_map_);
uint64_t current_value = 0;
for (int i = 0; i < max_cpu_id; ++i) {
current_value += *current_values;
current_values++;
}
return current_value;
}
// Searches the verifier's log for err_pattern. If a match is found, extracts
// the name and ID of the problematic helper and throws a HelperVerifierError.
//
// Example verfier log extract:
// [...]
// 36: (b7) r3 = 64 ; R3_w=64
// 37: (85) call bpf_d_path#147
// helper call is not allowed in probe
// [...]
//
// In the above log, "bpf_d_path" is the helper's name and "147" is the ID.
static Result<> check_helper_verifier_error(
const std::string &log,
const std::string &err_pattern,
const std::string &exception_msg_suffix)
{
auto err_pos = log.find(err_pattern);
if (err_pos == std::string_view::npos)
return OK();
std::string_view call_pattern = " call ";
auto call_pos = log.rfind(call_pattern, err_pos);
if (call_pos == std::string_view::npos)
return OK();
auto helper_begin = call_pos + call_pattern.size();
auto hash_pos = log.find("#", helper_begin);
if (hash_pos == std::string_view::npos)
return OK();
auto eol = log.find("\n", hash_pos + 1);
if (eol == std::string_view::npos)
return OK();
auto helper_name = std::string{ log.substr(helper_begin,
hash_pos - helper_begin) };
auto func_id = std::stoi(
std::string{ log.substr(hash_pos + 1, eol - hash_pos - 1) });
std::string msg = std::string{ "helper " } + helper_name +
exception_msg_suffix;
return make_error<HelperVerifierError>(msg,
static_cast<bpf_func_id>(func_id));
}
// The log should end with line:
// processed N insns (limit 1000000) ...
// so we try to find it. If it's not there, it's very likely that the log has
// been trimmed due to insufficient log limit. This function checks if that
// happened.
static bool is_log_trimmed(std::string_view log)
{
static const std::vector<std::string> tokens = { "processed", "insns" };
return !util::wildcard_match(log, tokens, true, true);
}
static bool is_stack_size_error(std::string_view log)
{
static const std::vector<std::string> tokens = { "stack size", "Too large" };
return util::wildcard_match(log, tokens, true, true);
}
Result<> BpfBytecode::load_progs(const RequiredResources &resources,
const BTF &btf,
BPFfeature &feature,
const Config &config)
{
std::unordered_map<std::string_view, std::vector<char>> log_bufs;
for (auto &[name, prog] : programs_) {
log_bufs[name] = std::vector<char>(config.log_size, '\0');
auto &log_buf = log_bufs[name];
bpf_program__set_log_buf(prog.bpf_prog(), log_buf.data(), log_buf.size());
}
prepare_progs(resources.begin_probes, btf, feature, config);
prepare_progs(resources.end_probes, btf, feature, config);
prepare_progs(resources.test_probes, btf, feature, config);
prepare_progs(resources.benchmark_probes, btf, feature, config);
prepare_progs(resources.signal_probes, btf, feature, config);
prepare_progs(resources.probes, btf, feature, config);
prepare_progs(resources.watchpoint_probes, btf, feature, config);
int res = bpf_object__load(bpf_object_.get());
// If requested, print the entire verifier logs, even if loading succeeded.
for (const auto &[name, prog] : programs_) {
if (bt_debug.contains(DebugStage::Verifier)) {
std::cout << "BPF verifier log for " << name << ":\n";
std::cout << "--------------------------------------\n";
std::cout << log_bufs[name].data() << std::endl;
}
}
if (res == 0)
return OK();
// If loading of bpf_object failed, we try to give user some hints of what
// could've gone wrong.
std::string last_error_msg;
for (const auto &[name, prog] : programs_) {
if (prog.fd() >= 0)
continue;
// Unfortunately, a negative fd does not mean that this specific program
// caused the failure. It can mean that libbpf didn't even try to load it
// b/c some other program failed to load. So, we only log program load
// failures when the verifier log is non-empty.
std::string log(log_bufs[name].data());
if (!log.empty()) {
// These should be the only errors that may occur here which do not imply
// a bpftrace bug so throw immediately with a proper error message.
auto ok = check_helper_verifier_error(
log, "helper call is not allowed in probe", " not allowed in probe");
if (!ok) {
return ok.takeError();
}
ok = check_helper_verifier_error(log,
"program of this type cannot use helper",
" not allowed in probe");
if (!ok) {
return ok.takeError();
}
ok = check_helper_verifier_error(
log,
"pointer arithmetic on ptr_or_null_ prohibited, null-check it first",
": result needs to be null-checked before accessing fields");
if (!ok) {
return ok.takeError();
}
if (is_stack_size_error(log)) {
return make_error<BpfLoadError>(
"Stack size is too large. Trying moving some scratch variables "
"into maps or try setting a lower on_stack_limit (e.g. `config = { "
"on_stack_limit=16 }`)");
}
std::stringstream errmsg;
errmsg << "Error loading BPF program for " << name
<< ". Error code: " << res << ".";
if (bt_verbose) {
errmsg << std::endl
<< "Kernel error log: " << std::endl
<< log << std::endl;
if (is_log_trimmed(log)) {
LOG(WARNING, errmsg)
<< "Kernel log seems to be trimmed. This may be due to buffer "
"not being big enough, try increasing the BPFTRACE_LOG_SIZE "
"environment variable beyond the current value of "
<< log_bufs[name].size() << " bytes";
}
} else {
errmsg << " Use -v for full kernel error log.";
}
last_error_msg = errmsg.str();
}
}
if (!last_error_msg.empty()) {
return make_error<BpfLoadError>(last_error_msg);
}
// The problem does not seem to be in program loading. It may be something
// else (e.g. maps failing to load) but we're not able to figure out what
// it is so advise user to check libbf output which should contain more
// information.
return make_error<BpfLoadError>(
"Unknown BPF object load failure. Try using the \"-d libbpf\" "
"option to see the full loading log.");
}
void BpfBytecode::prepare_progs(const std::vector<Probe> &probes,
const BTF &btf,
BPFfeature &feature,
const Config &config)
{
for (const auto &probe : probes) {
auto &program = getProgramForProbe(probe);
program.set_prog_type(probe);
program.set_expected_attach_type(probe, feature);
program.set_attach_target(probe, btf, config);
program.set_no_autoattach();
}
}
void BpfBytecode::attach_external()
{
for (const auto &prog : programs_) {
auto *p = prog.second.bpf_prog();
if (bpf_program__autoattach(p)) {
bpf_program__attach(p);
}
}
}
bool BpfBytecode::all_progs_loaded()
{
return std::ranges::all_of(programs_, [](const auto &prog) {
return prog.second.fd() >= 0;
});
}
bool BpfBytecode::hasMap(const std::string &name) const
{
return maps_.contains(name);
}
bool BpfBytecode::hasMap(MapType internal_type) const
{
return maps_.contains(to_string(internal_type));
}
const BpfMap &BpfBytecode::getMap(const std::string &name) const
{
auto map = maps_.find(name);
if (map == maps_.end()) {
LOG(BUG) << "Unknown map: " << name;
}
return map->second;
}
const BpfMap &BpfBytecode::getMap(MapType internal_type) const
{
return getMap(to_string(internal_type));
}
const BpfMap &BpfBytecode::getMap(int map_id) const
{
auto map = maps_by_id_.find(map_id);
if (map == maps_by_id_.end()) {
LOG(BUG) << "Unknown map id: " << std::to_string(map_id);
}
return *map->second;
}
const std::map<std::string, BpfMap> &BpfBytecode::maps() const
{
return maps_;
}
int BpfBytecode::countStackMaps() const
{
int n = 0;
for (const auto &map : maps_) {
if (map.second.is_stack_map())
n++;
}
return n;
}
void BpfBytecode::set_map_ids(RequiredResources &resources)
{
for (auto &map : maps_) {
auto map_info = resources.maps_info.find(map.first);
if (map_info != resources.maps_info.end() && map_info->second.id != -1)
maps_by_id_.emplace(map_info->second.id, &map.second);
}
}
} // namespace bpftrace