1 /*
2  * Copyright (C) 2017 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 "InplaceSamplerClient.h"
18 
19 #include <algorithm>
20 
21 #include "environment.h"
22 #include "inplace_sampler_lib.h"
23 #include "utils.h"
24 
25 static constexpr uint64_t EVENT_ID_FOR_INPLACE_SAMPLER = ULONG_MAX;
26 
Create(const perf_event_attr & attr,pid_t pid,const std::set<pid_t> & tids)27 std::unique_ptr<InplaceSamplerClient> InplaceSamplerClient::Create(const perf_event_attr& attr,
28                                                                    pid_t pid,
29                                                                    const std::set<pid_t>& tids) {
30   if (pid == -1) {
31     LOG(ERROR) << "inplace-sampler can't monitor system wide events.";
32     return nullptr;
33   }
34   std::unique_ptr<InplaceSamplerClient> sampler(new InplaceSamplerClient(attr, pid, tids));
35   if (!sampler->ConnectServer()) {
36     return nullptr;
37   }
38   return sampler;
39 }
40 
InplaceSamplerClient(const perf_event_attr & attr,pid_t pid,const std::set<pid_t> & tids)41 InplaceSamplerClient::InplaceSamplerClient(const perf_event_attr& attr, pid_t pid,
42                                            const std::set<pid_t>& tids)
43     : attr_(attr), pid_(pid), tids_(tids), got_start_profiling_reply_msg_(false) {
44   if (attr_.freq) {
45     sample_freq_ = attr_.sample_freq;
46   } else {
47     sample_freq_ = std::max(1u, static_cast<uint32_t>(1000000000 / attr_.sample_period));
48   }
49 }
50 
Id() const51 uint64_t InplaceSamplerClient::Id() const {
52   return EVENT_ID_FOR_INPLACE_SAMPLER;
53 }
54 
ConnectServer()55 bool InplaceSamplerClient::ConnectServer() {
56   std::string server_path = "inplace_sampler_server_" + std::to_string(pid_);
57   // Try to connect server in 1s.
58   uint64_t timeout = GetSystemClock() + 10000000000ull;
59   while (GetSystemClock() < timeout) {
60     conn_ = UnixSocketConnection::Connect(server_path, true);
61     if (conn_ != nullptr) {
62       return true;
63     }
64     usleep(10);
65   }
66   LOG(ERROR) << "Can't find inplace_sampler_server for process " << pid_;
67   return false;
68 }
69 
StartPolling(IOEventLoop & loop,const std::function<bool (Record *)> & record_callback,const std::function<bool ()> & close_callback)70 bool InplaceSamplerClient::StartPolling(IOEventLoop& loop,
71                                         const std::function<bool(Record*)>& record_callback,
72                                         const std::function<bool()>& close_callback) {
73   record_callback_ = record_callback;
74   CHECK(conn_ != nullptr);
75   auto read_callback = [&](const UnixSocketMessage& msg) {
76     return HandleMessage(msg);
77   };
78   if (!conn_->PrepareForIO(loop, read_callback, close_callback)) {
79     return false;
80   }
81   if (!SendStartProfilingMessage()) {
82     return false;
83   }
84   // If the inplace sampler doesn't reply in 3 seconds, report the error.
85   timeval tv;
86   tv.tv_sec = 3;
87   tv.tv_usec = 0;
88   auto check_reply_callback = [this]() {
89     if (!got_start_profiling_reply_msg_) {
90       LOG(ERROR) << "can't receive START_PROFILING_REPLY from process " << pid_;
91       return false;
92     }
93     return true;
94   };
95   return loop.AddPeriodicEvent(tv, check_reply_callback);
96 }
97 
SendStartProfilingMessage()98 bool InplaceSamplerClient::SendStartProfilingMessage() {
99   std::string options;
100   options += "freq=" + std::to_string(sample_freq_);
101   if (attr_.sample_type & PERF_SAMPLE_CALLCHAIN) {
102     options += " dump_callchain=1";
103   }
104   if (!tids_.empty()) {
105     options += " tids=";
106     bool first = true;
107     for (auto& tid : tids_) {
108       if (first) {
109         first = false;
110       } else {
111         options.push_back(',');
112       }
113       options += std::to_string(tid);
114     }
115   }
116   size_t size = sizeof(UnixSocketMessage) + options.size() + 1;
117   std::unique_ptr<char[]> data(new char[size]);
118   UnixSocketMessage* msg = reinterpret_cast<UnixSocketMessage*>(data.get());
119   msg->len = size;
120   msg->type = START_PROFILING;
121   strcpy(msg->data, options.c_str());
122   return conn_->SendMessage(*msg, true);
123 }
124 
StopProfiling(IOEventLoop & loop,const std::function<bool ()> & close_callback)125 bool InplaceSamplerClient::StopProfiling(IOEventLoop& loop,
126                                          const std::function<bool()>& close_callback) {
127   auto read_callback = [&](const UnixSocketMessage& msg) {
128     return HandleMessage(msg);
129   };
130   if (!conn_->PrepareForIO(loop, read_callback, close_callback)) {
131     return false;
132   }
133   // Notify inplace sampler to send buffered data and close the connection.
134   UnixSocketMessage msg;
135   msg.len = sizeof(UnixSocketMessage);
136   msg.type = END_PROFILING;
137   return conn_->SendMessage(msg, true);
138 }
139 
HandleMessage(const UnixSocketMessage & msg)140 bool InplaceSamplerClient::HandleMessage(const UnixSocketMessage& msg) {
141   const char* p = msg.data;
142   if (msg.type == START_PROFILING_REPLY) {
143       got_start_profiling_reply_msg_ = true;
144       if (strcmp(p, "ok") != 0) {
145         LOG(ERROR) << "receive reply from inplace_sampler_server of " << pid_ << ": " << p;
146         return false;
147       }
148   } else if (msg.type == THREAD_INFO) {
149     uint64_t time;
150     uint32_t tid;
151     MoveFromBinaryFormat(time, p);
152     MoveFromBinaryFormat(tid, p);
153     CommRecord r(attr_, pid_, tid, p, Id(), time);
154     if (!record_callback_(&r)) {
155       return false;
156     }
157   } else if (msg.type == MAP_INFO) {
158     uint64_t time;
159     uint64_t start;
160     uint64_t len;
161     uint64_t pgoff;
162     MoveFromBinaryFormat(time, p);
163     MoveFromBinaryFormat(start, p);
164     MoveFromBinaryFormat(len, p);
165     MoveFromBinaryFormat(pgoff, p);
166     MmapRecord r(attr_, false, pid_, pid_, start, len, pgoff, p, Id(), time);
167     if (!record_callback_(&r)) {
168       return false;
169     }
170   } else if (msg.type == SAMPLE_INFO) {
171     uint64_t time;
172     uint32_t tid;
173     uint32_t period;
174     uint32_t ip_nr;
175     MoveFromBinaryFormat(time, p);
176     MoveFromBinaryFormat(tid, p);
177     MoveFromBinaryFormat(period, p);
178     MoveFromBinaryFormat(ip_nr, p);
179     std::vector<uint64_t> ips(ip_nr);
180     MoveFromBinaryFormat(ips.data(), ip_nr, p);
181     // Don't know which cpu tid is running on, use cpu 0.
182     SampleRecord r(attr_, Id(), ips[0], pid_, tid, time, 0, period, ips);
183     if (!record_callback_(&r)) {
184       return false;
185     }
186   } else {
187     LOG(ERROR) << "Unexpected msg type: " << msg.type;
188     return false;
189   }
190   return true;
191 }
192