1 /*
2 * Copyright (C) 2024 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "src/trace_processor/importers/perf/attrs_section_reader.h"
18
19 #include <cinttypes>
20
21 #include "perfetto/base/logging.h"
22 #include "perfetto/base/status.h"
23 #include "perfetto/trace_processor/trace_blob_view.h"
24 #include "src/trace_processor/importers/perf/perf_file.h"
25
26 namespace perfetto::trace_processor::perf_importer {
27
28 // static
Create(const PerfFile::Header & header,TraceBlobView section)29 base::StatusOr<AttrsSectionReader> AttrsSectionReader::Create(
30 const PerfFile::Header& header,
31 TraceBlobView section) {
32 PERFETTO_CHECK(section.size() == header.attrs.size);
33
34 if (header.attr_size == 0) {
35 return base::ErrStatus("Invalid attr_size (0) in perf file header.");
36 }
37
38 if (header.attrs.size % header.attr_size != 0) {
39 return base::ErrStatus("Invalid attrs section size %" PRIu64
40 " for attr_size %" PRIu64 " in perf file header.",
41 header.attrs.size, header.attr_size);
42 }
43
44 const size_t num_attr = header.attrs.size / header.attr_size;
45
46 // Each entry is a perf_event_attr followed by a Section, but the size of
47 // the perf_event_attr struct written in the file might not be the same as
48 // sizeof(perf_event_attr) as this struct might grow over time (can be
49 // bigger or smaller).
50 static constexpr size_t kSectionSize = sizeof(PerfFile::Section);
51 if (header.attr_size < kSectionSize) {
52 return base::ErrStatus(
53 "Invalid attr_size in file header. Expected at least %zu, found "
54 "%" PRIu64,
55 kSectionSize, header.attr_size);
56 }
57 const size_t attr_size = header.attr_size - kSectionSize;
58
59 return AttrsSectionReader(std::move(section), num_attr, attr_size);
60 }
61
ReadNext(PerfFile::AttrsEntry & entry)62 base::Status AttrsSectionReader::ReadNext(PerfFile::AttrsEntry& entry) {
63 PERFETTO_CHECK(reader_.ReadPerfEventAttr(entry.attr, attr_size_));
64
65 if (entry.attr.size != attr_size_) {
66 return base::ErrStatus(
67 "Invalid attr.size. Expected %zu, but found %" PRIu32, attr_size_,
68 entry.attr.size);
69 }
70
71 PERFETTO_CHECK(reader_.Read(entry.ids));
72 --num_attr_;
73 return base::OkStatus();
74 }
75
76 } // namespace perfetto::trace_processor::perf_importer
77