forked from bpftrace/bpftrace
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtypes_format.cpp
More file actions
780 lines (728 loc) · 26.6 KB
/
Copy pathtypes_format.cpp
File metadata and controls
780 lines (728 loc) · 26.6 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
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
#include <algorithm>
#include <iomanip>
#include <string>
#include <utility>
#include "ast/async_event_types.h"
#include "bpftrace.h"
#include "log.h"
#include "required_resources.h"
#include "types_format.h"
#include "util/stats.h"
namespace bpftrace {
char TypeFormatError::ID;
void TypeFormatError::log(llvm::raw_ostream &OS) const
{
OS << "unable to convert type: " << typestr(ty_);
}
std::string format_build_id_stack(uint64_t nr_stack_frames,
const OpaqueValue &raw_stack)
{
std::ostringstream stack;
stack << "\n";
for (uint64_t i = 0; i < nr_stack_frames; ++i) {
auto build_id_struct = raw_stack.bitcast<bpf_stack_build_id>(i);
if (build_id_struct.status == 1) {
// Format build_id as a continuous hex string
stack << std::hex << std::setfill('0');
for (unsigned char j : build_id_struct.build_id) {
stack << std::setw(2) << static_cast<unsigned int>(j);
}
stack << std::dec << " " << "0x" << std::setfill('0') << std::setw(2)
<< std::hex << build_id_struct.offset << std::dec << std::endl;
} else {
stack << std::hex << build_id_struct.ip << std::dec << std::endl;
}
}
return stack.str();
}
Result<output::Primitive> format(BPFtrace &bpftrace,
const ast::CDefinitions &c_definitions,
const SizedType &type,
const OpaqueValue &value,
uint32_t div)
{
switch (type.GetTy()) {
case Type::timestamp_mode:
case Type::hist_t:
case Type::lhist_t:
case Type::tseries_t:
// These should never come in this way.
return make_error<TypeFormatError>(type);
case Type::none:
case Type::voidtype:
return std::monostate{};
case Type::boolean:
return value.bitcast<uint8_t>() != 0;
case Type::pointer: {
// Print a pointer as a clear hex value. This could optionally include
// the type or other information, but for now leave the existing format
// as is. We encode this as a symbolic value because the JSON backend
// will emit the raw number as a numeric value explicitly.
auto n = value.bitcast<uint64_t>();
std::ostringstream res;
res << "0x" << std::hex << n;
return output::Primitive::Symbolic(res.str(), n);
}
case Type::kstack_t: {
auto num_frames = value.bitcast<uint64_t>(0);
auto limit = type.stack_type.limit;
constexpr size_t stack_offset = sizeof(uint64_t);
auto len = static_cast<size_t>(type.stack_type.elem_size() * limit);
const auto raw_stack = value.slice(stack_offset, len);
return bpftrace.get_stack(
num_frames, raw_stack, -1, -1, false, type.stack_type, 8);
}
case Type::ustack_t: {
auto pid = value.bitcast<int32_t>(0);
auto probe_id = value.bitcast<int32_t>(1);
auto num_frames =
value.slice(sizeof(uint64_t), sizeof(uint64_t)).bitcast<uint64_t>(0);
auto limit = type.stack_type.limit;
constexpr size_t stack_offset = sizeof(uint64_t) * 2;
auto len = static_cast<size_t>(type.stack_type.elem_size() * limit);
const auto raw_stack = value.slice(stack_offset, len);
if (type.stack_type.mode == StackMode::build_id) {
return format_build_id_stack(num_frames, raw_stack);
}
return bpftrace.get_stack(
num_frames, raw_stack, pid, probe_id, true, type.stack_type, 8);
}
case Type::ksym_t: {
return bpftrace.resolve_ksym(value.bitcast<uint64_t>());
}
case Type::usym_t: {
return bpftrace.resolve_usym(value.bitcast<uint64_t>(),
value.slice(8, 4).bitcast<int32_t>(),
value.slice(12, 4).bitcast<int32_t>());
}
case Type::inet: {
return bpftrace.resolve_inet(value.bitcast<uint64_t>(),
value.slice(8).data());
}
case Type::username: {
return bpftrace.resolve_uid(value.bitcast<uint64_t>());
}
case Type::buffer: {
auto buf = value.bitcast<AsyncEvent::Buf>();
size_t length = buf.length;
output::Primitive::Buffer v;
v.data.resize(buf.length);
memcpy(v.data.data(),
value.slice(sizeof(AsyncEvent::Buf), length).data(),
length);
return v;
}
case Type::string: {
const char *p = value.data();
std::string s(p, strnlen(p, type.GetSize()));
// Add a trailer if string is truncated
//
// The heuristic we use is to check if the string exactly fits inside the
// buffer (NUL included). If it does, we assume it was truncated. This is
// a valid mechanism, with the string being "well-formed" essentially the
// signal that it was not truncated.
if (type.GetSize() == s.size()) {
s += bpftrace.config_->str_trunc_trailer;
}
return s;
}
case Type::array: {
size_t elem_size = type.GetElementTy().GetSize();
output::Primitive::Array array;
for (size_t i = 0; i < type.GetNumElements(); i++) {
auto elem_data = value.slice(i * elem_size, elem_size);
auto val = format(
bpftrace, c_definitions, type.GetElementTy(), elem_data, div);
if (!val) {
return val.takeError();
}
array.values.emplace_back(std::move(*val));
}
return array;
}
case Type::c_type:
case Type::record: {
output::Primitive::Record record;
for (auto &field : type.GetFields()) {
auto elem_data = value.slice(field.offset, field.type.GetSize());
if (field.bitfield) {
auto bf = *field.bitfield;
switch (field.type.GetIntBitWidth()) {
case 64:
elem_data = bf.to_opaque<uint64_t>(elem_data);
break;
case 32:
elem_data = bf.to_opaque<uint32_t>(elem_data);
break;
case 16:
elem_data = bf.to_opaque<uint16_t>(elem_data);
break;
case 8:
elem_data = bf.to_opaque<uint8_t>(elem_data);
break;
default:
// This type cannot be handled.
return make_error<TypeFormatError>(type);
}
}
auto val = format(bpftrace, c_definitions, field.type, elem_data, div);
if (!val) {
return val.takeError();
}
record.fields.emplace_back(field.name, std::move(*val));
}
return record;
}
case Type::tuple: {
output::Primitive::Tuple tuple;
for (auto &field : type.GetFields()) {
auto elem_data = value.slice(field.offset, field.type.GetSize());
auto val = format(bpftrace, c_definitions, field.type, elem_data, div);
if (!val) {
return val.takeError();
}
tuple.values.emplace_back(std::move(*val));
}
return tuple;
}
case Type::count_t: {
return util::reduce_value<uint64_t>(value) / div;
}
case Type::integer: {
if (type.IsEnumTy()) {
const auto &enum_name = type.GetName();
uint64_t enum_val;
switch (type.GetIntBitWidth()) {
case 64:
enum_val = value.bitcast<uint64_t>();
break;
case 32:
enum_val = value.bitcast<uint32_t>();
break;
case 16:
enum_val = value.bitcast<uint16_t>();
break;
case 8:
enum_val = value.bitcast<uint8_t>();
break;
default:
return make_error<TypeFormatError>(type);
}
auto it = c_definitions.enum_defs.find(enum_name);
if (it != c_definitions.enum_defs.end()) {
auto val_it = it->second.find(enum_val);
if (val_it != it->second.end()) {
return output::Primitive::Symbolic(val_it->second, enum_val);
}
}
if (bpftrace.btf_) {
auto btf_it = bpftrace.btf_->enum_defs_.find(enum_name);
if (btf_it != bpftrace.btf_->enum_defs_.end()) {
auto val_it = btf_it->second.find(enum_val);
if (val_it != btf_it->second.end()) {
return output::Primitive::Symbolic(val_it->second, enum_val);
}
}
}
// Fall back to something comprehensible in case user somehow
// tricked the type system into accepting an invalid enum.
return output::Primitive::Symbolic(std::to_string(enum_val), enum_val);
}
auto sign = type.IsSigned();
switch (type.GetIntBitWidth()) {
// clang-format off
case 64:
if (sign)
return util::reduce_value<int64_t>(value) / static_cast<int64_t>(div);
return util::reduce_value<uint64_t>(value) / div;
case 32:
if (sign)
return static_cast<int64_t>(
util::reduce_value<int32_t>(value) / static_cast<int32_t>(div));
return static_cast<uint64_t>(util::reduce_value<uint32_t>(value) / div);
case 16:
if (sign)
return
static_cast<int64_t>(util::reduce_value<int16_t>(value) / static_cast<int16_t>(div));
return static_cast<uint64_t>(util::reduce_value<uint16_t>(value) / div);
case 8:
if (sign)
return
static_cast<int64_t>(util::reduce_value<int8_t>(value) / static_cast<int8_t>(div));
return static_cast<uint64_t>(util::reduce_value<uint8_t>(value) / div);
default:
// This type cannot be handled.
return make_error<TypeFormatError>(type);
// clang-format on
}
}
case Type::sum_t: {
if (type.IsSigned())
return util::reduce_value<int64_t>(value) / div;
return util::reduce_value<uint64_t>(value) / div;
}
case Type::max_t:
case Type::min_t: {
if (value.count<uint64_t>() == 1) {
// See avg_t below, this may be collapsed.
if (type.IsSigned()) {
return value.bitcast<int64_t>() / div;
}
return value.bitcast<uint64_t>() / div;
}
if (type.IsSigned()) {
return util::min_max_value<int64_t>(value, type.IsMaxTy()) / div;
}
return util::min_max_value<uint64_t>(value, type.IsMaxTy()) / div;
}
case Type::timestamp: {
// Although the "type" is timestamp, it somehow comes with a format
// string. We could optionally store just a native nsec timestamp, and
// allow the output to choose the format. We will leave this for a future
// type. For now this both resolves and formats the time.
auto s = value.bitcast<const AsyncEvent::Strftime>();
const auto ts = bpftrace.resolve_timestamp(s.mode, s.nsecs);
return bpftrace.format_timestamp(ts, s.strftime_id);
}
case Type::mac_address: {
return bpftrace.resolve_mac_address(value.data());
}
case Type::cgroup_path_t: {
auto c = value.bitcast<const AsyncEvent::CgroupPath>();
return bpftrace.resolve_cgroup_path(c.cgroup_path_id, c.cgroup_id);
}
case Type::avg_t:
case Type::stats_t: {
if (type.IsAvgTy() && value.count<uint64_t>() == 1) {
// on this code path, avg is calculated in the kernel while printing the
// entire map is handled in a different function.
if (type.IsSigned()) {
return value.bitcast<int64_t>() / div;
}
return value.bitcast<uint64_t>() / div;
}
std::optional<output::Primitive> average, total, count;
if (type.IsSigned()) {
auto stats = util::stats_value<int64_t>(value);
average.emplace(stats.avg / div);
total.emplace(stats.total);
count.emplace(stats.count);
} else {
auto stats = util::stats_value<uint64_t>(value);
average.emplace(stats.avg / div);
total.emplace(stats.total);
count.emplace(stats.count);
}
if (type.IsStatsTy()) {
output::Primitive::Record vals;
vals.fields.emplace_back("count", std::move(*count));
vals.fields.emplace_back("average", std::move(*average));
vals.fields.emplace_back("total", std::move(*total));
return vals;
} else {
return std::move(*average);
}
}
}
return make_error<TypeFormatError>(type);
}
// Translate the index into the starting value for the corresponding interval.
// Each power of 2 is mapped into N = 2**k intervals, each of size
// S = 1 << ((index >> k) - 1), and starting at S * N.
// The last k bits of index indicate which interval we want.
//
// For example, if k = 2 and index = 0b11011 (27) we have:
// - N = 2**2 = 4;
// - interval size S is 1 << ((0b11011 >> 2) - 1) = 1 << (6 - 1) = 32
// - starting value is S * N = 128
// - the last 2 bits 11 indicate the third interval so the
// starting value is 128 + 32*3 = 224
static output::Primitive hist_index_label(uint32_t index, uint32_t k)
{
const uint32_t n = (1 << k);
const uint32_t interval = index & (n - 1);
assert(index >= n);
uint32_t power = (index >> k) - 1;
uint64_t value = (1ULL << power) * (n + interval);
// Choose the suffix for the largest power of 2^10
const uint32_t decade = power / 10;
const char suffix = "\0KMGTPE"[decade];
power -= 10 * decade;
std::ostringstream label;
label << (1ULL << power) * (n + interval);
if (suffix)
label << suffix;
return output::Primitive::Symbolic(label.str(), value);
}
static std::pair<int, int> indices(const std::vector<uint64_t> &values)
{
int min_index = -1;
int max_index = -1;
for (size_t i = 0; i < values.size(); i++) {
int v = values.at(i);
if (v > 0) {
if (min_index == -1)
min_index = i;
max_index = i;
}
}
return { min_index, max_index };
}
static output::Value::Histogram build_histogram(
const std::vector<uint64_t> &values,
uint32_t div,
uint32_t k)
{
output::Value::Histogram hist;
auto [min_index, max_index] = indices(values);
if (min_index == -1) {
return hist;
}
if (min_index != 0) {
if (min_index - 1 <= (2 << k)) {
hist.lower_bound = min_index - 1;
} else {
hist.lower_bound = hist_index_label(min_index - 1, k);
}
}
for (int i = min_index; i <= max_index; i++) {
// Index 0 is for negative values. Following that, each sequence
// of N = 1 << k indexes represents one power of 2.
// In particular:
// - the first set of N indexes is for values 0..N-1
// (one value per index)
// - the second and following sets of N indexes each contain
// <1, 2, 4 .. and subsequent powers of 2> values per index.
//
// Since the first and second set are closed intervals and the value
// of each interval equals "index - 1", we print it directly.
// Higher indexes contain multiple values and we use helpers to print
// the range as open intervals.
if (i == 0) {
hist.labels.emplace_back(0);
} else if (i <= (2 << k)) {
hist.labels.emplace_back(i);
} else {
hist.labels.push_back(hist_index_label(i, k));
}
hist.counts.push_back(values.at(i) / div);
}
return hist;
}
static output::Primitive lhist_index_label(int number, int step)
{
constexpr int kilo = 1024;
constexpr int mega = 1024 * 1024;
if (step % kilo != 0)
return static_cast<int64_t>(number);
std::ostringstream label;
if (number == 0) {
label << number;
} else if (number % mega == 0) {
label << number / mega << 'M';
} else if (number % kilo == 0) {
label << number / kilo << 'K';
} else {
label << number;
}
return output::Primitive::Symbolic(label.str(), number);
}
static output::Value::Histogram build_linear_histogram(
const std::vector<uint64_t> &values,
int min,
int max,
int step)
{
output::Value::Histogram hist;
auto [min_index, max_index] = indices(values);
if (min_index == -1) {
return hist;
}
if (min_index != 0) {
hist.lower_bound = lhist_index_label(min + ((min_index - 1) * step), step);
}
for (int i = min_index; i <= max_index; i++) {
// The final bucket represents values over the label, and we encode
// this into the histogram structure by simply omitting the label.
if (min + (i * step) <= max) {
hist.labels.push_back(lhist_index_label(min + (i * step), step));
}
hist.counts.push_back(values.at(i));
}
return hist;
}
template <typename T>
void sort_by_key_type(
std::vector<std::pair<OpaqueValue, OpaqueValue>> &values_by_key,
size_t offset)
{
std::ranges::stable_sort(values_by_key, [&](auto &a, auto &b) {
return a.first.slice(offset).template bitcast<T>() <
b.first.slice(offset).template bitcast<T>();
});
}
void sort_by_key(
const SizedType &key,
std::vector<std::pair<OpaqueValue, OpaqueValue>> &values_by_key)
{
if (key.IsTupleTy()) {
// Sort the key arguments in reverse order so the results are sorted by
// the first argument first, then the second, etc.
auto &fields = key.GetFields();
for (size_t i = key.GetFieldCount(); i-- > 0;) {
const auto &field = fields.at(i);
if (field.type.IsIntTy()) {
if (field.type.GetSize() == 8) {
sort_by_key_type<int64_t>(values_by_key, field.offset);
} else if (field.type.GetSize() == 4) {
sort_by_key_type<int32_t>(values_by_key, field.offset);
} else if (field.type.GetSize() == 2) {
sort_by_key_type<int16_t>(values_by_key, field.offset);
} else if (field.type.GetSize() == 1) {
sort_by_key_type<int8_t>(values_by_key, field.offset);
} else {
LOG(BUG)
<< "invalid integer argument size. 1, 2, 4, or 8 expected, but "
<< field.type.GetSize() << " provided";
}
} else if (field.type.IsStringTy()) {
std::ranges::stable_sort(values_by_key, [&](auto &a, auto &b) {
// This will actually do a string-like comparison between the opaque
// value memory blocks, which is exactly what we want for a string.
return a.first.slice(field.offset, field.type.GetSize()) <
b.first.slice(field.offset, field.type.GetSize());
});
}
}
} else if (key.IsIntTy()) {
if (key.GetSize() == 8) {
sort_by_key_type<int64_t>(values_by_key, 0);
} else if (key.GetSize() == 4) {
sort_by_key_type<int32_t>(values_by_key, 0);
} else if (key.GetSize() == 2) {
sort_by_key_type<int16_t>(values_by_key, 0);
} else if (key.GetSize() == 1) {
sort_by_key_type<int8_t>(values_by_key, 0);
} else {
LOG(BUG) << "invalid integer argument size. 1, 2, 4, or 8 expected, but "
<< key.GetSize() << " provided";
}
} else if (key.IsStringTy()) {
std::ranges::stable_sort(values_by_key, [&](auto &a, auto &b) {
return a.first < b.first; // See above.
});
}
}
static output::Value::TimeSeries build_time_series(
BPFtrace &bpftrace,
const std::map<uint64_t, output::Primitive> &values,
const std::pair<uint64_t, uint64_t> epoch_range,
const TSeriesArgs &args)
{
output::Value::TimeSeries tseries;
auto first_epoch = epoch_range.second;
auto last_epoch = epoch_range.first;
for (const auto &[epoch, _] : values) {
if (epoch < epoch_range.first) {
continue;
}
first_epoch = std::min(epoch, first_epoch);
last_epoch = std::max(epoch, last_epoch);
}
for (auto epoch = epoch_range.first; epoch <= epoch_range.second; epoch++) {
const auto &v = values.find(epoch);
if (epoch >= first_epoch) {
tseries.values.emplace_back(
output::Primitive::Timestamp(bpftrace.resolve_timestamp(
static_cast<uint64_t>(TimestampMode::tai),
epoch * args.interval_ns)),
v != values.end() ? v->second : std::monostate{});
}
}
return tseries;
}
Result<output::Value> format(BPFtrace &bpftrace,
const ast::CDefinitions &c_definitions,
const BpfMap &map,
size_t top,
uint32_t div)
{
uint32_t i = 0;
const auto &map_info = bpftrace.resources.maps_info.at(map.name());
const auto &key_type = map_info.key_type;
const auto &value_type = map_info.value_type;
uint64_t nvalues = map.is_per_cpu_type() ? bpftrace.ncpus_ : 1;
output::Value::OrderedMap rval;
if (value_type.IsHistTy() || value_type.IsLhistTy()) {
// A hist-map adds an extra 8 bytes onto the end of its key for
// storing the bucket number. e.g. A map defined as:
//
// @x[1, 2] = @hist(3);
//
// Would actually be stored with the key:
// [1, 2, 3]
auto values_by_key = map.collect_histogram_data(map_info, nvalues);
if (!values_by_key) {
return values_by_key.takeError();
}
// Sort based on sum of counts in all buckets.
std::vector<std::pair<OpaqueValue, uint64_t>> total_counts_by_key;
for (auto &[key, value] : *values_by_key) {
int64_t sum = 0;
for (unsigned long i : value) {
sum += i;
}
total_counts_by_key.emplace_back(key, sum);
}
std::ranges::sort(total_counts_by_key,
[&](auto &a, auto &b) { return a.second < b.second; });
if (div == 0) {
div = 1;
}
for (const auto &[key, count] : total_counts_by_key) {
if (top && total_counts_by_key.size() > top &&
i++ < (total_counts_by_key.size() - top))
continue;
output::Value::Histogram hist;
if (value_type.IsHistTy()) {
if (!std::holds_alternative<HistogramArgs>(map_info.detail))
LOG(BUG) << "call to hist with missing \"bits\" argument";
hist = build_histogram((*values_by_key)[key],
div,
std::get<HistogramArgs>(map_info.detail).bits);
} else {
if (!std::holds_alternative<LinearHistogramArgs>(map_info.detail))
LOG(BUG) << "call to lhist with missing arguments";
const auto &args = std::get<LinearHistogramArgs>(map_info.detail);
// N.B. div has no effect on linear histograms.
hist = build_linear_histogram(
(*values_by_key)[key], args.min, args.max, args.step);
}
// If this is a scalar map, then we just return the value.
if (map_info.is_scalar) {
return hist;
}
// Build out the value above.
auto key_val = format(bpftrace, c_definitions, key_type, key);
if (!key_val) {
return key_val.takeError();
}
rval.values.emplace_back(std::move(*key_val), std::move(hist));
}
return rval;
}
if (value_type.IsTSeriesTy()) {
const auto &args = std::get<TSeriesArgs>(map_info.detail);
auto values_by_key = map.collect_tseries_data(map_info, nvalues);
if (!values_by_key) {
return values_by_key.takeError();
}
// Sort from least to most recently updated.
std::vector<std::pair<OpaqueValue, uint64_t>> latest_epoch_by_key;
for (const auto &tseries : *values_by_key) {
uint64_t latest_epoch = 0;
for (const auto &bucket : tseries.second) {
latest_epoch = std::max(latest_epoch, bucket.first);
}
latest_epoch_by_key.emplace_back(tseries.first, latest_epoch);
}
std::ranges::sort(latest_epoch_by_key,
[&](auto &a, auto &b) { return a.second < b.second; });
auto last_epoch = latest_epoch_by_key.empty()
? std::numeric_limits<uint64_t>::max()
: latest_epoch_by_key.back().second;
auto first_epoch = last_epoch - args.num_intervals + 1;
auto range = std::make_pair(first_epoch, last_epoch);
// Type for the reduction. Note that when the elements are collected
// they have already been reduced, much like in the histogram case.
SizedType reduced_type = args.value_type.IsSigned() ? CreateInt64()
: CreateUInt64();
for (const auto &[key, value] : *values_by_key) {
// Collect all the values for this specific key.
std::map<uint64_t, output::Primitive> values;
for (const auto &[epoch, v] : value) {
auto p = format(bpftrace, c_definitions, reduced_type, v);
if (!p) {
return p.takeError();
}
values.emplace(epoch, std::move(*p));
}
auto key_res = format(bpftrace, c_definitions, key_type, key);
if (!key_res) {
return key_res.takeError();
}
auto ts = build_time_series(bpftrace, values, range, args);
if (map_info.is_scalar) {
return ts;
}
rval.values.emplace_back(std::move(*key_res), std::move(ts));
}
return rval;
}
auto values_by_key = map.collect_elements(nvalues);
if (!values_by_key) {
return values_by_key.takeError();
}
bool stats = false;
if (value_type.IsCountTy() || value_type.IsSumTy() || value_type.IsIntTy()) {
bool is_signed = value_type.IsSigned();
std::ranges::sort(*values_by_key, [&](auto &a, auto &b) {
if (is_signed)
return util::reduce_value<int64_t>(a.second) <
util::reduce_value<int64_t>(b.second);
return util::reduce_value<uint64_t>(a.second) <
util::reduce_value<uint64_t>(b.second);
});
} else if (value_type.IsMinTy() || value_type.IsMaxTy()) {
std::ranges::sort(*values_by_key, [&](auto &a, auto &b) {
return util::min_max_value<uint64_t>(a.second, value_type.IsMaxTy()) <
util::min_max_value<uint64_t>(b.second, value_type.IsMaxTy());
});
} else if (value_type.IsAvgTy() || value_type.IsStatsTy()) {
stats = true;
if (value_type.IsSigned()) {
std::ranges::sort(*values_by_key, [&](auto &a, auto &b) {
return util::avg_value<int64_t>(a.second) <
util::avg_value<int64_t>(b.second);
});
} else {
std::ranges::sort(*values_by_key, [&](auto &a, auto &b) {
return util::avg_value<uint64_t>(a.second) <
util::avg_value<uint64_t>(b.second);
});
}
} else {
sort_by_key(map_info.key_type, *values_by_key);
};
if (div == 0) {
div = 1;
}
// Print as a regular map.
size_t done = 0;
size_t total = values_by_key->size();
for (auto &[key, value] : *values_by_key) {
if (top && total > top && done++ < (total - top)) {
continue;
}
auto val_res = format(bpftrace, c_definitions, value_type, value, div);
if (!val_res) {
return val_res.takeError();
}
if (map_info.is_scalar) {
if (stats) {
return output::Value(output::Value::Stats(std::move(*val_res)));
}
return std::move(*val_res);
}
auto key_res = format(bpftrace, c_definitions, key_type, key);
if (!key_res) {
return key_res.takeError();
}
rval.values.emplace_back(std::move(*key_res), std::move(*val_res));
}
if (stats) {
return output::Value::Stats(std::move(rval));
}
return rval;
}
} // namespace bpftrace