1 /*
2 * Copyright (C) 2020 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 "ProbeEvents.h"
18
19 #include <inttypes.h>
20
21 #include <memory>
22 #include <string>
23
24 #include <android-base/file.h>
25 #include <android-base/logging.h>
26 #include <android-base/parseint.h>
27 #include <android-base/stringprintf.h>
28 #include <android-base/strings.h>
29 #include <android-base/unique_fd.h>
30
31 #include "RegEx.h"
32 #include "environment.h"
33 #include "event_selection_set.h"
34 #include "event_type.h"
35 #include "utils.h"
36
37 namespace simpleperf {
38
39 using android::base::ParseInt;
40 using android::base::ParseUint;
41 using android::base::Split;
42 using android::base::StringPrintf;
43 using android::base::unique_fd;
44 using android::base::WriteStringToFd;
45
46 static const std::string kKprobeEventPrefix = "kprobes:";
47
ParseKprobeEventName(const std::string & kprobe_cmd,ProbeEvent * event)48 bool ProbeEvents::ParseKprobeEventName(const std::string& kprobe_cmd, ProbeEvent* event) {
49 // kprobe_cmd is in formats described in <kernel>/Documentation/trace/kprobetrace.rst:
50 // p[:[GRP/]EVENT] [MOD:]SYM[+offs]|MEMADDR [FETCHARGS]
51 // r[MAXACTIVE][:[GRP/]EVENT] [MOD:]SYM[+offs] [FETCHARGS]
52 std::vector<std::string> args = Split(kprobe_cmd, " ");
53 if (args.size() < 2) {
54 return false;
55 }
56
57 // Parse given name.
58 event->group_name = "kprobes";
59 auto name_reg = RegEx::Create(R"(:([a-zA-Z_][\w_]*/)?([a-zA-Z_][\w_]*))");
60 auto match = name_reg->SearchAll(args[0]);
61 if (match->IsValid()) {
62 if (match->GetField(1).length() > 0) {
63 event->group_name = match->GetField(1);
64 event->group_name.pop_back();
65 }
66 event->event_name = match->GetField(2);
67 return true;
68 }
69
70 // Generate name from MEMADDR.
71 char probe_type = args[0][0];
72 uint64_t kaddr;
73 if (ParseUint(args[1], &kaddr)) {
74 event->event_name = StringPrintf("%c_0x%" PRIx64, probe_type, kaddr);
75 return true;
76 }
77
78 // Generate name from [MOD:]SYM[+offs].
79 std::string symbol;
80 int64_t offset;
81 size_t split_pos = args[1].find_first_of("+-");
82 if (split_pos == std::string::npos) {
83 symbol = args[1];
84 offset = 0;
85 } else {
86 symbol = args[1].substr(0, split_pos);
87 if (!ParseInt(args[1].substr(split_pos), &offset) || offset < 0) {
88 return false;
89 }
90 }
91 std::string s = StringPrintf("%c_%s_%" PRId64, probe_type, symbol.c_str(), offset);
92 event->event_name = RegEx::Create(R"(\.|:)")->Replace(s, "_").value();
93 return true;
94 }
95
~ProbeEvents()96 ProbeEvents::~ProbeEvents() {
97 if (!IsEmpty()) {
98 // Probe events can be deleted only when no perf event file is using them.
99 event_selection_set_.CloseEventFiles();
100 Clear();
101 }
102 }
103
IsKprobeSupported()104 bool ProbeEvents::IsKprobeSupported() {
105 if (!kprobe_control_path_.has_value()) {
106 kprobe_control_path_ = "";
107 if (const char* tracefs_dir = GetTraceFsDir(); tracefs_dir != nullptr) {
108 std::string path = std::string(tracefs_dir) + "/kprobe_events";
109 if (IsRegularFile(path)) {
110 kprobe_control_path_ = std::move(path);
111 }
112 }
113 }
114 return !kprobe_control_path_.value().empty();
115 }
116
AddKprobe(const std::string & kprobe_cmd)117 bool ProbeEvents::AddKprobe(const std::string& kprobe_cmd) {
118 ProbeEvent event;
119 if (!ParseKprobeEventName(kprobe_cmd, &event)) {
120 LOG(ERROR) << "invalid kprobe cmd: " << kprobe_cmd;
121 return false;
122 }
123 if (!WriteKprobeCmd(kprobe_cmd)) {
124 return false;
125 }
126 kprobe_events_.emplace_back(std::move(event));
127 return true;
128 }
129
IsProbeEvent(const std::string & event_name)130 bool ProbeEvents::IsProbeEvent(const std::string& event_name) {
131 return android::base::StartsWith(event_name, kKprobeEventPrefix);
132 }
133
CreateProbeEventIfNotExist(const std::string & event_name)134 bool ProbeEvents::CreateProbeEventIfNotExist(const std::string& event_name) {
135 if (!IsProbeEvent(event_name) || (EventTypeManager::Instance().FindType(event_name) != nullptr)) {
136 // No need to create a probe event.
137 return true;
138 }
139 std::string function_name = event_name.substr(kKprobeEventPrefix.size());
140 return AddKprobe(StringPrintf("p:%s %s", function_name.c_str(), function_name.c_str()));
141 }
142
Clear()143 void ProbeEvents::Clear() {
144 for (const auto& kprobe_event : kprobe_events_) {
145 if (!WriteKprobeCmd("-:" + kprobe_event.group_name + "/" + kprobe_event.event_name)) {
146 LOG(WARNING) << "failed to delete kprobe event " << kprobe_event.group_name << ":"
147 << kprobe_event.event_name;
148 }
149 EventTypeManager::Instance().RemoveProbeType(kprobe_event.group_name + ":" +
150 kprobe_event.event_name);
151 }
152 kprobe_events_.clear();
153 }
154
WriteKprobeCmd(const std::string & kprobe_cmd)155 bool ProbeEvents::WriteKprobeCmd(const std::string& kprobe_cmd) {
156 if (!IsKprobeSupported()) {
157 LOG(ERROR) << "kprobe events isn't supported by the kernel.";
158 return false;
159 }
160 const std::string& path = kprobe_control_path_.value();
161 unique_fd fd(open(path.c_str(), O_APPEND | O_WRONLY | O_CLOEXEC));
162 if (!fd.ok()) {
163 PLOG(ERROR) << "failed to open " << path;
164 return false;
165 }
166 if (!WriteStringToFd(kprobe_cmd, fd)) {
167 PLOG(ERROR) << "failed to write '" << kprobe_cmd << "' to " << path;
168 return false;
169 }
170 return true;
171 }
172
173 } // namespace simpleperf
174