blob: 85f3c5299bc18daaac9d4096ca7fe3d032ba82e5 [file] [log] [blame]
Josh Gao6082e7d2018-04-05 16:16:04 -07001/*
2 * Copyright (C) 2018 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 <stdint.h>
18
19#include <deque>
20#include <mutex>
21#include <string>
22#include <thread>
23
24#include <android-base/logging.h>
25#include <android-base/stringprintf.h>
26#include <android-base/thread_annotations.h>
27
28#include "adb_unique_fd.h"
29#include "adb_utils.h"
30#include "sysdeps.h"
31#include "sysdeps/memory.h"
32#include "transport.h"
33#include "types.h"
34
35static void CreateWakeFds(unique_fd* read, unique_fd* write) {
36 // TODO: eventfd on linux?
37 int wake_fds[2];
38 int rc = adb_socketpair(wake_fds);
39 set_file_block_mode(wake_fds[0], false);
40 set_file_block_mode(wake_fds[1], false);
41 CHECK_EQ(0, rc);
42 *read = unique_fd(wake_fds[0]);
43 *write = unique_fd(wake_fds[1]);
44}
45
46struct NonblockingFdConnection : public Connection {
47 NonblockingFdConnection(unique_fd fd) : started_(false), fd_(std::move(fd)) {
48 set_file_block_mode(fd_.get(), false);
49 CreateWakeFds(&wake_fd_read_, &wake_fd_write_);
50 }
51
52 void SetRunning(bool value) {
53 std::lock_guard<std::mutex> lock(run_mutex_);
54 running_ = value;
55 }
56
57 bool IsRunning() {
58 std::lock_guard<std::mutex> lock(run_mutex_);
59 return running_;
60 }
61
62 void Run(std::string* error) {
63 SetRunning(true);
64 while (IsRunning()) {
65 adb_pollfd pfds[2] = {
66 {.fd = fd_.get(), .events = POLLIN},
67 {.fd = wake_fd_read_.get(), .events = POLLIN},
68 };
69
70 {
71 std::lock_guard<std::mutex> lock(this->write_mutex_);
72 if (!writable_) {
73 pfds[0].events |= POLLOUT;
74 }
75 }
76
77 int rc = adb_poll(pfds, 2, -1);
78 if (rc == -1) {
79 *error = android::base::StringPrintf("poll failed: %s", strerror(errno));
80 return;
81 } else if (rc == 0) {
82 LOG(FATAL) << "poll timed out with an infinite timeout?";
83 }
84
85 if (pfds[0].revents) {
86 if ((pfds[0].revents & POLLOUT)) {
87 std::lock_guard<std::mutex> lock(this->write_mutex_);
88 WriteResult result = DispatchWrites();
89 switch (result) {
90 case WriteResult::Error:
91 *error = "write failed";
92 return;
93
94 case WriteResult::Completed:
95 writable_ = true;
96 break;
97
98 case WriteResult::TryAgain:
99 break;
100 }
101 }
102
103 if (pfds[0].revents & POLLIN) {
104 // TODO: Should we be getting blocks from a free list?
105 auto block = std::make_unique<IOVector::block_type>(MAX_PAYLOAD);
106 rc = adb_read(fd_.get(), &(*block)[0], block->size());
107 if (rc == -1) {
108 *error = std::string("read failed: ") + strerror(errno);
109 return;
110 } else if (rc == 0) {
111 *error = "read failed: EOF";
112 return;
113 }
114 block->resize(rc);
115 read_buffer_.append(std::move(block));
116
117 if (!read_header_ && read_buffer_.size() >= sizeof(amessage)) {
118 auto header_buf = read_buffer_.take_front(sizeof(amessage)).coalesce();
119 CHECK_EQ(sizeof(amessage), header_buf.size());
120 read_header_ = std::make_unique<amessage>();
121 memcpy(read_header_.get(), header_buf.data(), sizeof(amessage));
122 }
123
124 if (read_header_ && read_buffer_.size() >= read_header_->data_length) {
125 auto data_chain = read_buffer_.take_front(read_header_->data_length);
126
127 // TODO: Make apacket carry around a IOVector instead of coalescing.
128 auto payload = data_chain.coalesce<apacket::payload_type>();
129 auto packet = std::make_unique<apacket>();
130 packet->msg = *read_header_;
131 packet->payload = std::move(payload);
132 read_header_ = nullptr;
133 read_callback_(this, std::move(packet));
134 }
135 }
136 }
137
138 if (pfds[1].revents) {
139 uint64_t buf;
140 rc = adb_read(wake_fd_read_.get(), &buf, sizeof(buf));
141 CHECK_EQ(static_cast<int>(sizeof(buf)), rc);
142
143 // We were woken up either to add POLLOUT to our events, or to exit.
144 // Do nothing.
145 }
146 }
147 }
148
149 void Start() override final {
150 if (started_.exchange(true)) {
151 LOG(FATAL) << "Connection started multiple times?";
152 }
153
154 thread_ = std::thread([this]() {
155 std::string error = "connection closed";
156 Run(&error);
157 this->error_callback_(this, error);
158 });
159 }
160
161 void Stop() override final {
162 SetRunning(false);
163 WakeThread();
164 thread_.join();
165 }
166
167 void WakeThread() {
168 uint64_t buf = 0;
169 if (TEMP_FAILURE_RETRY(adb_write(wake_fd_write_.get(), &buf, sizeof(buf))) != sizeof(buf)) {
170 LOG(FATAL) << "failed to wake up thread";
171 }
172 }
173
174 enum class WriteResult {
175 Error,
176 Completed,
177 TryAgain,
178 };
179
180 WriteResult DispatchWrites() REQUIRES(write_mutex_) {
181 CHECK(!write_buffer_.empty());
182 if (!writable_) {
183 return WriteResult::TryAgain;
184 }
185
186 auto iovs = write_buffer_.iovecs();
187 ssize_t rc = adb_writev(fd_.get(), iovs.data(), iovs.size());
188 if (rc == -1) {
189 return WriteResult::Error;
190 } else if (rc == 0) {
191 errno = 0;
192 return WriteResult::Error;
193 }
194
195 // TODO: Implement a more efficient drop_front?
196 write_buffer_.take_front(rc);
197 if (write_buffer_.empty()) {
198 return WriteResult::Completed;
199 }
200
201 // There's data left in the range, which means our write returned early.
202 return WriteResult::TryAgain;
203 }
204
205 bool Write(std::unique_ptr<apacket> packet) final {
206 std::lock_guard<std::mutex> lock(write_mutex_);
207 const char* header_begin = reinterpret_cast<const char*>(&packet->msg);
208 const char* header_end = header_begin + sizeof(packet->msg);
209 auto header_block = std::make_unique<IOVector::block_type>(header_begin, header_end);
210 write_buffer_.append(std::move(header_block));
211 if (!packet->payload.empty()) {
212 write_buffer_.append(std::make_unique<IOVector::block_type>(std::move(packet->payload)));
213 }
214 return DispatchWrites() != WriteResult::Error;
215 }
216
217 std::thread thread_;
218
219 std::atomic<bool> started_;
220 std::mutex run_mutex_;
221 bool running_ GUARDED_BY(run_mutex_);
222
223 std::unique_ptr<amessage> read_header_;
224 IOVector read_buffer_;
225
226 unique_fd fd_;
227 unique_fd wake_fd_read_;
228 unique_fd wake_fd_write_;
229
230 std::mutex write_mutex_;
231 bool writable_ GUARDED_BY(write_mutex_) = true;
232 IOVector write_buffer_ GUARDED_BY(write_mutex_);
233
234 IOVector incoming_queue_;
235};
236
237std::unique_ptr<Connection> Connection::FromFd(unique_fd fd) {
238 return std::make_unique<NonblockingFdConnection>(std::move(fd));
239}