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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
extern crate alloc;
use core::fmt;
use alloc::string;
use alloc::vec;
use crate::*;
use perf_field_format::ascii_to_u32;
use perf_field_format::consume_string;
use perf_field_format::is_space_or_tab;
/// This macro is used in certain edge cases that I don't expect to happen in normal
/// `format` files. The code treats these as errors. The macro provides an easy way
/// to make an instrumented build that reports these cases.
///
/// At present, does nothing.
macro_rules! debug_eprintln {
($($arg:tt)*) => {};
}
/// Values for the DecodingStyle property of PerfEventFormat.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PerfEventDecodingStyle {
/// Event should be decoded using tracefs "format" file.
TraceEventFormat,
/// Event contains embedded "EventHeader" metadata and should be decoded using
/// [`EventHeaderEnumerator`]. (TraceEvent decoding information is present, but the
/// first TraceEvent-format field is named "eventheader_flags".)
EventHeader,
}
impl fmt::Display for PerfEventDecodingStyle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let str = match self {
Self::TraceEventFormat => "TraceEventFormat",
Self::EventHeader => "EventHeader",
};
return f.pad(str);
}
}
/// Event information parsed from a tracefs "format" file.
#[derive(Debug)]
pub struct PerfEventFormat {
system_name: string::String,
name: string::String,
print_fmt: string::String,
fields: vec::Vec<PerfFieldFormat>,
id: u32,
common_field_count: u16,
common_fields_size: u16,
decoding_style: PerfEventDecodingStyle,
}
impl PerfEventFormat {
/// Parses an event's "format" file and sets the fields of this object based
/// on the results.
///
/// - `long_is_64_bits`:
/// Indicates the size to use for "long" fields in this event.
/// true if sizeof(long) == 8, false if sizeof(long) == 4.
///
/// - `system_name`:
/// The name of the system. For example, the system_name for "user_events:my_event"
/// would be "user_events".
///
/// - `format_file_contents`:
/// The contents of the "format" file. This is typically obtained from tracefs,
/// e.g. the format_file_contents for "user_events:my_event" will usually be the
/// contents of "/sys/kernel/tracing/events/user_events/my_event/format".
///
/// If "ID:" is a valid unsigned and and "name:" is not empty, returns
/// a usable value. Otherwise, returns an `EMPTY` value.
pub fn parse(
long_is_64_bits: bool,
system_name: &str,
format_file_contents: &str,
) -> Option<Self> {
let mut name = "";
let mut print_fmt = "";
let mut fields = vec::Vec::new();
let mut id = None;
let mut common_field_count = 0u16;
let format_bytes = format_file_contents.as_bytes();
// Search for lines like "NAME: VALUE..."
let mut pos = 0;
'NextLine: while pos < format_bytes.len() {
// Skip any newlines.
while is_eol_char(format_bytes[pos]) {
pos += 1;
if pos >= format_bytes.len() {
break 'NextLine;
}
}
// Skip spaces.
while is_space_or_tab(format_bytes[pos]) {
debug_eprintln!("Space before propname in event");
pos += 1; // Unexpected.
if pos >= format_bytes.len() {
break 'NextLine;
}
}
// "NAME:"
let prop_name_pos = pos;
while format_bytes[pos] != b':' {
if is_eol_char(format_bytes[pos]) {
debug_eprintln!("EOL before ':' in format");
continue 'NextLine; // Unexpected.
}
pos += 1;
if pos >= format_bytes.len() {
debug_eprintln!("EOF before ':' in format");
break 'NextLine; // Unexpected.
}
}
let prop_name = &format_bytes[prop_name_pos..pos];
pos += 1; // Skip ':'
// Skip spaces.
while pos < format_bytes.len() && is_space_or_tab(format_bytes[pos]) {
pos += 1;
}
let prop_value_pos = pos;
// "VALUE..."
while pos < format_bytes.len() && !is_eol_char(format_bytes[pos]) {
let consumed = format_bytes[pos];
pos += 1;
if consumed == b'"' {
pos = consume_string(pos, format_bytes, b'"');
}
}
// Did we find something we can use?
if prop_name == b"name" {
name = &format_file_contents[prop_value_pos..pos];
} else if prop_name == b"ID" && pos < format_bytes.len() {
id = ascii_to_u32(&format_bytes[prop_value_pos..pos]);
} else if prop_name == b"print fmt" {
print_fmt = &format_file_contents[prop_value_pos..pos];
} else if prop_name == b"format" {
let mut common = true;
fields.clear();
// Search for lines like: " field:TYPE NAME; offset:N; size:N; signed:N;"
while pos < format_bytes.len() {
debug_assert!(
is_eol_char(format_bytes[pos]),
"Loop should only repeat at EOL"
);
if format_bytes.len() - pos >= 2
&& format_bytes[pos] == b'\r'
&& format_bytes[pos + 1] == b'\n'
{
pos += 2; // Skip CRLF.
} else {
pos += 1; // Skip CR or LF.
}
let line_start_pos = pos;
while pos < format_bytes.len() && !is_eol_char(format_bytes[pos]) {
pos += 1;
}
if line_start_pos == pos {
// Blank line.
if common {
// First blank line means we're done with common fields.
common = false;
continue;
} else {
// Second blank line means we're done with format.
break;
}
}
let field = PerfFieldFormat::parse(
long_is_64_bits,
&format_file_contents[line_start_pos..pos],
);
if let Some(field) = field {
fields.push(field);
if common {
common_field_count += 1;
}
} else {
debug_eprintln!("Field parse failure");
}
}
}
}
match id {
Some(id) if !name.is_empty() => {
let common_fields_size = if common_field_count == 0 {
0
} else {
let last_common_field = &fields[common_field_count as usize - 1];
last_common_field.offset() + last_common_field.size()
};
let decoding_style = if fields.len() > common_field_count as usize
&& fields[common_field_count as usize].name() == "eventheader_flags"
{
PerfEventDecodingStyle::EventHeader
} else {
PerfEventDecodingStyle::TraceEventFormat
};
return Some(Self {
system_name: string::String::from(system_name),
name: string::String::from(name),
print_fmt: string::String::from(print_fmt),
fields,
id,
common_field_count,
common_fields_size,
decoding_style,
});
}
_ => {
return None;
}
}
}
/// Returns the value of the `system_name` parameter provided to the constructor,
/// e.g. `"user_events"`.
pub fn system_name(&self) -> &str {
&self.system_name
}
/// Returns the value of the "name:" property, e.g. `"my_event"`.
pub fn name(&self) -> &str {
&self.name
}
/// Returns the value of the "print fmt:" property.
pub fn print_fmt(&self) -> &str {
&self.print_fmt
}
/// Returns the fields from the "format:" property.
pub fn fields(&self) -> &[PerfFieldFormat] {
&self.fields
}
/// Returns the value of the "ID:" property. Note that this value gets
/// matched against the "common_type" field of an event, not the id field
/// of perf_event_attr or PerfSampleEventInfo.
pub fn id(&self) -> u32 {
self.id
}
/// Returns the number of "common_*" fields at the start of the event.
/// User fields start at this index. At present, there are 4 common fields:
/// common_type, common_flags, common_preempt_count, common_pid.
pub fn common_field_count(&self) -> usize {
self.common_field_count as usize
}
/// Returns the offset of the end of the last "common_*" field.
/// This is the offset of the first user field.
pub fn common_fields_size(&self) -> u16 {
self.common_fields_size
}
/// Returns the detected event decoding system - `TraceEventFormat` or `EventHeader`.
pub fn decoding_style(&self) -> PerfEventDecodingStyle {
self.decoding_style
}
/// Writes a string representation of this format to the provided string.
/// The string representation is in the format of a tracefs "format" file.
pub fn write_to<W: fmt::Write>(&self, s: &mut W) -> fmt::Result {
writeln!(s, "name: {}", self.name())?;
writeln!(s, "ID: {}", self.id())?;
s.write_str("format:\n")?;
let common_field_count = self.common_field_count();
for (i, field) in self.fields().iter().enumerate() {
write!(
s,
"\tfield:{};\toffset:{};\tsize:{};",
field.field(),
field.offset(),
field.size(),
)?;
if let Some(signed) = field.signed() {
writeln!(s, "\tsigned:{};", signed as u8)?;
} else {
s.write_str("\n")?;
}
if i + 1 == common_field_count {
s.write_str("\n")?;
}
}
return writeln!(s, "\nprint fmt: {}", self.print_fmt());
}
}
fn is_eol_char(c: u8) -> bool {
c == b'\r' || c == b'\n'
}