-
Notifications
You must be signed in to change notification settings - Fork 10
/
ctf2ctf.cpp
2117 lines (1874 loc) · 71.5 KB
/
ctf2ctf.cpp
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
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
ctf2ctf.cpp
This file is part of ctf2ctf, a converter from LTTng/CTF to Chromium's Common Trace Format.
Copyright (C) 2019 Klarälvdalens Datakonsult AB, a KDAB Group company, [email protected]
Author: Milian Wolff <[email protected]>
Licensees holding valid commercial KDAB ctf2ctf licenses may use this file in
accordance with ctf2ctf Commercial License Agreement provided with the Software.
Contact [email protected] if any conditions of this licensing are not clear to you.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <babeltrace/babeltrace.h>
#include <babeltrace/ctf/events.h>
#include <babeltrace/ctf/iterator.h>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <stdio_ext.h>
#include <csignal>
#include <cstring>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <variant>
#include <vector>
#include "fs.h"
#include "clioptions.h"
#include "config.h"
#if QtGui_FOUND
#include <QEvent>
#include <QMetaEnum>
#include <QString>
#endif
namespace
{
volatile std::sig_atomic_t s_shutdownRequested = 0;
void shutdownGracefully(int sig)
{
if (!s_shutdownRequested) {
s_shutdownRequested = 1;
return;
}
// re-raise signal with default handler and trigger program termination
std::signal(sig, SIG_DFL);
std::raise(sig);
}
void installSignalHandler()
{
#ifdef SIGHUP
std::signal(SIGHUP, shutdownGracefully);
#endif
#ifdef SIGINT
std::signal(SIGINT, shutdownGracefully);
#endif
#ifdef SIGTERM
std::signal(SIGTERM, shutdownGracefully);
#endif
}
struct ErrorOutput
{
std::ostream& out(std::string_view prefix, std::string_view file, int line)
{
if (m_lastWasProgress)
std::cerr << '\n';
m_lastWasProgress = false;
return std::cerr << prefix << " (" << file << ':' << line << "): ";
}
std::ostream& progress()
{
if (m_lastWasProgress)
return std::cerr << '\r';
m_lastWasProgress = true;
return std::cerr;
}
static ErrorOutput& self()
{
static ErrorOutput out;
return out;
}
private:
bool m_lastWasProgress = false;
};
struct EndWithNewline
{
EndWithNewline(std::ostream &out)
: out(out)
{}
~EndWithNewline()
{
out << '\n';
}
template<typename T>
std::ostream &operator<<(T&& arg)
{
return out << arg;
}
std::ostream &out;
};
#define ERROR() EndWithNewline(ErrorOutput::self().out("ERROR", __FILE__, __LINE__))
#define WARNING() EndWithNewline(ErrorOutput::self().out("WARNING", __FILE__, __LINE__))
#define DEBUG() EndWithNewline(ErrorOutput::self().out("DEBUG", __FILE__, __LINE__))
#define PROGRESS() ErrorOutput::self().progress()
// cf. lttng-modules/instrumentation/events/lttng-module/block.h
std::string rwbsToString(uint64_t rwbs)
{
std::string ret;
auto check = [&ret, rwbs](std::string_view name, uint16_t flag) {
if (rwbs & (1 << flag)) {
if (!ret.empty())
ret += ", ";
ret += name;
}
};
check("write", 0);
check("discard", 1);
check("read", 2);
check("rahead", 3);
check("barrier", 4);
check("sync", 5);
check("meta", 6);
check("secure", 7);
check("flush", 8);
check("fua", 9);
check("preflush", 10);
return ret;
}
constexpr auto TIMESTAMP_PRECISION = std::numeric_limits<double>::max_digits10;
template<typename Callback>
void findMetadataFiles(const fs::path& path, Callback&& callback)
{
for (const auto& entry : fs::recursive_directory_iterator(path)) {
if (fs::is_regular_file(entry.status()) && entry.path().filename() == "metadata")
callback(entry.path().parent_path().c_str());
}
}
template<typename T, typename Cleanup>
auto wrap(T* value, Cleanup cleanup)
{
return std::unique_ptr<T, Cleanup>(value, cleanup);
}
template<typename Reader>
auto get(const bt_ctf_event* event, const bt_definition* scope, const char* name, Reader reader)
{
auto definition = bt_ctf_get_field(event, scope, name);
auto ret = std::optional<std::invoke_result_t<Reader, decltype(definition)>>();
if (definition)
ret = std::make_optional(reader(definition));
return ret;
}
auto get_uint64(const bt_ctf_event* event, const bt_definition* scope, const char* name)
{
return get(event, scope, name, bt_ctf_get_uint64);
}
auto get_int64(const bt_ctf_event* event, const bt_definition* scope, const char* name)
{
return get(event, scope, name, bt_ctf_get_int64);
}
auto get_char_array(const bt_ctf_event* event, const bt_definition* scope, const char* name)
{
return get(event, scope, name, bt_ctf_get_char_array);
}
auto get_string(const bt_ctf_event* event, const bt_definition* scope, const char* name)
{
return get(event, scope, name, bt_ctf_get_string);
}
auto get_float(const bt_ctf_event* event, const bt_definition* scope, const char* name)
{
return get(event, scope, name, bt_ctf_get_float);
}
bool startsWith(std::string_view string, std::string_view prefix)
{
return string.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), string.begin());
}
bool endsWith(std::string_view string, std::string_view suffix)
{
return string.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), string.rbegin());
}
bool removeSuffix(std::string& name, std::string_view suffix)
{
if (!endsWith(name, suffix))
return false;
name.resize(name.size() - suffix.length());
return true;
}
bool removePrefix(std::string& name, std::string_view prefix)
{
if (!startsWith(name, prefix))
return false;
name.erase(0, prefix.size());
return true;
}
template<typename List, typename Needle>
bool contains(List&& list, const Needle& needle)
{
return std::find(list.begin(), list.end(), needle) != list.end();
}
template<typename T1, typename T2>
bool contains(const std::initializer_list<T1>& list, const T2& needle)
{
return std::find(begin(list), end(list), needle) != end(list);
}
template<typename Whitelist, typename Needle>
bool isWhitelisted(const Whitelist& whitelist, const Needle& needle)
{
return whitelist.empty() || contains(whitelist, needle);
}
template<typename T>
auto findMmapAt(T&& mmaps, uint64_t addr)
{
for (auto it = mmaps.begin(), end = mmaps.end(); it != end; ++it) {
if (it->addr > addr)
break;
if (it->addr <= addr && addr < (it->addr + it->len))
return it;
}
return mmaps.end();
}
struct KMemAlloc
{
uint64_t requested = 0;
uint64_t allocated = 0;
};
KMemAlloc operator+(const KMemAlloc& lhs, const KMemAlloc& rhs)
{
return {lhs.requested + rhs.requested, lhs.allocated + rhs.allocated};
}
KMemAlloc operator-(const KMemAlloc& lhs, const KMemAlloc& rhs)
{
return {lhs.requested - rhs.requested, lhs.allocated - rhs.allocated};
}
KMemAlloc& operator+=(KMemAlloc& lhs, const KMemAlloc& rhs)
{
lhs = lhs + rhs;
return lhs;
}
KMemAlloc& operator-=(KMemAlloc& lhs, const KMemAlloc& rhs)
{
lhs = lhs - rhs;
return lhs;
}
std::string commName(std::string_view comm, int64_t tid)
{
std::string ret;
ret += comm;
ret += " (";
ret += std::to_string(tid);
ret += ")";
return ret;
}
enum class ArgsType
{
Object,
Array,
Event,
};
enum class IntegerArgFormatFlag
{
Decimal,
Hexadecimal
};
enum class ArgError
{
UnknownType,
UnknownSignedness,
UnhandledArrayType,
UnhandledType,
};
using Arg = std::variant<int64_t, uint64_t, double, std::string_view, char, ArgError>;
class JsonArgsPrinter
{
public:
const std::string_view label;
const ArgsType type = ArgsType::Object;
JsonArgsPrinter(ArgsType type, std::string_view label, FILE* out, JsonArgsPrinter* parent)
: label(label)
, type(type)
, out(out)
, parent(parent)
{
}
~JsonArgsPrinter()
{
if (!firstField) {
switch (type) {
case ArgsType::Event:
case ArgsType::Object:
fprintf(out, "}");
break;
case ArgsType::Array:
fprintf(out, "]");
break;
}
}
}
template<typename T, typename... FormatArgs>
void writeField(std::string_view field, T value, FormatArgs... formatArgs)
{
newField(field);
writeValue(value, formatArgs...);
}
JsonArgsPrinter argsPrinter(ArgsType type, std::string_view label)
{
assert(type != ArgsType::Event);
return {type, label, out, this};
}
private:
void newField(std::string_view field)
{
if (firstField) {
firstField = false;
if (parent)
parent->newField(label);
switch (type) {
case ArgsType::Event:
case ArgsType::Object:
fprintf(out, "{");
break;
case ArgsType::Array:
fprintf(out, "[");
break;
}
} else {
fprintf(out, ", ");
}
if (type == ArgsType::Array)
return;
writeValue(field);
fprintf(out, ": ");
}
void writeValue(int64_t value, int base = 10)
{
switch (base) {
case 8:
if (value < 0)
fprintf(out, "\"-0o%lo\"", -static_cast<uint64_t>(value));
else
fprintf(out, "\"0o%lo\"", static_cast<uint64_t>(value));
break;
case 16:
if (value < 0)
fprintf(out, "\"-0x%lx\"", -static_cast<uint64_t>(value));
else
fprintf(out, "\"0x%lx\"", static_cast<uint64_t>(value));
break;
default:
WARNING() << "unhandled integer base: " << base;
[[fallthrough]];
case 10:
fprintf(out, "%ld", value);
break;
}
}
void writeValue(double value)
{
fprintf(out, "%.*g", TIMESTAMP_PRECISION, value);
}
void writeValue(uint64_t value, int base = 10)
{
switch (base) {
case 8:
fprintf(out, "\"0o%lo\"", value);
break;
case 16:
fprintf(out, "\"0x%lx\"", value);
break;
default:
WARNING() << "unhandled integer base: " << base;
[[fallthrough]];
case 10:
fprintf(out, "%lu", value);
break;
}
}
void writeValue(std::string_view string)
{
putc('"', out);
for (auto c : string) {
if (c == '\n') {
fputs("\\n", out);
continue;
} else if (c == '\r') {
fputs("\\r", out);
continue;
}
if ((c >= 0 && c <= 0x1F) || c == '"' || c == '\\')
putc('\\', out);
putc(c, out);
}
putc('"', out);
}
void writeValue(ArgError error, int64_t arg)
{
switch (error) {
case ArgError::UnknownType:
fputs(R"("<unknown type>")", out);
break;
case ArgError::UnknownSignedness:
fputs(R"("<unknown signedness>")", out);
break;
case ArgError::UnhandledArrayType:
fprintf(out, R"("<unhandled array type %ld>")", arg);
break;
case ArgError::UnhandledType:
fprintf(out, R"("<unhandled type %ld>")", arg);
break;
}
}
void writeValue(char c)
{
fprintf(out, "\"%c\"", c);
}
void writeValue(const Arg& arg)
{
std::visit([this](auto arg) { writeValue(arg); }, arg);
}
FILE* out = nullptr;
JsonArgsPrinter* parent = nullptr;
bool firstField = true;
};
class JsonPrinter
{
public:
JsonPrinter(const std::string& output)
{
if (output.empty() || output == "-")
return;
if (output == "stderr") {
out = stderr;
return;
}
if (auto fd = fopen(output.c_str(), "w"))
out = fd;
else
ERROR() << "failed to open " << output << ": " << strerror(errno);
}
~JsonPrinter()
{
if (!firstEvent)
writeSuffix();
if (out != stderr && out != stdout)
fclose(out);
else
fflush(out);
}
JsonArgsPrinter eventPrinter()
{
if (firstEvent) {
firstEvent = false;
writePrefix();
} else {
fprintf(out, ",");
}
fprintf(out, "\n ");
return {ArgsType::Event, {}, out, nullptr};
}
private:
void writePrefix()
{
fprintf(out, "{\n \"traceEvents\": [");
}
void writeSuffix()
{
fprintf(out, "\n ]\n}\n");
}
FILE* out = stdout;
bool firstEvent = true;
};
struct Event;
struct Context
{
static constexpr const uint64_t PAGE_SIZE = 4096;
bool reportedBrokenTracefString = false;
JsonPrinter printer;
CliOptions options;
Context(CliOptions options)
: printer(options.outputFile)
, options(std::move(options))
{
cores.reserve(32);
pids.reserve(1024);
tids.reserve(1024);
irqs.reserve(32);
blockDevices.reserve(32);
}
double toMs(int64_t timestamp)
{
if (options.relativeTimestamps) {
if (isFilteredByTime(timestamp)) {
timestamp = 0;
} else if (!firstTimestamp) {
firstTimestamp = timestamp;
timestamp = 0;
} else {
timestamp -= firstTimestamp;
}
}
const auto ms = timestamp / 1000;
const auto ns = timestamp % 1000;
return static_cast<double>(ms) + static_cast<double>(ns) * 1E-3;
}
int64_t tid(uint64_t cpuId) const
{
if (cores.size() <= cpuId)
return INVALID_TID;
return cores[cpuId].tid;
}
int64_t pid(int64_t tid) const
{
auto it = tids.find(tid);
return it == tids.end() ? INVALID_TID : it->second.pid;
}
void setTid(uint64_t cpuId, int64_t tid)
{
if (cores.size() <= cpuId)
cores.resize(cpuId + 1);
cores[cpuId].tid = tid;
}
void setPid(int64_t tid, int64_t pid)
{
tids[tid].pid = pid;
}
void setOpenAtFilename(int64_t tid, std::string_view filename)
{
tids[tid].openAtFilename = filename;
}
void setOpenAtFd(int64_t pid, int64_t tid, int64_t fd)
{
pids[pid].fdToFilename[fd] = std::move(tids[tid].openAtFilename);
}
void setFdFilename(int64_t pid, int64_t fd, std::string_view filename)
{
pids[pid].fdToFilename[fd] = filename;
}
void closeFd(int64_t pid, int64_t fd)
{
auto& fds = pids[pid].fdToFilename;
auto it = fds.find(fd);
if (it != fds.end())
fds.erase(it);
}
std::string_view fdToFilename(int64_t pid, int64_t fd) const
{
std::string_view filename = "??";
if (fd == 0)
filename = "stdin";
else if (fd == 1)
filename = "stdout";
else if (fd == 2)
filename = "stderr";
auto pid_it = pids.find(pid);
if (pid_it == pids.end())
return filename;
const auto& fds = pid_it->second.fdToFilename;
auto fd_it = fds.find(fd);
if (fd_it == fds.end())
return filename;
filename = fd_it->second;
return filename;
}
void setIrqName(uint64_t irq, std::string_view name, std::string_view action)
{
irqs[irq] = {std::string(name), std::string(action)};
}
struct IrqDataView
{
std::string_view name;
std::string_view action;
};
IrqDataView irq(uint64_t irq) const
{
auto it = irqs.find(irq);
if (it == irqs.end())
return {};
return {it->second.name, it->second.action};
}
void setBlockDeviceName(uint64_t device, std::string_view name)
{
blockDevices[device].name = name;
}
std::string_view blockDeviceName(uint64_t device) const
{
auto it = blockDevices.find(device);
if (it == blockDevices.end())
return "??";
return it->second.name;
}
void mmap(int64_t pid, uint64_t addr, uint64_t len, std::string_view file, int64_t fd)
{
auto& mmaps = pids[pid].mmaps;
auto it =
std::lower_bound(mmaps.begin(), mmaps.end(), addr, [](auto map, auto addr) { return map.addr < addr; });
mmaps.insert(it, {addr, len, std::string(file), fd});
}
void mmapEntry(int64_t tid, uint64_t len, int64_t fd)
{
tids[tid].mmapEntry = {len, fd};
}
void mmapExit(int64_t pid, int64_t tid, uint64_t addr, int64_t timestamp)
{
auto& entry = tids[tid].mmapEntry;
if (addr && entry.len) {
mmap(pid, addr, entry.len, fdToFilename(pid, entry.fd), entry.fd);
anonMmapped(pid, timestamp, entry.fd, entry.len, true);
}
entry = {};
}
void munmap(int64_t pid, uint64_t addr, uint64_t len, int64_t timestamp)
{
auto& mmaps = pids[pid].mmaps;
auto it = findMmapAt(mmaps, addr);
if (it == mmaps.end())
return;
anonMmapped(pid, timestamp, it->fd, len, false);
if (it->addr == addr && it->len == len) {
mmaps.erase(it);
return;
} else if (it->addr == addr) {
it->addr += len;
} else if (it->addr + len == addr + len) {
it->len -= len;
} else {
// split up
const auto trailing = it->addr + it->len - addr - len;
it->len = (addr - it->addr);
mmaps.insert(it + 1, {addr + len, trailing, it->file, it->fd});
}
}
std::string_view fileMmappedAt(int64_t pid, uint64_t addr) const
{
auto pid_it = pids.find(pid);
if (pid_it == pids.end())
return "??";
const auto& mmaps = pid_it->second.mmaps;
auto it = findMmapAt(mmaps, addr);
if (it == mmaps.end())
return "??";
return it->file;
}
void fork(int64_t parentPid, int64_t childPid)
{
// follow children by default
if (options.processWhitelist.empty())
return;
if (!contains(options.pidWhitelist, parentPid) || contains(options.pidWhitelist, childPid))
return;
options.pidWhitelist.push_back(childPid);
}
void threadExit(int64_t tid, int64_t pid, int64_t timestamp)
{
if (tid == pid) {
auto pid_it = pids.find(pid);
if (pid_it != pids.end()) {
if (pid_it->second.anonMmapped > 0) {
// reset counters to zero to ensure the graph expands the full width of process lifetime
printCounterValue("anon mmapped", timestamp, pid, int64_t(0));
}
pids.erase(pid_it);
}
}
if (auto tid_it = tids.find(tid); tid_it != tids.end())
tids.erase(tids.find(tid));
}
void pageFault(int64_t pid, int64_t timestamp)
{
auto& pageFaults = pids[pid].pageFaults;
pageFaults++;
printCounterValue("page faults", timestamp, pid, pageFaults);
}
std::string& getTidName(int64_t id)
{
auto it = tids.find(id);
if (it == tids.end())
it = tids.insert(it, {id, {}});
return it->second.name;
}
void printName(int64_t tid, int64_t pid, std::string_view name, int64_t timestamp)
{
if (tid == pid) {
bool whiteListedPid = contains(options.pidWhitelist, pid);
if (!whiteListedPid && isFilteredByProcessName(name))
return;
if (!options.processWhitelist.empty() && !whiteListedPid)
options.pidWhitelist.push_back(pid); // add pid to filter to exclude events
}
if (isFilteredByPid(pid))
return;
auto printName = [this, tid, pid, name, timestamp](const char* type) {
printEvent(type, 'M', timestamp, pid, tid, {}, {{"name", name}});
};
if (pid != INVALID_TID) {
auto& pidName = getTidName(pid);
if (pidName.empty() || (tid == pid && pidName != name)) {
if (pidName.empty()) {
printEvent("process_sort_index", 'M', timestamp, pid, pid, {}, {{"sort_index", pid}});
}
pidName = name;
printName("process_name");
if (tid == pid) {
// always update main thread name when we update the process name
printName("thread_name");
return;
}
}
}
if (tid != INVALID_TID) {
auto& tidName = getTidName(tid);
if (tidName != name) {
tidName = name;
printName("thread_name");
}
}
}
void parseEvent(bt_ctf_event* event);
void handleEvent(const Event& event);
void drainHeldBackEvents(std::vector<Event>& heldBackEvents_forCpu);
void drainHeldBackEvents();
enum KMemType
{
KMalloc,
CacheAlloc,
};
void alloc(uint64_t ptr, const KMemAlloc& alloc, int64_t timestamp, KMemType type)
{
auto& hash = type == KMalloc ? kmem : kmemCached;
auto& current = type == KMalloc ? currentAlloc : currentCached;
hash[ptr] = alloc;
current += alloc;
printCount(type, timestamp);
}
void free(uint64_t ptr, int64_t timestamp, KMemType type)
{
auto& hash = type == KMalloc ? kmem : kmemCached;
auto& current = type == KMalloc ? currentAlloc : currentCached;
current -= hash[ptr];
printCount(type, timestamp);
}
void pageAlloc(uint32_t order, int64_t timestamp)
{
currentKmemPages += pow(2, order);
printCount(CounterGroup::Memory, "mm_page_alloc", currentKmemPages * PAGE_SIZE, timestamp);
}
void pageFree(uint32_t order, int64_t timestamp)
{
currentKmemPages -= pow(2, order);
printCount(CounterGroup::Memory, "mm_page_alloc", currentKmemPages * PAGE_SIZE, timestamp);
}
// swapper is the idle process on linux
static const constexpr int64_t SWAPPER_TID = 0;
void schedSwitch(int64_t prevTid, int64_t prevPid, std::string_view prevComm, int64_t nextTid, int64_t nextPid,
std::string_view nextComm, uint64_t cpuId, int64_t timestamp)
{
if (prevTid == nextTid || isFilteredByTime(timestamp))
return;
if (cores.size() <= cpuId)
cores.resize(cpuId);
auto& core = cores[cpuId];
const bool wasRunning = core.running;
const bool isRunning = nextTid != SWAPPER_TID;
if (wasRunning != isRunning) {
const auto numRunning = std::count_if(cores.begin(), cores.end(), [](auto core) { return core.running; });
printCount(CounterGroup::CPU, "CPU utilization", numRunning, timestamp);
core.running = isRunning;
}
const auto group = dataFor(CounterGroup::CPU, timestamp);
const auto eventTid = CPU_PROCESS_TID_MULTIPLICATOR * static_cast<int64_t>(cpuId + 1);
if (!core.printedCpuStateName) {
printEvent("thread_name", 'M', timestamp, group.id, eventTid, {},
{{"name", "CPU " + std::to_string(cpuId) + " state"}});
core.printedCpuStateName = true;
}
auto printCpuCoreProcessEvent = [this, eventTid, timestamp, group](int64_t tid, char type) {
if (tid == SWAPPER_TID)
return;
if (isFilteredByPid(pid(tid)))
return;
printEvent(commName(tids[tid].name, tid), type, timestamp, group.id, eventTid, "process");
};
printCpuCoreProcessEvent(prevTid, 'E');
printCpuCoreProcessEvent(nextTid, 'B');
// TODO: look into flow events?
if (!isFilteredByPid(prevPid)) {
auto event = eventPrinter("sched_switch", 'B', timestamp, prevPid, prevTid, "sched");
auto args = event.argsPrinter(ArgsType::Object, "args");
auto out = args.argsPrinter(ArgsType::Object, "out");
out.writeField("next_comm", nextComm);
out.writeField("next_pid", nextPid);
out.writeField("next_tid", nextTid);
}
if (!isFilteredByPid(nextPid)) {
auto event = eventPrinter("sched_switch", 'E', timestamp, nextPid, nextTid, "sched");
auto args = event.argsPrinter(ArgsType::Object, "args");
auto out = args.argsPrinter(ArgsType::Object, "in");
out.writeField("prev_comm", prevComm);
out.writeField("prev_pid", prevPid);
out.writeField("prev_tid", prevTid);
}
}
void cpuFrequency(uint64_t cpuId, uint64_t frequency, int64_t timestamp)
{
printCount(CounterGroup::CPU, "CPU " + std::to_string(cpuId) + " frequency", frequency, timestamp);
}
void cpuUsage(const std::string& label, double usage, int64_t timestamp)
{
printCount(CounterGroup::CPU, label + " usage", usage, timestamp);
}
void blockRqIssue(uint64_t dev, uint64_t sector, uint64_t nr_sector, uint64_t bytes, uint64_t rwbs, int64_t tid,
std::string_view comm, int64_t timestamp)
{
if (isFilteredByTime(timestamp))
return;
const auto pid = this->pid(tid);
if (isFilteredByPid(pid))
return;
auto device_it = blockDevices.find(dev);
if (device_it == blockDevices.end())
return;
auto& device = device_it->second;
const auto group = dataFor(CounterGroup::Block, timestamp);
const auto eventTid = BLOCK_TID_OFFFSET - dev;
if (!device.printedDeviceName) {
printEvent("thread_name", 'M', timestamp, group.id, eventTid, {}, {{"name", device.name + " requests"}});
device.printedDeviceName = true;
}
device.bytesPending += bytes;
device.requests[sector] = {bytes, std::string(comm), tid};
printCount(CounterGroup::Block, device.name + " bytes pending", device.bytesPending, timestamp);
printEvent(commName(comm, tid), 'B', timestamp, group.id, eventTid, "block",
{{"sector", sector}, {"nr_sector", nr_sector}, {"bytes", bytes}, {"rwbs", rwbsToString(rwbs)}});
auto& pidData = pids[pid];
pidData.blockIoBytesPending += bytes;
printCounterValue("block I/O bytes pending", timestamp, pid, pidData.blockIoBytesPending);
}
void blockRqRequeue(uint64_t dev, uint64_t sector, int64_t timestamp)
{
finishBlockRequest(
dev, sector, timestamp, [this](const auto& comm, auto tid, auto groupId, auto eventTid, auto timestamp) {
printEvent(commName(comm, tid), 'E', timestamp, groupId, eventTid, "block", {{"error", "requeue"}});
});
}
void blockRqComplete(uint64_t dev, uint64_t sector, int64_t error, int64_t timestamp)
{
finishBlockRequest(