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