1 /*
2  * Copyright 2016, 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 <debuggerd/client.h>
18 
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <stdlib.h>
22 #include <sys/poll.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <time.h>
26 #include <unistd.h>
27 
28 #include <chrono>
29 #include <iomanip>
30 
31 #include <android-base/cmsg.h>
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
34 #include <android-base/parseint.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <android-base/unique_fd.h>
38 #include <bionic/reserved_signals.h>
39 #include <cutils/sockets.h>
40 #include <procinfo/process.h>
41 
42 #include "debuggerd/handler.h"
43 #include "protocol.h"
44 #include "util.h"
45 
46 using namespace std::chrono_literals;
47 
48 using android::base::ReadFileToString;
49 using android::base::SendFileDescriptors;
50 using android::base::StringAppendV;
51 using android::base::unique_fd;
52 using android::base::WriteStringToFd;
53 
54 #define TAG "libdebuggerd_client: "
55 
56 // Log an error both to the log (via LOG(ERROR)) and to the given fd.
log_error(int fd,int errno_value,const char * format,...)57 static void log_error(int fd, int errno_value, const char* format, ...) __printflike(3, 4) {
58   std::string message(TAG);
59 
60   va_list ap;
61   va_start(ap, format);
62   StringAppendV(&message, format, ap);
63   va_end(ap);
64 
65   if (errno_value != 0) {
66     message = message + ": " + strerror(errno_value);
67   }
68 
69   if (fd != -1) {
70     dprintf(fd, "%s\n", message.c_str());
71   }
72 
73   LOG(ERROR) << message;
74 }
75 
76 template <typename Duration>
populate_timeval(struct timeval * tv,const Duration & duration)77 static void populate_timeval(struct timeval* tv, const Duration& duration) {
78   auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
79   auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(duration - seconds);
80   tv->tv_sec = static_cast<long>(seconds.count());
81   tv->tv_usec = static_cast<long>(microseconds.count());
82 }
83 
84 /**
85  * Returns the wchan data for each thread in the process,
86  * or empty string if unable to obtain any data.
87  */
get_wchan_data(int fd,pid_t pid)88 static std::string get_wchan_data(int fd, pid_t pid) {
89   std::vector<pid_t> tids;
90   if (!android::procinfo::GetProcessTids(pid, &tids)) {
91     log_error(fd, 0, "failed to get process tids");
92     return "";
93   }
94 
95   std::stringstream data;
96   for (int tid : tids) {
97     std::string path = "/proc/" + std::to_string(pid) + "/task/" + std::to_string(tid) + "/wchan";
98     std::string wchan_str;
99     if (!ReadFileToString(path, &wchan_str, true)) {
100       log_error(fd, errno, "failed to read \"%s\"", path.c_str());
101       continue;
102     }
103     data << "sysTid=" << std::left << std::setw(10) << tid << wchan_str << "\n";
104   }
105 
106   std::stringstream buffer;
107   if (std::string str = data.str(); !str.empty()) {
108     buffer << "\n----- Waiting Channels: pid " << pid << " at " << get_timestamp() << " -----\n"
109            << "Cmd line: " << android::base::Join(get_command_line(pid), " ") << "\n";
110     buffer << "\n" << str << "\n";
111     buffer << "----- end " << std::to_string(pid) << " -----\n";
112     buffer << "\n";
113   }
114   return buffer.str();
115 }
116 
debuggerd_trigger_dump(pid_t tid,DebuggerdDumpType dump_type,unsigned int timeout_ms,unique_fd output_fd)117 bool debuggerd_trigger_dump(pid_t tid, DebuggerdDumpType dump_type, unsigned int timeout_ms,
118                             unique_fd output_fd) {
119   pid_t pid = tid;
120   if (dump_type == kDebuggerdJavaBacktrace) {
121     // Java dumps always get sent to the tgid, so we need to resolve our tid to a tgid.
122     android::procinfo::ProcessInfo procinfo;
123     std::string error;
124     if (!android::procinfo::GetProcessInfo(tid, &procinfo, &error)) {
125       log_error(output_fd, 0, "failed to get process info: %s", error.c_str());
126       return false;
127     }
128     pid = procinfo.pid;
129   }
130 
131   LOG(INFO) << TAG "started dumping process " << pid;
132 
133   // Rather than try to deal with poll() all the way through the flow, we update
134   // the socket timeout between each step (and only use poll() during the final
135   // copy loop).
136   const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
137   auto update_timeout = [timeout_ms, &output_fd](int sockfd, auto end) {
138     if (timeout_ms <= 0) return true;
139 
140     auto remaining = end - std::chrono::steady_clock::now();
141     if (remaining < decltype(remaining)::zero()) {
142       log_error(output_fd, 0, "timeout expired");
143       return false;
144     }
145 
146     struct timeval timeout;
147     populate_timeval(&timeout, remaining);
148     if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0) {
149       log_error(output_fd, errno, "failed to set receive timeout");
150       return false;
151     }
152     if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) != 0) {
153       log_error(output_fd, errno, "failed to set send timeout");
154       return false;
155     }
156     return true;
157   };
158 
159   unique_fd sockfd(socket(AF_LOCAL, SOCK_SEQPACKET, 0));
160   if (sockfd == -1) {
161     log_error(output_fd, errno, "failed to create socket");
162     return false;
163   }
164 
165   if (!update_timeout(sockfd, end)) return false;
166 
167   if (socket_local_client_connect(sockfd.get(), kTombstonedInterceptSocketName,
168                                   ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET) == -1) {
169     log_error(output_fd, errno, "failed to connect to tombstoned");
170     return false;
171   }
172 
173   InterceptRequest req = {
174       .dump_type = dump_type,
175       .pid = pid,
176   };
177 
178   // Create an intermediate pipe to pass to the other end.
179   unique_fd pipe_read, pipe_write;
180   if (!Pipe(&pipe_read, &pipe_write)) {
181     log_error(output_fd, errno, "failed to create pipe");
182     return false;
183   }
184 
185   std::string pipe_size_str;
186   int pipe_buffer_size = 1024 * 1024;
187   if (android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
188     pipe_size_str = android::base::Trim(pipe_size_str);
189 
190     if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
191       LOG(FATAL) << "failed to parse pipe max size '" << pipe_size_str << "'";
192     }
193   }
194 
195   if (fcntl(pipe_read.get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
196     log_error(output_fd, errno, "failed to set pipe buffer size");
197   }
198 
199   if (!update_timeout(sockfd, end)) return false;
200   ssize_t rc = SendFileDescriptors(sockfd, &req, sizeof(req), pipe_write.get());
201   pipe_write.reset();
202   if (rc != sizeof(req)) {
203     log_error(output_fd, errno, "failed to send output fd to tombstoned");
204     return false;
205   }
206 
207   auto get_response = [&output_fd](const char* kind, int sockfd, InterceptResponse* response) {
208     ssize_t rc = TEMP_FAILURE_RETRY(recv(sockfd, response, sizeof(*response), MSG_TRUNC));
209     if (rc == 0) {
210       log_error(output_fd, 0, "failed to read %s response from tombstoned: timeout reached?", kind);
211       return false;
212     } else if (rc == -1) {
213       log_error(output_fd, errno, "failed to read %s response from tombstoned", kind);
214       return false;
215     } else if (rc != sizeof(*response)) {
216       log_error(output_fd, 0,
217                 "received packet of unexpected length from tombstoned while reading %s response: "
218                 "expected %zd, received %zd",
219                 kind, sizeof(*response), rc);
220       return false;
221     }
222     return true;
223   };
224 
225   // Check to make sure we've successfully registered.
226   InterceptResponse response;
227   if (!update_timeout(sockfd, end)) return false;
228   if (!get_response("initial", sockfd, &response)) return false;
229   if (response.status != InterceptStatus::kRegistered) {
230     log_error(output_fd, 0, "unexpected registration response: %d",
231               static_cast<int>(response.status));
232     return false;
233   }
234 
235   // Send the signal.
236   const int signal = (dump_type == kDebuggerdJavaBacktrace) ? SIGQUIT : BIONIC_SIGNAL_DEBUGGER;
237   sigval val = {.sival_int = (dump_type == kDebuggerdNativeBacktrace) ? 1 : 0};
238   if (sigqueue(pid, signal, val) != 0) {
239     log_error(output_fd, errno, "failed to send signal to pid %d", pid);
240     return false;
241   }
242 
243   if (!update_timeout(sockfd, end)) return false;
244   if (!get_response("status", sockfd, &response)) return false;
245   if (response.status != InterceptStatus::kStarted) {
246     response.error_message[sizeof(response.error_message) - 1] = '\0';
247     log_error(output_fd, 0, "tombstoned reported failure: %s", response.error_message);
248     return false;
249   }
250 
251   // Forward output from the pipe to the output fd.
252   while (true) {
253     auto remaining = end - std::chrono::steady_clock::now();
254     auto remaining_ms = std::chrono::duration_cast<std::chrono::milliseconds>(remaining).count();
255     if (timeout_ms <= 0) {
256       remaining_ms = -1;
257     } else if (remaining_ms < 0) {
258       log_error(output_fd, 0, "timeout expired");
259       return false;
260     }
261 
262     struct pollfd pfd = {
263         .fd = pipe_read.get(), .events = POLLIN, .revents = 0,
264     };
265 
266     rc = poll(&pfd, 1, remaining_ms);
267     if (rc == -1) {
268       if (errno == EINTR) {
269         continue;
270       } else {
271         log_error(output_fd, errno, "error while polling");
272         return false;
273       }
274     } else if (rc == 0) {
275       log_error(output_fd, 0, "timeout expired");
276       return false;
277     }
278 
279     char buf[1024];
280     rc = TEMP_FAILURE_RETRY(read(pipe_read.get(), buf, sizeof(buf)));
281     if (rc == 0) {
282       // Done.
283       break;
284     } else if (rc == -1) {
285       log_error(output_fd, errno, "error while reading");
286       return false;
287     }
288 
289     if (!android::base::WriteFully(output_fd.get(), buf, rc)) {
290       log_error(output_fd, errno, "error while writing");
291       return false;
292     }
293   }
294 
295   LOG(INFO) << TAG "done dumping process " << pid;
296 
297   return true;
298 }
299 
dump_backtrace_to_file(pid_t tid,DebuggerdDumpType dump_type,int fd)300 int dump_backtrace_to_file(pid_t tid, DebuggerdDumpType dump_type, int fd) {
301   return dump_backtrace_to_file_timeout(tid, dump_type, 0, fd);
302 }
303 
dump_backtrace_to_file_timeout(pid_t tid,DebuggerdDumpType dump_type,int timeout_secs,int fd)304 int dump_backtrace_to_file_timeout(pid_t tid, DebuggerdDumpType dump_type, int timeout_secs,
305                                    int fd) {
306   android::base::unique_fd copy(dup(fd));
307   if (copy == -1) {
308     return -1;
309   }
310 
311   // debuggerd_trigger_dump results in every thread in the process being interrupted
312   // by a signal, so we need to fetch the wchan data before calling that.
313   std::string wchan_data = get_wchan_data(fd, tid);
314 
315   int timeout_ms = timeout_secs > 0 ? timeout_secs * 1000 : 0;
316   int ret = debuggerd_trigger_dump(tid, dump_type, timeout_ms, std::move(copy)) ? 0 : -1;
317 
318   // Dump wchan data, since only privileged processes (CAP_SYS_ADMIN) can read
319   // kernel stack traces (/proc/*/stack).
320   if (!WriteStringToFd(wchan_data, fd)) {
321     LOG(WARNING) << TAG "Failed to dump wchan data for pid: " << tid;
322   }
323 
324   return ret;
325 }
326