Skip to content

Commit 99f3f4a

Browse files
committed
Slightly safer linux perf counters
1 parent 64463d4 commit 99f3f4a

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

benchmarks/performancecounters/linux-perf-events.h

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// https://github.com/WojciechMula/toys/blob/master/000helpers/linux-perf-events.h
21
#pragma once
32
#ifdef __linux__
43

@@ -44,14 +43,15 @@ class LinuxEvents {
4443
uint32_t i = 0;
4544
for (auto config : config_vec) {
4645
attribs.config = config;
47-
fd = static_cast<int>(
46+
int _fd = static_cast<int>(
4847
syscall(__NR_perf_event_open, &attribs, pid, cpu, group, flags));
49-
if (fd == -1) {
48+
if (_fd == -1) {
5049
report_error("perf_event_open");
5150
}
52-
ioctl(fd, PERF_EVENT_IOC_ID, &ids[i++]);
51+
ioctl(_fd, PERF_EVENT_IOC_ID, &ids[i++]);
5352
if (group == -1) {
54-
group = fd;
53+
group = _fd;
54+
fd = _fd;
5555
}
5656
}
5757

@@ -87,15 +87,19 @@ class LinuxEvents {
8787
}
8888
}
8989
// our actual results are in slots 1,3,5, ... of this structure
90-
// we really should be checking our ids obtained earlier to be safe
9190
for (uint32_t i = 1; i < temp_result_vec.size(); i += 2) {
9291
results[i / 2] = temp_result_vec[i];
9392
}
93+
for (uint32_t i = 2; i < temp_result_vec.size(); i += 2) {
94+
if (ids[i / 2 - 1] != temp_result_vec[i]) {
95+
report_error("event mismatch");
96+
}
97+
}
9498
}
9599

96100
bool is_working() { return working; }
97101

98102
private:
99103
void report_error(const std::string &) { working = false; }
100104
};
101-
#endif
105+
#endif

0 commit comments

Comments
 (0)