blob: 3ce2064aed523fcb0163fa2034269558262b58ff [file] [log] [blame]
Elliott Hughes872d4ec2011-10-21 17:07:15 -07001/*
2 * Copyright (C) 2008 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
Elliott Hughes872d4ec2011-10-21 17:07:15 -070017#include <errno.h>
18#include <stdio.h>
19#include <sys/socket.h>
20#include <sys/un.h>
21#include <unistd.h>
22
Elliott Hughes07ed66b2012-12-12 18:34:25 -080023#include "base/logging.h"
Elliott Hughese222ee02012-12-13 14:41:43 -080024#include "base/stringprintf.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080025#include "jdwp/jdwp_priv.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080026
Elliott Hughes872d4ec2011-10-21 17:07:15 -070027#ifdef HAVE_ANDROID_OS
28#include "cutils/sockets.h"
29#endif
30
31/*
32 * The JDWP <-> ADB transport protocol is explained in detail
33 * in system/core/adb/jdwp_service.c. Here's a summary.
34 *
35 * 1/ when the JDWP thread starts, it tries to connect to a Unix
36 * domain stream socket (@jdwp-control) that is opened by the
37 * ADB daemon.
38 *
39 * 2/ it then sends the current process PID as a string of 4 hexadecimal
40 * chars (no terminating zero)
41 *
42 * 3/ then, it uses recvmsg to receive file descriptors from the
43 * daemon. each incoming file descriptor is a pass-through to
44 * a given JDWP debugger, that can be used to read the usual
45 * JDWP-handshake, etc...
46 */
47
Elliott Hughes872d4ec2011-10-21 17:07:15 -070048#define kJdwpControlName "\0jdwp-control"
49#define kJdwpControlNameLen (sizeof(kJdwpControlName)-1)
50
51namespace art {
52
53namespace JDWP {
54
55struct JdwpNetState : public JdwpNetStateBase {
56 int controlSock;
Elliott Hughes872d4ec2011-10-21 17:07:15 -070057 bool shuttingDown;
58 int wakeFds[2];
59
Elliott Hughes872d4ec2011-10-21 17:07:15 -070060 socklen_t controlAddrLen;
61 union {
Elliott Hughes7b9d9962012-04-20 18:48:18 -070062 sockaddr_un controlAddrUn;
63 sockaddr controlAddrPlain;
Elliott Hughes872d4ec2011-10-21 17:07:15 -070064 } controlAddr;
65
66 JdwpNetState() {
67 controlSock = -1;
Elliott Hughes872d4ec2011-10-21 17:07:15 -070068 shuttingDown = false;
69 wakeFds[0] = -1;
70 wakeFds[1] = -1;
71
Elliott Hughes872d4ec2011-10-21 17:07:15 -070072 controlAddr.controlAddrUn.sun_family = AF_UNIX;
73 controlAddrLen = sizeof(controlAddr.controlAddrUn.sun_family) + kJdwpControlNameLen;
74 memcpy(controlAddr.controlAddrUn.sun_path, kJdwpControlName, kJdwpControlNameLen);
75 }
76};
77
Elliott Hughes68a5e3c2013-04-17 17:13:35 -070078static JdwpNetState* GetNetState(JdwpState* state) {
79 return reinterpret_cast<JdwpNetState*>(state->netState);
80}
81
Elliott Hughes872d4ec2011-10-21 17:07:15 -070082static void adbStateFree(JdwpNetState* netState) {
83 if (netState == NULL) {
84 return;
85 }
86
87 if (netState->clientSock >= 0) {
88 shutdown(netState->clientSock, SHUT_RDWR);
89 close(netState->clientSock);
90 }
91 if (netState->controlSock >= 0) {
92 shutdown(netState->controlSock, SHUT_RDWR);
93 close(netState->controlSock);
94 }
95 if (netState->wakeFds[0] >= 0) {
96 close(netState->wakeFds[0]);
97 netState->wakeFds[0] = -1;
98 }
99 if (netState->wakeFds[1] >= 0) {
100 close(netState->wakeFds[1]);
101 netState->wakeFds[1] = -1;
102 }
103
104 delete netState;
105}
106
107/*
108 * Do initial prep work, e.g. binding to ports and opening files. This
109 * runs in the main thread, before the JDWP thread starts, so it shouldn't
110 * do anything that might block forever.
111 */
Elliott Hughes376a7a02011-10-24 18:35:55 -0700112static bool startup(JdwpState* state, const JdwpOptions*) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800113 VLOG(jdwp) << "ADB transport startup";
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700114 state->netState = new JdwpNetState;
115 return (state->netState != NULL);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700116}
117
118/*
119 * Receive a file descriptor from ADB. The fd can be used to communicate
120 * directly with a debugger or DDMS.
121 *
122 * Returns the file descriptor on success. On failure, returns -1 and
123 * closes netState->controlSock.
124 */
125static int receiveClientFd(JdwpNetState* netState) {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700126 msghdr msg;
127 cmsghdr* cmsg;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700128 iovec iov;
129 char dummy = '!';
130 union {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700131 cmsghdr cm;
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700132 char buffer[CMSG_SPACE(sizeof(int))];
133 } cm_un;
134 int ret;
135
136 iov.iov_base = &dummy;
137 iov.iov_len = 1;
138 msg.msg_name = NULL;
139 msg.msg_namelen = 0;
140 msg.msg_iov = &iov;
141 msg.msg_iovlen = 1;
142 msg.msg_flags = 0;
143 msg.msg_control = cm_un.buffer;
144 msg.msg_controllen = sizeof(cm_un.buffer);
145
146 cmsg = CMSG_FIRSTHDR(&msg);
147 cmsg->cmsg_len = msg.msg_controllen;
148 cmsg->cmsg_level = SOL_SOCKET;
149 cmsg->cmsg_type = SCM_RIGHTS;
150 ((int*)(void*)CMSG_DATA(cmsg))[0] = -1;
151
152 do {
153 ret = recvmsg(netState->controlSock, &msg, 0);
154 } while (ret < 0 && errno == EINTR);
155
156 if (ret <= 0) {
157 if (ret < 0) {
Elliott Hughes3d30d9b2011-12-07 17:35:48 -0800158 PLOG(WARNING) << "Receiving file descriptor from ADB failed (socket " << netState->controlSock << ")";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700159 }
160 close(netState->controlSock);
161 netState->controlSock = -1;
162 return -1;
163 }
164
165 return ((int*)(void*)CMSG_DATA(cmsg))[0];
166}
167
168/*
169 * Block forever, waiting for a debugger to connect to us. Called from the
170 * JDWP thread.
171 *
172 * This needs to un-block and return "false" if the VM is shutting down. It
173 * should return "true" when it successfully accepts a connection.
174 */
175static bool acceptConnection(JdwpState* state) {
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700176 JdwpNetState* netState = GetNetState(state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700177 int retryCount = 0;
178
179 /* first, ensure that we get a connection to the ADB daemon */
180
Elliott Hughesa21039c2012-06-21 12:09:25 -0700181 retry:
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700182 if (netState->shuttingDown) {
183 return false;
184 }
185
186 if (netState->controlSock < 0) {
187 int sleep_ms = 500;
188 const int sleep_max_ms = 2*1000;
189 char buff[5];
190
191 netState->controlSock = socket(PF_UNIX, SOCK_STREAM, 0);
192 if (netState->controlSock < 0) {
193 PLOG(ERROR) << "Could not create ADB control socket";
194 return false;
195 }
196
197 if (pipe(netState->wakeFds) < 0) {
198 PLOG(ERROR) << "pipe failed";
199 return false;
200 }
201
202 snprintf(buff, sizeof(buff), "%04x", getpid());
203 buff[4] = 0;
204
205 for (;;) {
206 /*
207 * If adbd isn't running, because USB debugging was disabled or
208 * perhaps the system is restarting it for "adb root", the
209 * connect() will fail. We loop here forever waiting for it
210 * to come back.
211 *
212 * Waking up and polling every couple of seconds is generally a
213 * bad thing to do, but we only do this if the application is
214 * debuggable *and* adbd isn't running. Still, for the sake
215 * of battery life, we should consider timing out and giving
216 * up after a few minutes in case somebody ships an app with
217 * the debuggable flag set.
218 */
219 int ret = connect(netState->controlSock, &netState->controlAddr.controlAddrPlain, netState->controlAddrLen);
220 if (!ret) {
221#ifdef HAVE_ANDROID_OS
222 if (!socket_peer_is_trusted(netState->controlSock)) {
223 if (shutdown(netState->controlSock, SHUT_RDWR)) {
224 PLOG(ERROR) << "trouble shutting down socket";
225 }
226 return false;
227 }
228#endif
229
230 /* now try to send our pid to the ADB daemon */
Elliott Hughesa21039c2012-06-21 12:09:25 -0700231 ret = TEMP_FAILURE_RETRY(send(netState->controlSock, buff, 4, 0));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700232 if (ret >= 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800233 VLOG(jdwp) << StringPrintf("PID sent as '%.*s' to ADB", 4, buff);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700234 break;
235 }
236
237 PLOG(ERROR) << "Weird, can't send JDWP process pid to ADB";
238 return false;
239 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800240 if (VLOG_IS_ON(jdwp)) {
241 PLOG(ERROR) << "Can't connect to ADB control socket";
242 }
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700243
Elliott Hughesa21039c2012-06-21 12:09:25 -0700244 usleep(sleep_ms * 1000);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700245
246 sleep_ms += (sleep_ms >> 1);
247 if (sleep_ms > sleep_max_ms) {
248 sleep_ms = sleep_max_ms;
249 }
250 if (netState->shuttingDown) {
251 return false;
252 }
253 }
254 }
255
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800256 VLOG(jdwp) << "trying to receive file descriptor from ADB";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700257 /* now we can receive a client file descriptor */
258 netState->clientSock = receiveClientFd(netState);
259 if (netState->shuttingDown) {
260 return false; // suppress logs and additional activity
261 }
262 if (netState->clientSock < 0) {
263 if (++retryCount > 5) {
264 LOG(ERROR) << "adb connection max retries exceeded";
265 return false;
266 }
267 goto retry;
268 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800269 VLOG(jdwp) << "received file descriptor " << netState->clientSock << " from ADB";
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700270 netState->SetAwaitingHandshake(true);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700271 netState->inputCount = 0;
272 return true;
273 }
274}
275
276/*
277 * Connect out to a debugger (for server=n). Not required.
278 */
Elliott Hughesa21039c2012-06-21 12:09:25 -0700279static bool establishConnection(JdwpState*, const JdwpOptions*) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700280 return false;
281}
282
283/*
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700284 * Close all network stuff, including the socket we use to listen for
285 * new connections.
286 *
287 * May be called from a non-JDWP thread, e.g. when the VM is shutting down.
288 */
289static void adbStateShutdown(JdwpNetState* netState) {
290 int controlSock;
291 int clientSock;
292
293 if (netState == NULL) {
294 return;
295 }
296
297 netState->shuttingDown = true;
298
299 clientSock = netState->clientSock;
300 if (clientSock >= 0) {
301 shutdown(clientSock, SHUT_RDWR);
302 netState->clientSock = -1;
303 }
304
305 controlSock = netState->controlSock;
306 if (controlSock >= 0) {
307 shutdown(controlSock, SHUT_RDWR);
308 netState->controlSock = -1;
309 }
310
311 if (netState->wakeFds[1] >= 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800312 VLOG(jdwp) << "+++ writing to wakePipe";
Elliott Hughes068193c2013-04-15 16:05:28 -0700313 TEMP_FAILURE_RETRY(write(netState->wakeFds[1], "", 1));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700314 }
315}
316
317static void netShutdown(JdwpState* state) {
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700318 adbStateShutdown(GetNetState(state));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700319}
320
321/*
322 * Free up anything we put in state->netState. This is called after
323 * "netShutdown", after the JDWP thread has stopped.
324 */
325static void netFree(JdwpState* state) {
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700326 adbStateFree(GetNetState(state));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700327}
328
329/*
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700330 * Process incoming data. If no data is available, this will block until
331 * some arrives.
332 *
333 * If we get a full packet, handle it.
334 *
335 * To take some of the mystery out of life, we want to reject incoming
336 * connections if we already have a debugger attached. If we don't, the
337 * debugger will just mysteriously hang until it times out. We could just
338 * close the listen socket, but there's a good chance we won't be able to
339 * bind to the same port again, which would confuse utilities.
340 *
341 * Returns "false" on error (indicating that the connection has been severed),
342 * "true" if things are still okay.
343 */
344static bool processIncoming(JdwpState* state) {
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700345 JdwpNetState* netState = GetNetState(state);
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700346 int readCount;
347
348 CHECK_GE(netState->clientSock, 0);
349
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700350 if (!netState->HaveFullPacket()) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700351 /* read some more, looping until we have data */
352 errno = 0;
353 while (1) {
354 int selCount;
355 fd_set readfds;
356 int maxfd = -1;
357 int fd;
358
359 FD_ZERO(&readfds);
360
361 /* configure fds; note these may get zapped by another thread */
362 fd = netState->controlSock;
363 if (fd >= 0) {
364 FD_SET(fd, &readfds);
365 if (maxfd < fd) {
366 maxfd = fd;
367 }
368 }
369 fd = netState->clientSock;
370 if (fd >= 0) {
371 FD_SET(fd, &readfds);
372 if (maxfd < fd) {
373 maxfd = fd;
374 }
375 }
376 fd = netState->wakeFds[0];
377 if (fd >= 0) {
378 FD_SET(fd, &readfds);
379 if (maxfd < fd) {
380 maxfd = fd;
381 }
382 } else {
383 LOG(INFO) << "NOTE: entering select w/o wakepipe";
384 }
385
386 if (maxfd < 0) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800387 VLOG(jdwp) << "+++ all fds are closed";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700388 return false;
389 }
390
391 /*
392 * Select blocks until it sees activity on the file descriptors.
393 * Closing the local file descriptor does not count as activity,
394 * so we can't rely on that to wake us up (it works for read()
395 * and accept(), but not select()).
396 *
397 * We can do one of three things: (1) send a signal and catch
398 * EINTR, (2) open an additional fd ("wakePipe") and write to
399 * it when it's time to exit, or (3) time out periodically and
400 * re-issue the select. We're currently using #2, as it's more
401 * reliable than #1 and generally better than #3. Wastes two fds.
402 */
403 selCount = select(maxfd+1, &readfds, NULL, NULL, NULL);
404 if (selCount < 0) {
405 if (errno == EINTR) {
406 continue;
407 }
408 PLOG(ERROR) << "select failed";
409 goto fail;
410 }
411
412 if (netState->wakeFds[0] >= 0 && FD_ISSET(netState->wakeFds[0], &readfds)) {
413 LOG(DEBUG) << "Got wake-up signal, bailing out of select";
414 goto fail;
415 }
416 if (netState->controlSock >= 0 && FD_ISSET(netState->controlSock, &readfds)) {
417 int sock = receiveClientFd(netState);
418 if (sock >= 0) {
419 LOG(INFO) << "Ignoring second debugger -- accepting and dropping";
420 close(sock);
421 } else {
422 CHECK_LT(netState->controlSock, 0);
423 /*
424 * Remote side most likely went away, so our next read
425 * on netState->clientSock will fail and throw us out
426 * of the loop.
427 */
428 }
429 }
430 if (netState->clientSock >= 0 && FD_ISSET(netState->clientSock, &readfds)) {
431 readCount = read(netState->clientSock, netState->inputBuffer + netState->inputCount, sizeof(netState->inputBuffer) - netState->inputCount);
432 if (readCount < 0) {
433 /* read failed */
434 if (errno != EINTR) {
435 goto fail;
436 }
437 LOG(DEBUG) << "+++ EINTR hit";
438 return true;
439 } else if (readCount == 0) {
440 /* EOF hit -- far end went away */
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800441 VLOG(jdwp) << "+++ peer disconnected";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700442 goto fail;
443 } else {
444 break;
445 }
446 }
447 }
448
449 netState->inputCount += readCount;
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700450 if (!netState->HaveFullPacket()) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700451 return true; /* still not there yet */
452 }
453 }
454
455 /*
456 * Special-case the initial handshake. For some bizarre reason we're
457 * expected to emulate bad tty settings by echoing the request back
458 * exactly as it was sent. Note the handshake is always initiated by
459 * the debugger, no matter who connects to whom.
460 *
461 * Other than this one case, the protocol [claims to be] stateless.
462 */
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700463 if (netState->IsAwaitingHandshake()) {
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700464 int cc;
465
466 if (memcmp(netState->inputBuffer, kMagicHandshake, kMagicHandshakeLen) != 0) {
467 LOG(ERROR) << StringPrintf("ERROR: bad handshake '%.14s'", netState->inputBuffer);
468 goto fail;
469 }
470
471 errno = 0;
Elliott Hughes068193c2013-04-15 16:05:28 -0700472 cc = TEMP_FAILURE_RETRY(write(netState->clientSock, netState->inputBuffer, kMagicHandshakeLen));
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700473 if (cc != kMagicHandshakeLen) {
474 PLOG(ERROR) << "Failed writing handshake bytes (" << cc << " of " << kMagicHandshakeLen << ")";
475 goto fail;
476 }
477
Elliott Hughescb693062013-02-21 09:48:08 -0800478 netState->ConsumeBytes(kMagicHandshakeLen);
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700479 netState->SetAwaitingHandshake(false);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800480 VLOG(jdwp) << "+++ handshake complete";
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700481 return true;
482 }
483
484 /*
485 * Handle this packet.
486 */
Elliott Hughescb693062013-02-21 09:48:08 -0800487 return state->HandlePacket();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700488
Elliott Hughesa21039c2012-06-21 12:09:25 -0700489 fail:
Elliott Hughes68a5e3c2013-04-17 17:13:35 -0700490 netState->Close();
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700491 return false;
492}
493
494/*
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700495 * Our functions.
496 */
497static const JdwpTransport adbTransport = {
498 startup,
499 acceptConnection,
500 establishConnection,
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700501 netShutdown,
502 netFree,
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700503 processIncoming,
Elliott Hughes872d4ec2011-10-21 17:07:15 -0700504};
505
506/*
507 * Return our set.
508 */
509const JdwpTransport* AndroidAdbTransport() {
510 return &adbTransport;
511}
512
513} // namespace JDWP
514
515} // namespace art