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 <unistd.h>
26
27#include <chrono>
28
29#include <android-base/file.h>
30#include <android-base/logging.h>
31#include <android-base/parseint.h>
32#include <android-base/stringprintf.h>
33#include <android-base/strings.h>
34#include <android-base/unique_fd.h>
35#include <cutils/sockets.h>
36#include <debuggerd/handler.h>
37#include <debuggerd/protocol.h>
38#include <debuggerd/util.h>
39
40using namespace std::chrono_literals;
41
42using android::base::unique_fd;
43
44static bool send_signal(pid_t pid, bool backtrace) {
45  sigval val;
46  val.sival_int = backtrace;
47  if (sigqueue(pid, DEBUGGER_SIGNAL, val) != 0) {
48    PLOG(ERROR) << "libdebuggerd_client: failed to send signal to pid " << pid;
49    return false;
50  }
51  return true;
52}
53
54template <typename Duration>
55static void populate_timeval(struct timeval* tv, const Duration& duration) {
56  auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
57  auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(duration - seconds);
58  tv->tv_sec = static_cast<long>(seconds.count());
59  tv->tv_usec = static_cast<long>(microseconds.count());
60}
61
62bool debuggerd_trigger_dump(pid_t pid, unique_fd output_fd, DebuggerdDumpType dump_type,
63                            unsigned int timeout_ms) {
64  LOG(INFO) << "libdebuggerd_client: started dumping process " << pid;
65  unique_fd sockfd;
66  const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms);
67  auto time_left = [&end]() { return end - std::chrono::steady_clock::now(); };
68  auto set_timeout = [timeout_ms, &time_left](int sockfd) {
69    if (timeout_ms <= 0) {
70      return sockfd;
71    }
72
73    auto remaining = time_left();
74    if (remaining < decltype(remaining)::zero()) {
75      LOG(ERROR) << "libdebuggerd_client: timeout expired";
76      return -1;
77    }
78
79    struct timeval timeout;
80    populate_timeval(&timeout, remaining);
81
82    if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0) {
83      PLOG(ERROR) << "libdebuggerd_client: failed to set receive timeout";
84      return -1;
85    }
86    if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) != 0) {
87      PLOG(ERROR) << "libdebuggerd_client: failed to set send timeout";
88      return -1;
89    }
90
91    return sockfd;
92  };
93
94  sockfd.reset(socket(AF_LOCAL, SOCK_SEQPACKET, 0));
95  if (sockfd == -1) {
96    PLOG(ERROR) << "libdebugger_client: failed to create socket";
97    return false;
98  }
99
100  if (socket_local_client_connect(set_timeout(sockfd.get()), kTombstonedInterceptSocketName,
101                                  ANDROID_SOCKET_NAMESPACE_RESERVED, SOCK_SEQPACKET) == -1) {
102    PLOG(ERROR) << "libdebuggerd_client: failed to connect to tombstoned";
103    return false;
104  }
105
106  InterceptRequest req = {.pid = pid };
107  if (!set_timeout(sockfd)) {
108    PLOG(ERROR) << "libdebugger_client: failed to set timeout";
109    return false;
110  }
111
112  // Create an intermediate pipe to pass to the other end.
113  unique_fd pipe_read, pipe_write;
114  if (!Pipe(&pipe_read, &pipe_write)) {
115    PLOG(ERROR) << "libdebuggerd_client: failed to create pipe";
116    return false;
117  }
118
119  std::string pipe_size_str;
120  int pipe_buffer_size = 1024 * 1024;
121  if (android::base::ReadFileToString("/proc/sys/fs/pipe-max-size", &pipe_size_str)) {
122    pipe_size_str = android::base::Trim(pipe_size_str);
123
124    if (!android::base::ParseInt(pipe_size_str.c_str(), &pipe_buffer_size, 0)) {
125      LOG(FATAL) << "failed to parse pipe max size '" << pipe_size_str << "'";
126    }
127  }
128
129  if (fcntl(pipe_read.get(), F_SETPIPE_SZ, pipe_buffer_size) != pipe_buffer_size) {
130    PLOG(ERROR) << "failed to set pipe buffer size";
131  }
132
133  if (send_fd(set_timeout(sockfd), &req, sizeof(req), std::move(pipe_write)) != sizeof(req)) {
134    PLOG(ERROR) << "libdebuggerd_client: failed to send output fd to tombstoned";
135    return false;
136  }
137
138  // Check to make sure we've successfully registered.
139  InterceptResponse response;
140  ssize_t rc =
141      TEMP_FAILURE_RETRY(recv(set_timeout(sockfd.get()), &response, sizeof(response), MSG_TRUNC));
142  if (rc == 0) {
143    LOG(ERROR) << "libdebuggerd_client: failed to read response from tombstoned: timeout reached?";
144    return false;
145  } else if (rc != sizeof(response)) {
146    LOG(ERROR)
147        << "libdebuggerd_client: received packet of unexpected length from tombstoned: expected "
148        << sizeof(response) << ", received " << rc;
149    return false;
150  }
151
152  if (response.status != InterceptStatus::kRegistered) {
153    LOG(ERROR) << "libdebuggerd_client: unexpected registration response: "
154               << static_cast<int>(response.status);
155    return false;
156  }
157
158  bool backtrace = dump_type == kDebuggerdBacktrace;
159  send_signal(pid, backtrace);
160
161  rc = TEMP_FAILURE_RETRY(recv(set_timeout(sockfd.get()), &response, sizeof(response), MSG_TRUNC));
162  if (rc == 0) {
163    LOG(ERROR) << "libdebuggerd_client: failed to read response from tombstoned: timeout reached?";
164    return false;
165  } else if (rc != sizeof(response)) {
166    LOG(ERROR)
167      << "libdebuggerd_client: received packet of unexpected length from tombstoned: expected "
168      << sizeof(response) << ", received " << rc;
169    return false;
170  }
171
172  if (response.status != InterceptStatus::kStarted) {
173    response.error_message[sizeof(response.error_message) - 1] = '\0';
174    LOG(ERROR) << "libdebuggerd_client: tombstoned reported failure: " << response.error_message;
175    return false;
176  }
177
178  // Forward output from the pipe to the output fd.
179  while (true) {
180    auto remaining_ms = std::chrono::duration_cast<std::chrono::milliseconds>(time_left()).count();
181    if (timeout_ms <= 0) {
182      remaining_ms = -1;
183    } else if (remaining_ms < 0) {
184      LOG(ERROR) << "libdebuggerd_client: timeout expired";
185      return false;
186    }
187
188    struct pollfd pfd = {
189        .fd = pipe_read.get(), .events = POLLIN, .revents = 0,
190    };
191
192    rc = poll(&pfd, 1, remaining_ms);
193    if (rc == -1) {
194      if (errno == EINTR) {
195        continue;
196      } else {
197        PLOG(ERROR) << "libdebuggerd_client: error while polling";
198        return false;
199      }
200    } else if (rc == 0) {
201      LOG(ERROR) << "libdebuggerd_client: timeout expired";
202      return false;
203    }
204
205    char buf[1024];
206    rc = TEMP_FAILURE_RETRY(read(pipe_read.get(), buf, sizeof(buf)));
207    if (rc == 0) {
208      // Done.
209      break;
210    } else if (rc == -1) {
211      PLOG(ERROR) << "libdebuggerd_client: error while reading";
212      return false;
213    }
214
215    if (!android::base::WriteFully(output_fd.get(), buf, rc)) {
216      PLOG(ERROR) << "libdebuggerd_client: error while writing";
217      return false;
218    }
219  }
220
221  LOG(INFO) << "libdebuggerd_client: done dumping process " << pid;
222
223  return true;
224}
225
226int dump_backtrace_to_file(pid_t tid, int fd) {
227  return dump_backtrace_to_file_timeout(tid, fd, 0);
228}
229
230int dump_backtrace_to_file_timeout(pid_t tid, int fd, int timeout_secs) {
231  android::base::unique_fd copy(dup(fd));
232  if (copy == -1) {
233    return -1;
234  }
235  int timeout_ms = timeout_secs > 0 ? timeout_secs * 1000 : 0;
236  return debuggerd_trigger_dump(tid, std::move(copy), kDebuggerdBacktrace, timeout_ms) ? 0 : -1;
237}
238