Alex Light | 3979571 | 2017-12-14 11:58:21 -0800 | [diff] [blame] | 1 | /* Copyright (C) 2017 The Android Open Source Project |
| 2 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
| 3 | * |
| 4 | * This file implements interfaces from the file jdwpTransport.h. This |
| 5 | * implementation is licensed under the same terms as the file |
| 6 | * jdwpTransport.h. The copyright and license information for the file |
| 7 | * jdwpTransport.h follows. |
| 8 | * |
| 9 | * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. |
| 10 | * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
| 11 | * |
| 12 | * This code is free software; you can redistribute it and/or modify it |
| 13 | * under the terms of the GNU General Public License version 2 only, as |
| 14 | * published by the Free Software Foundation. Oracle designates this |
| 15 | * particular file as subject to the "Classpath" exception as provided |
| 16 | * by Oracle in the LICENSE file that accompanied this code. |
| 17 | * |
| 18 | * This code is distributed in the hope that it will be useful, but WITHOUT |
| 19 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| 20 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
| 21 | * version 2 for more details (a copy is included in the LICENSE file that |
| 22 | * accompanied this code). |
| 23 | * |
| 24 | * You should have received a copy of the GNU General Public License version |
| 25 | * 2 along with this work; if not, write to the Free Software Foundation, |
| 26 | * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
| 27 | * |
| 28 | * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
| 29 | * or visit www.oracle.com if you need additional information or have any |
| 30 | * questions. |
| 31 | */ |
| 32 | |
| 33 | #include "dt_fd_forward.h" |
| 34 | |
| 35 | #include <string> |
| 36 | #include <vector> |
| 37 | |
| 38 | #include <android-base/endian.h> |
| 39 | #include <android-base/logging.h> |
| 40 | #include <android-base/parseint.h> |
| 41 | #include <android-base/stringprintf.h> |
| 42 | |
| 43 | #include <sys/ioctl.h> |
| 44 | #include <sys/eventfd.h> |
| 45 | #include <sys/socket.h> |
| 46 | #include <sys/types.h> |
| 47 | #include <unistd.h> |
| 48 | #include <poll.h> |
| 49 | |
| 50 | #include <jni.h> |
| 51 | #include <jdwpTransport.h> |
| 52 | |
| 53 | namespace dt_fd_forward { |
| 54 | |
| 55 | // Helper that puts line-number in error message. |
| 56 | #define DT_IO_ERROR(f) \ |
| 57 | SetLastError(::android::base::StringPrintf("%s:%d - %s: %s", \ |
| 58 | __FILE__, __LINE__, f, strerror(errno))) |
| 59 | |
| 60 | extern const jdwpTransportNativeInterface_ gTransportInterface; |
| 61 | |
| 62 | template <typename T> static T HostToNetwork(T in); |
| 63 | template <typename T> static T NetworkToHost(T in); |
| 64 | |
| 65 | template<> int8_t HostToNetwork(int8_t in) { return in; } |
| 66 | template<> int8_t NetworkToHost(int8_t in) { return in; } |
| 67 | template<> int16_t HostToNetwork(int16_t in) { return htons(in); } |
| 68 | template<> int16_t NetworkToHost(int16_t in) { return ntohs(in); } |
| 69 | template<> int32_t HostToNetwork(int32_t in) { return htonl(in); } |
| 70 | template<> int32_t NetworkToHost(int32_t in) { return ntohl(in); } |
| 71 | |
| 72 | FdForwardTransport::FdForwardTransport(jdwpTransportCallback* cb) |
| 73 | : mem_(*cb), |
| 74 | read_fd_(-1), |
| 75 | write_fd_(-1), |
| 76 | wakeup_fd_(eventfd(0, EFD_NONBLOCK)), |
| 77 | listen_fd_(-1), |
| 78 | close_notify_fd_(-1), |
| 79 | state_(TransportState::kClosed), |
| 80 | current_seq_num_(0) {} |
| 81 | |
| 82 | FdForwardTransport::~FdForwardTransport() { } |
| 83 | |
| 84 | bool FdForwardTransport::ChangeState(TransportState old_state, TransportState new_state) { |
| 85 | if (old_state == state_) { |
| 86 | state_ = new_state; |
| 87 | state_cv_.notify_all(); |
| 88 | return true; |
| 89 | } else { |
| 90 | return false; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | jdwpTransportError FdForwardTransport::PerformAttach(int listen_fd) { |
| 95 | jdwpTransportError err = SetupListen(listen_fd); |
| 96 | if (err != OK) { |
| 97 | return OK; |
| 98 | } |
| 99 | err = Accept(); |
| 100 | StopListening(); |
| 101 | return err; |
| 102 | } |
| 103 | |
| 104 | static void SendListenMessage(const android::base::unique_fd& fd) { |
| 105 | TEMP_FAILURE_RETRY(send(fd, kListenStartMessage, sizeof(kListenStartMessage), MSG_EOR)); |
| 106 | } |
| 107 | |
| 108 | jdwpTransportError FdForwardTransport::SetupListen(int listen_fd) { |
| 109 | std::lock_guard<std::mutex> lk(state_mutex_); |
| 110 | if (!ChangeState(TransportState::kClosed, TransportState::kListenSetup)) { |
| 111 | return ERR(ILLEGAL_STATE); |
| 112 | } else { |
| 113 | listen_fd_.reset(dup(listen_fd)); |
| 114 | SendListenMessage(listen_fd_); |
| 115 | CHECK(ChangeState(TransportState::kListenSetup, TransportState::kListening)); |
| 116 | return OK; |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | static void SendListenEndMessage(const android::base::unique_fd& fd) { |
| 121 | TEMP_FAILURE_RETRY(send(fd, kListenEndMessage, sizeof(kListenEndMessage), MSG_EOR)); |
| 122 | } |
| 123 | |
| 124 | jdwpTransportError FdForwardTransport::StopListening() { |
| 125 | std::lock_guard<std::mutex> lk(state_mutex_); |
| 126 | if (listen_fd_ != -1) { |
| 127 | SendListenEndMessage(listen_fd_); |
| 128 | } |
| 129 | // Don't close the listen_fd_ since we might need it for later calls to listen. |
| 130 | if (ChangeState(TransportState::kListening, TransportState::kClosed) || |
| 131 | state_ == TransportState::kOpen) { |
| 132 | listen_fd_.reset(); |
| 133 | } |
| 134 | return OK; |
| 135 | } |
| 136 | |
| 137 | // Last error message. |
| 138 | thread_local std::string global_last_error_; |
| 139 | |
| 140 | void FdForwardTransport::SetLastError(const std::string& desc) { |
| 141 | LOG(ERROR) << desc; |
| 142 | global_last_error_ = desc; |
| 143 | } |
| 144 | |
| 145 | IOResult FdForwardTransport::ReadFullyWithoutChecks(void* data, size_t ndata) { |
| 146 | uint8_t* bdata = reinterpret_cast<uint8_t*>(data); |
| 147 | size_t nbytes = 0; |
| 148 | while (nbytes < ndata) { |
| 149 | int res = TEMP_FAILURE_RETRY(read(read_fd_, bdata + nbytes, ndata - nbytes)); |
| 150 | if (res < 0) { |
| 151 | DT_IO_ERROR("Failed read()"); |
| 152 | return IOResult::kError; |
| 153 | } else if (res == 0) { |
| 154 | return IOResult::kEOF; |
| 155 | } else { |
| 156 | nbytes += res; |
| 157 | } |
| 158 | } |
| 159 | return IOResult::kOk; |
| 160 | } |
| 161 | |
| 162 | IOResult FdForwardTransport::ReadUpToMax(void* data, size_t ndata, /*out*/size_t* read_amount) { |
| 163 | CHECK_GE(read_fd_.get(), 0); |
| 164 | int avail; |
| 165 | int res = ioctl(read_fd_, FIONREAD, &avail); |
| 166 | if (res < 0) { |
| 167 | DT_IO_ERROR("Failed ioctl(read_fd_, FIONREAD, &avail)"); |
| 168 | return IOResult::kError; |
| 169 | } |
| 170 | size_t to_read = std::min(static_cast<size_t>(avail), ndata); |
| 171 | *read_amount = to_read; |
| 172 | if (*read_amount == 0) { |
| 173 | // Check if the read would cause an EOF. |
| 174 | struct pollfd pollfd = { read_fd_, POLLRDHUP, 0 }; |
| 175 | res = poll(&pollfd, /*nfds*/1, /*timeout*/0); |
| 176 | if (res < 0 || (pollfd.revents & POLLERR) == POLLERR) { |
| 177 | DT_IO_ERROR("Failed poll on read fd."); |
| 178 | return IOResult::kError; |
| 179 | } |
| 180 | return ((pollfd.revents & (POLLRDHUP | POLLHUP)) == 0) ? IOResult::kOk : IOResult::kEOF; |
| 181 | } |
| 182 | |
| 183 | return ReadFullyWithoutChecks(data, to_read); |
| 184 | } |
| 185 | |
| 186 | IOResult FdForwardTransport::ReadFully(void* data, size_t ndata) { |
| 187 | uint64_t seq_num = current_seq_num_; |
| 188 | size_t nbytes = 0; |
| 189 | while (nbytes < ndata) { |
| 190 | size_t read_len; |
| 191 | struct pollfd pollfds[2]; |
| 192 | { |
| 193 | std::lock_guard<std::mutex> lk(state_mutex_); |
| 194 | // Operations in this block must not cause an unbounded pause. |
| 195 | if (state_ != TransportState::kOpen || seq_num != current_seq_num_) { |
| 196 | // Async-close occurred! |
| 197 | return IOResult::kInterrupt; |
| 198 | } else { |
| 199 | CHECK_GE(read_fd_.get(), 0); |
| 200 | } |
| 201 | IOResult res = ReadUpToMax(reinterpret_cast<uint8_t*>(data) + nbytes, |
| 202 | ndata - nbytes, |
| 203 | /*out*/&read_len); |
| 204 | if (res != IOResult::kOk) { |
| 205 | return res; |
| 206 | } else { |
| 207 | nbytes += read_len; |
| 208 | } |
| 209 | |
| 210 | pollfds[0] = { read_fd_, POLLRDHUP | POLLIN, 0 }; |
| 211 | pollfds[1] = { wakeup_fd_, POLLIN, 0 }; |
| 212 | } |
| 213 | if (read_len == 0) { |
| 214 | // No more data. Sleep without locks until more is available. We don't actually check for any |
| 215 | // errors since possible ones are (1) the read_fd_ is closed or wakeup happens which are both |
| 216 | // fine since the wakeup_fd_ or the poll failing will wake us up. |
| 217 | int poll_res = poll(pollfds, 2, -1); |
| 218 | if (poll_res < 0) { |
| 219 | DT_IO_ERROR("Failed to poll!"); |
| 220 | } |
| 221 | // Clear the wakeup_fd regardless. |
| 222 | uint64_t val; |
| 223 | int unused = read(wakeup_fd_, &val, sizeof(val)); |
| 224 | DCHECK(unused == sizeof(val) || errno == EAGAIN); |
| 225 | if (poll_res < 0) { |
| 226 | return IOResult::kError; |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | return IOResult::kOk; |
| 231 | } |
| 232 | |
| 233 | // A helper that allows us to lock the eventfd 'fd'. |
| 234 | class ScopedEventFdLock { |
| 235 | public: |
| 236 | explicit ScopedEventFdLock(const android::base::unique_fd& fd) : fd_(fd), data_(0) { |
| 237 | TEMP_FAILURE_RETRY(read(fd_, &data_, sizeof(data_))); |
| 238 | } |
| 239 | |
| 240 | ~ScopedEventFdLock() { |
| 241 | TEMP_FAILURE_RETRY(write(fd_, &data_, sizeof(data_))); |
| 242 | } |
| 243 | |
| 244 | private: |
| 245 | const android::base::unique_fd& fd_; |
| 246 | uint64_t data_; |
| 247 | }; |
| 248 | |
| 249 | IOResult FdForwardTransport::WriteFullyWithoutChecks(const void* data, size_t ndata) { |
| 250 | ScopedEventFdLock sefdl(write_lock_fd_); |
| 251 | const uint8_t* bdata = static_cast<const uint8_t*>(data); |
| 252 | size_t nbytes = 0; |
| 253 | while (nbytes < ndata) { |
| 254 | int res = TEMP_FAILURE_RETRY(write(write_fd_, bdata + nbytes, ndata - nbytes)); |
| 255 | if (res < 0) { |
| 256 | DT_IO_ERROR("Failed write()"); |
| 257 | return IOResult::kError; |
| 258 | } else if (res == 0) { |
| 259 | return IOResult::kEOF; |
| 260 | } else { |
| 261 | nbytes += res; |
| 262 | } |
| 263 | } |
| 264 | return IOResult::kOk; |
| 265 | } |
| 266 | |
| 267 | IOResult FdForwardTransport::WriteFully(const void* data, size_t ndata) { |
| 268 | std::lock_guard<std::mutex> lk(state_mutex_); |
| 269 | if (state_ != TransportState::kOpen) { |
| 270 | return IOResult::kInterrupt; |
| 271 | } |
| 272 | return WriteFullyWithoutChecks(data, ndata); |
| 273 | } |
| 274 | |
| 275 | static void SendAcceptMessage(int fd) { |
| 276 | TEMP_FAILURE_RETRY(send(fd, kAcceptMessage, sizeof(kAcceptMessage), MSG_EOR)); |
| 277 | } |
| 278 | |
| 279 | IOResult FdForwardTransport::ReceiveFdsFromSocket() { |
| 280 | union { |
| 281 | cmsghdr cm; |
| 282 | uint8_t buffer[CMSG_SPACE(sizeof(FdSet))]; |
| 283 | } msg_union; |
| 284 | // We don't actually care about the data. Only FDs. We need to have an iovec anyway to tell if we |
| 285 | // got the values or not though. |
| 286 | char dummy = '\0'; |
| 287 | iovec iov; |
| 288 | iov.iov_base = &dummy; |
| 289 | iov.iov_len = sizeof(dummy); |
| 290 | |
| 291 | msghdr msg; |
| 292 | memset(&msg, 0, sizeof(msg)); |
| 293 | msg.msg_iov = &iov; |
| 294 | msg.msg_iovlen = 1; |
| 295 | msg.msg_control = msg_union.buffer; |
| 296 | msg.msg_controllen = sizeof(msg_union.buffer); |
| 297 | |
| 298 | cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); |
| 299 | cmsg->cmsg_len = msg.msg_controllen; |
| 300 | cmsg->cmsg_level = SOL_SOCKET; |
| 301 | cmsg->cmsg_type = SCM_RIGHTS; |
| 302 | memset(reinterpret_cast<int*>(CMSG_DATA(cmsg)), -1, FdSet::kDataLength); |
| 303 | |
| 304 | int res = TEMP_FAILURE_RETRY(recvmsg(listen_fd_, &msg, 0)); |
| 305 | if (res <= 0) { |
| 306 | DT_IO_ERROR("Failed to receive fds!"); |
| 307 | return IOResult::kError; |
| 308 | } |
| 309 | FdSet out_fds = FdSet::ReadData(CMSG_DATA(cmsg)); |
| 310 | if (out_fds.read_fd_ < 0 || out_fds.write_fd_ < 0 || out_fds.write_lock_fd_ < 0) { |
| 311 | DT_IO_ERROR("Received fds were invalid!"); |
| 312 | if (out_fds.read_fd_ >= 0) { |
| 313 | close(out_fds.read_fd_); |
| 314 | } |
| 315 | if (out_fds.write_fd_ >= 0) { |
| 316 | close(out_fds.write_fd_); |
| 317 | } |
| 318 | if (out_fds.write_lock_fd_ >= 0) { |
| 319 | close(out_fds.write_lock_fd_); |
| 320 | } |
| 321 | return IOResult::kError; |
| 322 | } |
| 323 | |
| 324 | read_fd_.reset(out_fds.read_fd_); |
| 325 | write_fd_.reset(out_fds.write_fd_); |
| 326 | write_lock_fd_.reset(out_fds.write_lock_fd_); |
| 327 | |
| 328 | // We got the fds. Send ack. |
| 329 | close_notify_fd_.reset(dup(listen_fd_)); |
| 330 | SendAcceptMessage(close_notify_fd_); |
| 331 | |
| 332 | return IOResult::kOk; |
| 333 | } |
| 334 | |
| 335 | // Accept the connection. Note that we match the behavior of other transports which is to just close |
| 336 | // the connection and try again if we get a bad handshake. |
| 337 | jdwpTransportError FdForwardTransport::Accept() { |
| 338 | // TODO Work with timeouts. |
| 339 | while (true) { |
| 340 | std::unique_lock<std::mutex> lk(state_mutex_); |
| 341 | while (!ChangeState(TransportState::kListening, TransportState::kOpening)) { |
| 342 | if (state_ == TransportState::kClosed || |
| 343 | state_ == TransportState::kOpen) { |
| 344 | return ERR(ILLEGAL_STATE); |
| 345 | } |
| 346 | state_cv_.wait(lk); |
| 347 | } |
| 348 | |
| 349 | DCHECK_NE(listen_fd_.get(), -1); |
| 350 | if (ReceiveFdsFromSocket() != IOResult::kOk) { |
| 351 | CHECK(ChangeState(TransportState::kOpening, TransportState::kListening)); |
| 352 | return ERR(IO_ERROR); |
| 353 | } |
| 354 | |
| 355 | current_seq_num_++; |
| 356 | |
| 357 | // Moved to the opening state. |
| 358 | char handshake_recv[sizeof(kJdwpHandshake)]; |
| 359 | memset(handshake_recv, 0, sizeof(handshake_recv)); |
| 360 | IOResult res = ReadFullyWithoutChecks(handshake_recv, sizeof(handshake_recv)); |
| 361 | if (res != IOResult::kOk || |
| 362 | strncmp(handshake_recv, kJdwpHandshake, sizeof(kJdwpHandshake)) != 0) { |
| 363 | DT_IO_ERROR("Failed to read handshake"); |
| 364 | CHECK(ChangeState(TransportState::kOpening, TransportState::kListening)); |
| 365 | CloseFdsLocked(); |
| 366 | // Retry. |
| 367 | continue; |
| 368 | } |
| 369 | res = WriteFullyWithoutChecks(kJdwpHandshake, sizeof(kJdwpHandshake)); |
| 370 | if (res != IOResult::kOk) { |
| 371 | DT_IO_ERROR("Failed to write handshake"); |
| 372 | CHECK(ChangeState(TransportState::kOpening, TransportState::kListening)); |
| 373 | CloseFdsLocked(); |
| 374 | // Retry. |
| 375 | continue; |
| 376 | } |
| 377 | break; |
| 378 | } |
| 379 | CHECK(ChangeState(TransportState::kOpening, TransportState::kOpen)); |
| 380 | return OK; |
| 381 | } |
| 382 | |
| 383 | void SendClosingMessage(int fd) { |
| 384 | if (fd >= 0) { |
| 385 | TEMP_FAILURE_RETRY(send(fd, kCloseMessage, sizeof(kCloseMessage), MSG_EOR)); |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | // Actually close the fds associated with this transport. |
| 390 | void FdForwardTransport::CloseFdsLocked() { |
| 391 | // We have a different set of fd's now. Increase the seq number. |
| 392 | current_seq_num_++; |
| 393 | |
| 394 | // All access to these is locked under the state_mutex_ so we are safe to close these. |
| 395 | { |
| 396 | ScopedEventFdLock sefdl(write_lock_fd_); |
| 397 | if (close_notify_fd_ >= 0) { |
| 398 | SendClosingMessage(close_notify_fd_); |
| 399 | } |
| 400 | close_notify_fd_.reset(); |
| 401 | read_fd_.reset(); |
| 402 | write_fd_.reset(); |
| 403 | close_notify_fd_.reset(); |
| 404 | } |
| 405 | write_lock_fd_.reset(); |
| 406 | |
| 407 | // Send a wakeup in case we have any in-progress reads/writes. |
| 408 | uint64_t data = 1; |
| 409 | TEMP_FAILURE_RETRY(write(wakeup_fd_, &data, sizeof(data))); |
| 410 | } |
| 411 | |
| 412 | jdwpTransportError FdForwardTransport::Close() { |
| 413 | std::lock_guard<std::mutex> lk(state_mutex_); |
| 414 | jdwpTransportError res = |
| 415 | ChangeState(TransportState::kOpen, TransportState::kClosed) ? OK : ERR(ILLEGAL_STATE); |
| 416 | // Send a wakeup after changing the state even if nothing actually happened. |
| 417 | uint64_t data = 1; |
| 418 | TEMP_FAILURE_RETRY(write(wakeup_fd_, &data, sizeof(data))); |
| 419 | if (res == OK) { |
| 420 | CloseFdsLocked(); |
| 421 | } |
| 422 | return res; |
| 423 | } |
| 424 | |
| 425 | // A helper class to read and parse the JDWP packet. |
| 426 | class PacketReader { |
| 427 | public: |
| 428 | PacketReader(FdForwardTransport* transport, jdwpPacket* pkt) |
| 429 | : transport_(transport), |
| 430 | pkt_(pkt), |
| 431 | is_eof_(false), |
| 432 | is_err_(false) {} |
| 433 | bool ReadFully() { |
| 434 | // Zero out. |
| 435 | memset(pkt_, 0, sizeof(jdwpPacket)); |
| 436 | int32_t len = ReadInt32(); // read len |
| 437 | if (is_err_) { |
| 438 | return false; |
| 439 | } else if (is_eof_) { |
| 440 | return true; |
| 441 | } else if (len < 11) { |
| 442 | transport_->DT_IO_ERROR("Packet with len < 11 received!"); |
| 443 | return false; |
| 444 | } |
| 445 | pkt_->type.cmd.len = len; |
| 446 | pkt_->type.cmd.id = ReadInt32(); |
| 447 | pkt_->type.cmd.flags = ReadByte(); |
| 448 | if (is_err_) { |
| 449 | return false; |
| 450 | } else if (is_eof_) { |
| 451 | return true; |
| 452 | } else if ((pkt_->type.reply.flags & JDWPTRANSPORT_FLAGS_REPLY) == JDWPTRANSPORT_FLAGS_REPLY) { |
| 453 | ReadReplyPacket(); |
| 454 | } else { |
| 455 | ReadCmdPacket(); |
| 456 | } |
| 457 | return !is_err_; |
| 458 | } |
| 459 | |
| 460 | private: |
| 461 | void ReadReplyPacket() { |
| 462 | pkt_->type.reply.errorCode = ReadInt16(); |
| 463 | pkt_->type.reply.data = ReadRemaining(); |
| 464 | } |
| 465 | |
| 466 | void ReadCmdPacket() { |
| 467 | pkt_->type.cmd.cmdSet = ReadByte(); |
| 468 | pkt_->type.cmd.cmd = ReadByte(); |
| 469 | pkt_->type.cmd.data = ReadRemaining(); |
| 470 | } |
| 471 | |
| 472 | template <typename T> |
| 473 | T HandleResult(IOResult res, T val, T fail) { |
| 474 | switch (res) { |
| 475 | case IOResult::kError: |
| 476 | is_err_ = true; |
| 477 | return fail; |
| 478 | case IOResult::kOk: |
| 479 | return val; |
| 480 | case IOResult::kEOF: |
| 481 | is_eof_ = true; |
| 482 | pkt_->type.cmd.len = 0; |
| 483 | return fail; |
| 484 | case IOResult::kInterrupt: |
| 485 | transport_->DT_IO_ERROR("Failed to read, concurrent close!"); |
| 486 | is_err_ = true; |
| 487 | return fail; |
| 488 | } |
| 489 | } |
| 490 | |
| 491 | jbyte* ReadRemaining() { |
| 492 | if (is_eof_ || is_err_) { |
| 493 | return nullptr; |
| 494 | } |
| 495 | jbyte* out = nullptr; |
| 496 | jint rem = pkt_->type.cmd.len - 11; |
| 497 | CHECK_GE(rem, 0); |
| 498 | if (rem == 0) { |
| 499 | return nullptr; |
| 500 | } else { |
| 501 | out = reinterpret_cast<jbyte*>(transport_->Alloc(rem)); |
| 502 | IOResult res = transport_->ReadFully(out, rem); |
| 503 | jbyte* ret = HandleResult(res, out, static_cast<jbyte*>(nullptr)); |
| 504 | if (ret != out) { |
| 505 | transport_->Free(out); |
| 506 | } |
| 507 | return ret; |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | jbyte ReadByte() { |
| 512 | if (is_eof_ || is_err_) { |
| 513 | return -1; |
| 514 | } |
| 515 | jbyte out; |
| 516 | IOResult res = transport_->ReadFully(&out, sizeof(out)); |
| 517 | return HandleResult(res, NetworkToHost(out), static_cast<jbyte>(-1)); |
| 518 | } |
| 519 | |
| 520 | jshort ReadInt16() { |
| 521 | if (is_eof_ || is_err_) { |
| 522 | return -1; |
| 523 | } |
| 524 | jshort out; |
| 525 | IOResult res = transport_->ReadFully(&out, sizeof(out)); |
| 526 | return HandleResult(res, NetworkToHost(out), static_cast<jshort>(-1)); |
| 527 | } |
| 528 | |
| 529 | jint ReadInt32() { |
| 530 | if (is_eof_ || is_err_) { |
| 531 | return -1; |
| 532 | } |
| 533 | jint out; |
| 534 | IOResult res = transport_->ReadFully(&out, sizeof(out)); |
| 535 | return HandleResult(res, NetworkToHost(out), -1); |
| 536 | } |
| 537 | |
| 538 | FdForwardTransport* transport_; |
| 539 | jdwpPacket* pkt_; |
| 540 | bool is_eof_; |
| 541 | bool is_err_; |
| 542 | }; |
| 543 | |
| 544 | jdwpTransportError FdForwardTransport::ReadPacket(jdwpPacket* pkt) { |
| 545 | if (pkt == nullptr) { |
| 546 | return ERR(ILLEGAL_ARGUMENT); |
| 547 | } |
| 548 | PacketReader reader(this, pkt); |
| 549 | if (reader.ReadFully()) { |
| 550 | return OK; |
| 551 | } else { |
| 552 | return ERR(IO_ERROR); |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | // A class that writes a packet to the transport. |
| 557 | class PacketWriter { |
| 558 | public: |
| 559 | PacketWriter(FdForwardTransport* transport, const jdwpPacket* pkt) |
| 560 | : transport_(transport), pkt_(pkt), data_() {} |
| 561 | |
| 562 | bool WriteFully() { |
| 563 | PushInt32(pkt_->type.cmd.len); |
| 564 | PushInt32(pkt_->type.cmd.id); |
| 565 | PushByte(pkt_->type.cmd.flags); |
| 566 | if ((pkt_->type.reply.flags & JDWPTRANSPORT_FLAGS_REPLY) == JDWPTRANSPORT_FLAGS_REPLY) { |
| 567 | PushInt16(pkt_->type.reply.errorCode); |
| 568 | PushData(pkt_->type.reply.data, pkt_->type.reply.len - 11); |
| 569 | } else { |
| 570 | PushByte(pkt_->type.cmd.cmdSet); |
| 571 | PushByte(pkt_->type.cmd.cmd); |
| 572 | PushData(pkt_->type.cmd.data, pkt_->type.cmd.len - 11); |
| 573 | } |
| 574 | IOResult res = transport_->WriteFully(data_.data(), data_.size()); |
| 575 | return res == IOResult::kOk; |
| 576 | } |
| 577 | |
| 578 | private: |
| 579 | void PushInt32(int32_t data) { |
| 580 | data = HostToNetwork(data); |
| 581 | PushData(&data, sizeof(data)); |
| 582 | } |
| 583 | void PushInt16(int16_t data) { |
| 584 | data = HostToNetwork(data); |
| 585 | PushData(&data, sizeof(data)); |
| 586 | } |
| 587 | void PushByte(jbyte data) { |
| 588 | data_.push_back(HostToNetwork(data)); |
| 589 | } |
| 590 | |
| 591 | void PushData(void* d, size_t size) { |
| 592 | uint8_t* bytes = reinterpret_cast<uint8_t*>(d); |
| 593 | data_.insert(data_.end(), bytes, bytes + size); |
| 594 | } |
| 595 | |
| 596 | FdForwardTransport* transport_; |
| 597 | const jdwpPacket* pkt_; |
| 598 | std::vector<uint8_t> data_; |
| 599 | }; |
| 600 | |
| 601 | jdwpTransportError FdForwardTransport::WritePacket(const jdwpPacket* pkt) { |
| 602 | if (pkt == nullptr) { |
| 603 | return ERR(ILLEGAL_ARGUMENT); |
| 604 | } |
| 605 | PacketWriter writer(this, pkt); |
| 606 | if (writer.WriteFully()) { |
| 607 | return OK; |
| 608 | } else { |
| 609 | return ERR(IO_ERROR); |
| 610 | } |
| 611 | } |
| 612 | |
| 613 | jboolean FdForwardTransport::IsOpen() { |
| 614 | return state_ == TransportState::kOpen; |
| 615 | } |
| 616 | |
| 617 | void* FdForwardTransport::Alloc(size_t s) { |
| 618 | return mem_.alloc(s); |
| 619 | } |
| 620 | |
| 621 | void FdForwardTransport::Free(void* data) { |
| 622 | mem_.free(data); |
| 623 | } |
| 624 | |
| 625 | jdwpTransportError FdForwardTransport::GetLastError(/*out*/char** err) { |
| 626 | std::string data = global_last_error_; |
| 627 | *err = reinterpret_cast<char*>(Alloc(data.size() + 1)); |
| 628 | strcpy(*err, data.c_str()); |
| 629 | return OK; |
| 630 | } |
| 631 | |
| 632 | static FdForwardTransport* AsFdForward(jdwpTransportEnv* env) { |
| 633 | return reinterpret_cast<FdForwardTransport*>(env); |
| 634 | } |
| 635 | |
| 636 | static jdwpTransportError ParseAddress(const std::string& addr, |
| 637 | /*out*/int* listen_sock) { |
| 638 | if (!android::base::ParseInt(addr.c_str(), listen_sock) || *listen_sock < 0) { |
| 639 | LOG(ERROR) << "address format is <fd_num> not " << addr; |
| 640 | return ERR(ILLEGAL_ARGUMENT); |
| 641 | } |
| 642 | return OK; |
| 643 | } |
| 644 | |
| 645 | class JdwpTransportFunctions { |
| 646 | public: |
| 647 | static jdwpTransportError GetCapabilities(jdwpTransportEnv* env ATTRIBUTE_UNUSED, |
| 648 | /*out*/ JDWPTransportCapabilities* capabilities_ptr) { |
| 649 | // We don't support any of the optional capabilities (can_timeout_attach, can_timeout_accept, |
| 650 | // can_timeout_handshake) so just return a zeroed capabilities ptr. |
| 651 | // TODO We should maybe support these timeout options. |
| 652 | memset(capabilities_ptr, 0, sizeof(JDWPTransportCapabilities)); |
| 653 | return OK; |
| 654 | } |
| 655 | |
| 656 | // Address is <sock_fd> |
| 657 | static jdwpTransportError Attach(jdwpTransportEnv* env, |
| 658 | const char* address, |
| 659 | jlong attach_timeout ATTRIBUTE_UNUSED, |
| 660 | jlong handshake_timeout ATTRIBUTE_UNUSED) { |
| 661 | if (address == nullptr || *address == '\0') { |
| 662 | return ERR(ILLEGAL_ARGUMENT); |
| 663 | } |
| 664 | int listen_fd; |
| 665 | jdwpTransportError err = ParseAddress(address, &listen_fd); |
| 666 | if (err != OK) { |
| 667 | return err; |
| 668 | } |
| 669 | return AsFdForward(env)->PerformAttach(listen_fd); |
| 670 | } |
| 671 | |
| 672 | static jdwpTransportError StartListening(jdwpTransportEnv* env, |
| 673 | const char* address, |
| 674 | /*out*/ char** actual_address) { |
| 675 | if (address == nullptr || *address == '\0') { |
| 676 | return ERR(ILLEGAL_ARGUMENT); |
| 677 | } |
| 678 | int listen_fd; |
| 679 | jdwpTransportError err = ParseAddress(address, &listen_fd); |
| 680 | if (err != OK) { |
| 681 | return err; |
| 682 | } |
| 683 | err = AsFdForward(env)->SetupListen(listen_fd); |
| 684 | if (err != OK) { |
| 685 | return err; |
| 686 | } |
| 687 | if (actual_address != nullptr) { |
| 688 | *actual_address = reinterpret_cast<char*>(AsFdForward(env)->Alloc(strlen(address) + 1)); |
| 689 | memcpy(*actual_address, address, strlen(address) + 1); |
| 690 | } |
| 691 | return OK; |
| 692 | } |
| 693 | |
| 694 | static jdwpTransportError StopListening(jdwpTransportEnv* env) { |
| 695 | return AsFdForward(env)->StopListening(); |
| 696 | } |
| 697 | |
| 698 | static jdwpTransportError Accept(jdwpTransportEnv* env, |
| 699 | jlong accept_timeout ATTRIBUTE_UNUSED, |
| 700 | jlong handshake_timeout ATTRIBUTE_UNUSED) { |
| 701 | return AsFdForward(env)->Accept(); |
| 702 | } |
| 703 | |
| 704 | static jboolean IsOpen(jdwpTransportEnv* env) { |
| 705 | return AsFdForward(env)->IsOpen(); |
| 706 | } |
| 707 | |
| 708 | static jdwpTransportError Close(jdwpTransportEnv* env) { |
| 709 | return AsFdForward(env)->Close(); |
| 710 | } |
| 711 | |
| 712 | static jdwpTransportError ReadPacket(jdwpTransportEnv* env, jdwpPacket *pkt) { |
| 713 | return AsFdForward(env)->ReadPacket(pkt); |
| 714 | } |
| 715 | |
| 716 | static jdwpTransportError WritePacket(jdwpTransportEnv* env, const jdwpPacket* pkt) { |
| 717 | return AsFdForward(env)->WritePacket(pkt); |
| 718 | } |
| 719 | |
| 720 | static jdwpTransportError GetLastError(jdwpTransportEnv* env, char** error) { |
| 721 | return AsFdForward(env)->GetLastError(error); |
| 722 | } |
| 723 | }; |
| 724 | |
| 725 | // The actual struct holding all the entrypoints into the jdwpTransport interface. |
| 726 | const jdwpTransportNativeInterface_ gTransportInterface = { |
| 727 | nullptr, // reserved1 |
| 728 | JdwpTransportFunctions::GetCapabilities, |
| 729 | JdwpTransportFunctions::Attach, |
| 730 | JdwpTransportFunctions::StartListening, |
| 731 | JdwpTransportFunctions::StopListening, |
| 732 | JdwpTransportFunctions::Accept, |
| 733 | JdwpTransportFunctions::IsOpen, |
| 734 | JdwpTransportFunctions::Close, |
| 735 | JdwpTransportFunctions::ReadPacket, |
| 736 | JdwpTransportFunctions::WritePacket, |
| 737 | JdwpTransportFunctions::GetLastError, |
| 738 | }; |
| 739 | |
| 740 | extern "C" |
| 741 | JNIEXPORT jint JNICALL jdwpTransport_OnLoad(JavaVM* vm ATTRIBUTE_UNUSED, |
| 742 | jdwpTransportCallback* cb, |
| 743 | jint version, |
| 744 | jdwpTransportEnv** /*out*/env) { |
| 745 | if (version != JDWPTRANSPORT_VERSION_1_0) { |
| 746 | LOG(ERROR) << "unknown version " << version; |
| 747 | return JNI_EVERSION; |
| 748 | } |
| 749 | void* data = cb->alloc(sizeof(FdForwardTransport)); |
| 750 | if (data == nullptr) { |
| 751 | LOG(ERROR) << "Failed to allocate data for transport!"; |
| 752 | return JNI_ENOMEM; |
| 753 | } |
| 754 | FdForwardTransport* transport = |
| 755 | new (data) FdForwardTransport(cb); |
| 756 | transport->functions = &gTransportInterface; |
| 757 | *env = transport; |
| 758 | return JNI_OK; |
| 759 | } |
| 760 | |
| 761 | } // namespace dt_fd_forward |