blob: 6c066694db770fd054b6947fb35a10ed415ac311 [file] [log] [blame]
David Pursell80f67022015-08-28 15:08:49 -07001/*
2 * Copyright (C) 2015 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
David Pursell0955c662015-08-31 10:42:13 -070017// Functionality for launching and managing shell subprocesses.
18//
19// There are two types of subprocesses, PTY or raw. PTY is typically used for
20// an interactive session, raw for non-interactive. There are also two methods
21// of communication with the subprocess, passing raw data or using a simple
22// protocol to wrap packets. The protocol allows separating stdout/stderr and
23// passing the exit code back, but is not backwards compatible.
24// ----------------+--------------------------------------
25// Type Protocol | Exit code? Separate stdout/stderr?
26// ----------------+--------------------------------------
27// PTY No | No No
28// Raw No | No No
29// PTY Yes | Yes No
30// Raw Yes | Yes Yes
31// ----------------+--------------------------------------
32//
33// Non-protocol subprocesses work by passing subprocess stdin/out/err through
34// a single pipe which is registered with a local socket in adbd. The local
35// socket uses the fdevent loop to pass raw data between this pipe and the
36// transport, which then passes data back to the adb client. Cleanup is done by
37// waiting in a separate thread for the subprocesses to exit and then signaling
38// a separate fdevent to close out the local socket from the main loop.
39//
40// ------------------+-------------------------+------------------------------
41// Subprocess | adbd subprocess thread | adbd main fdevent loop
42// ------------------+-------------------------+------------------------------
43// | |
44// stdin/out/err <-----------------------------> LocalSocket
45// | | |
46// | | Block on exit |
47// | | * |
48// v | * |
49// Exit ---> Unblock |
50// | | |
51// | v |
52// | Notify shell exit FD ---> Close LocalSocket
53// ------------------+-------------------------+------------------------------
54//
55// The protocol requires the thread to intercept stdin/out/err in order to
56// wrap/unwrap data with shell protocol packets.
57//
58// ------------------+-------------------------+------------------------------
59// Subprocess | adbd subprocess thread | adbd main fdevent loop
60// ------------------+-------------------------+------------------------------
61// | |
62// stdin/out <---> Protocol <---> LocalSocket
63// stderr ---> Protocol ---> LocalSocket
64// | | |
65// v | |
66// Exit ---> Exit code protocol ---> LocalSocket
67// | | |
68// | v |
69// | Notify shell exit FD ---> Close LocalSocket
70// ------------------+-------------------------+------------------------------
71//
72// An alternate approach is to put the protocol wrapping/unwrapping in the main
73// fdevent loop, which has the advantage of being able to re-use the existing
74// select() code for handling data streams. However, implementation turned out
75// to be more complex due to partial reads and non-blocking I/O so this model
76// was chosen instead.
77
Yabin Cuiaed3c612015-09-22 15:52:57 -070078#define TRACE_TAG SHELL
David Pursell80f67022015-08-28 15:08:49 -070079
Yabin Cui6dfef252015-10-06 15:10:05 -070080#include "sysdeps.h"
David Pursell80f67022015-08-28 15:08:49 -070081
Yabin Cui6dfef252015-10-06 15:10:05 -070082#include "shell_service.h"
David Pursell80f67022015-08-28 15:08:49 -070083
David Pursella9320582015-08-28 18:31:29 -070084#include <errno.h>
David Pursell80f67022015-08-28 15:08:49 -070085#include <pty.h>
Elliott Hughesfbe43322015-11-02 13:29:19 -080086#include <pwd.h>
David Pursell0955c662015-08-31 10:42:13 -070087#include <sys/select.h>
David Pursell80f67022015-08-28 15:08:49 -070088#include <termios.h>
89
David Pursell0955c662015-08-31 10:42:13 -070090#include <memory>
91
Elliott Hughes4f713192015-12-04 22:00:26 -080092#include <android-base/logging.h>
93#include <android-base/stringprintf.h>
David Pursell80f67022015-08-28 15:08:49 -070094#include <paths.h>
95
96#include "adb.h"
97#include "adb_io.h"
98#include "adb_trace.h"
Yabin Cui6dfef252015-10-06 15:10:05 -070099#include "adb_utils.h"
David Pursell80f67022015-08-28 15:08:49 -0700100
101namespace {
102
103void init_subproc_child()
104{
105 setsid();
106
107 // Set OOM score adjustment to prevent killing
108 int fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC);
109 if (fd >= 0) {
110 adb_write(fd, "0", 1);
111 adb_close(fd);
112 } else {
113 D("adb: unable to update oom_score_adj");
114 }
115}
116
David Pursella9320582015-08-28 18:31:29 -0700117// Reads from |fd| until close or failure.
118std::string ReadAll(int fd) {
119 char buffer[512];
120 std::string received;
121
122 while (1) {
123 int bytes = adb_read(fd, buffer, sizeof(buffer));
124 if (bytes <= 0) {
125 break;
126 }
127 received.append(buffer, bytes);
David Pursell80f67022015-08-28 15:08:49 -0700128 }
129
David Pursella9320582015-08-28 18:31:29 -0700130 return received;
131}
132
133// Helper to automatically close an FD when it goes out of scope.
134class ScopedFd {
135 public:
136 ScopedFd() {}
137 ~ScopedFd() { Reset(); }
138
139 void Reset(int fd=-1) {
140 if (fd != fd_) {
141 if (valid()) {
142 adb_close(fd_);
143 }
144 fd_ = fd;
145 }
146 }
147
148 int Release() {
149 int temp = fd_;
150 fd_ = -1;
151 return temp;
152 }
153
154 bool valid() const { return fd_ >= 0; }
155
156 int fd() const { return fd_; }
157
158 private:
159 int fd_ = -1;
160
161 DISALLOW_COPY_AND_ASSIGN(ScopedFd);
162};
163
164// Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
165bool CreateSocketpair(ScopedFd* fd1, ScopedFd* fd2) {
166 int sockets[2];
167 if (adb_socketpair(sockets) < 0) {
168 PLOG(ERROR) << "cannot create socket pair";
169 return false;
170 }
171 fd1->Reset(sockets[0]);
172 fd2->Reset(sockets[1]);
173 return true;
174}
175
176class Subprocess {
177 public:
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800178 Subprocess(const std::string& command, const char* terminal_type,
179 SubprocessType type, SubprocessProtocol protocol);
David Pursella9320582015-08-28 18:31:29 -0700180 ~Subprocess();
181
182 const std::string& command() const { return command_; }
183 bool is_interactive() const { return command_.empty(); }
184
185 int local_socket_fd() const { return local_socket_sfd_.fd(); }
186
187 pid_t pid() const { return pid_; }
188
189 // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
190 // and exec's the child. Returns false on failure.
191 bool ForkAndExec();
192
193 private:
194 // Opens the file at |pts_name|.
195 int OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd);
196
197 static void* ThreadHandler(void* userdata);
David Pursell0955c662015-08-31 10:42:13 -0700198 void PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700199 void WaitForExit();
200
David Pursell0955c662015-08-31 10:42:13 -0700201 ScopedFd* SelectLoop(fd_set* master_read_set_ptr,
202 fd_set* master_write_set_ptr);
203
204 // Input/output stream handlers. Success returns nullptr, failure returns
205 // a pointer to the failed FD.
206 ScopedFd* PassInput();
207 ScopedFd* PassOutput(ScopedFd* sfd, ShellProtocol::Id id);
208
David Pursella9320582015-08-28 18:31:29 -0700209 const std::string command_;
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800210 const std::string terminal_type_;
David Pursella9320582015-08-28 18:31:29 -0700211 SubprocessType type_;
David Pursell0955c662015-08-31 10:42:13 -0700212 SubprocessProtocol protocol_;
David Pursella9320582015-08-28 18:31:29 -0700213 pid_t pid_ = -1;
214 ScopedFd local_socket_sfd_;
215
David Pursell0955c662015-08-31 10:42:13 -0700216 // Shell protocol variables.
217 ScopedFd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
218 std::unique_ptr<ShellProtocol> input_, output_;
219 size_t input_bytes_left_ = 0;
220
David Pursella9320582015-08-28 18:31:29 -0700221 DISALLOW_COPY_AND_ASSIGN(Subprocess);
222};
223
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800224Subprocess::Subprocess(const std::string& command, const char* terminal_type,
225 SubprocessType type, SubprocessProtocol protocol)
226 : command_(command),
227 terminal_type_(terminal_type ? terminal_type : ""),
228 type_(type),
229 protocol_(protocol) {
David Pursella9320582015-08-28 18:31:29 -0700230}
231
232Subprocess::~Subprocess() {
233}
234
235bool Subprocess::ForkAndExec() {
David Pursell0955c662015-08-31 10:42:13 -0700236 ScopedFd child_stdinout_sfd, child_stderr_sfd;
237 ScopedFd parent_error_sfd, child_error_sfd;
David Pursella9320582015-08-28 18:31:29 -0700238 char pts_name[PATH_MAX];
239
240 // Create a socketpair for the fork() child to report any errors back to
241 // the parent. Since we use threads, logging directly from the child could
242 // create a race condition.
243 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
244 LOG(ERROR) << "failed to create pipe for subprocess error reporting";
245 }
246
247 if (type_ == SubprocessType::kPty) {
248 int fd;
249 pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
David Pursell0955c662015-08-31 10:42:13 -0700250 stdinout_sfd_.Reset(fd);
David Pursella9320582015-08-28 18:31:29 -0700251 } else {
David Pursell0955c662015-08-31 10:42:13 -0700252 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
253 return false;
254 }
255 // Raw subprocess + shell protocol allows for splitting stderr.
256 if (protocol_ == SubprocessProtocol::kShell &&
257 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
David Pursella9320582015-08-28 18:31:29 -0700258 return false;
259 }
260 pid_ = fork();
261 }
262
263 if (pid_ == -1) {
264 PLOG(ERROR) << "fork failed";
265 return false;
266 }
267
268 if (pid_ == 0) {
269 // Subprocess child.
David Pursell80f67022015-08-28 15:08:49 -0700270 init_subproc_child();
271
David Pursella9320582015-08-28 18:31:29 -0700272 if (type_ == SubprocessType::kPty) {
David Pursell0955c662015-08-31 10:42:13 -0700273 child_stdinout_sfd.Reset(OpenPtyChildFd(pts_name, &child_error_sfd));
David Pursella9320582015-08-28 18:31:29 -0700274 }
275
David Pursell0955c662015-08-31 10:42:13 -0700276 dup2(child_stdinout_sfd.fd(), STDIN_FILENO);
277 dup2(child_stdinout_sfd.fd(), STDOUT_FILENO);
278 dup2(child_stderr_sfd.valid() ? child_stderr_sfd.fd() : child_stdinout_sfd.fd(),
279 STDERR_FILENO);
David Pursella9320582015-08-28 18:31:29 -0700280
281 // exec doesn't trigger destructors, close the FDs manually.
David Pursell0955c662015-08-31 10:42:13 -0700282 stdinout_sfd_.Reset();
283 stderr_sfd_.Reset();
284 child_stdinout_sfd.Reset();
285 child_stderr_sfd.Reset();
David Pursella9320582015-08-28 18:31:29 -0700286 parent_error_sfd.Reset();
287 close_on_exec(child_error_sfd.fd());
288
Elliott Hughesfbe43322015-11-02 13:29:19 -0800289 // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
290 passwd* pw = getpwuid(getuid());
291 if (pw != nullptr) {
Elliott Hughesfbe43322015-11-02 13:29:19 -0800292 setenv("LOGNAME", pw->pw_name, 1);
293 setenv("SHELL", pw->pw_shell, 1);
294 setenv("USER", pw->pw_name, 1);
295 }
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800296 if (!terminal_type_.empty()) {
297 setenv("TERM", terminal_type_.c_str(), 1);
298 }
Elliott Hughesfbe43322015-11-02 13:29:19 -0800299
Nick Kralevich173eb392015-12-07 15:17:56 -0800300 setenv("HOME", "/data/local/tmp", 1);
301 chdir(getenv("HOME"));
David Pursella9320582015-08-28 18:31:29 -0700302 if (is_interactive()) {
303 execl(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr);
304 } else {
305 execl(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr);
306 }
307 WriteFdExactly(child_error_sfd.fd(), "exec '" _PATH_BSHELL "' failed");
308 child_error_sfd.Reset();
309 exit(-1);
310 }
311
312 // Subprocess parent.
David Pursell0955c662015-08-31 10:42:13 -0700313 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
314 stdinout_sfd_.fd(), stderr_sfd_.fd());
David Pursella9320582015-08-28 18:31:29 -0700315
316 // Wait to make sure the subprocess exec'd without error.
317 child_error_sfd.Reset();
318 std::string error_message = ReadAll(parent_error_sfd.fd());
319 if (!error_message.empty()) {
320 LOG(ERROR) << error_message;
321 return false;
322 }
323
David Pursell0955c662015-08-31 10:42:13 -0700324 if (protocol_ == SubprocessProtocol::kNone) {
325 // No protocol: all streams pass through the stdinout FD and hook
326 // directly into the local socket for raw data transfer.
327 local_socket_sfd_.Reset(stdinout_sfd_.Release());
328 } else {
329 // Shell protocol: create another socketpair to intercept data.
330 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
331 return false;
332 }
333 D("protocol FD = %d", protocol_sfd_.fd());
334
335 input_.reset(new ShellProtocol(protocol_sfd_.fd()));
336 output_.reset(new ShellProtocol(protocol_sfd_.fd()));
337 if (!input_ || !output_) {
338 LOG(ERROR) << "failed to allocate shell protocol objects";
339 return false;
340 }
341
342 // Don't let reads/writes to the subprocess block our thread. This isn't
343 // likely but could happen under unusual circumstances, such as if we
344 // write a ton of data to stdin but the subprocess never reads it and
345 // the pipe fills up.
346 for (int fd : {stdinout_sfd_.fd(), stderr_sfd_.fd()}) {
347 if (fd >= 0) {
Yabin Cui6dfef252015-10-06 15:10:05 -0700348 if (!set_file_block_mode(fd, false)) {
349 LOG(ERROR) << "failed to set non-blocking mode for fd " << fd;
David Pursell0955c662015-08-31 10:42:13 -0700350 return false;
351 }
352 }
353 }
354 }
David Pursella9320582015-08-28 18:31:29 -0700355
356 if (!adb_thread_create(ThreadHandler, this)) {
357 PLOG(ERROR) << "failed to create subprocess thread";
358 return false;
359 }
360
361 return true;
362}
363
364int Subprocess::OpenPtyChildFd(const char* pts_name, ScopedFd* error_sfd) {
365 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
366 if (child_fd == -1) {
367 // Don't use WriteFdFmt; since we're in the fork() child we don't want
368 // to allocate any heap memory to avoid race conditions.
369 const char* messages[] = {"child failed to open pseudo-term slave ",
370 pts_name, ": ", strerror(errno)};
371 for (const char* message : messages) {
372 WriteFdExactly(error_sfd->fd(), message);
373 }
374 exit(-1);
375 }
376
377 if (!is_interactive()) {
378 termios tattr;
379 if (tcgetattr(child_fd, &tattr) == -1) {
380 WriteFdExactly(error_sfd->fd(), "tcgetattr failed");
David Pursell80f67022015-08-28 15:08:49 -0700381 exit(-1);
382 }
383
David Pursella9320582015-08-28 18:31:29 -0700384 cfmakeraw(&tattr);
385 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
386 WriteFdExactly(error_sfd->fd(), "tcsetattr failed");
387 exit(-1);
David Pursell80f67022015-08-28 15:08:49 -0700388 }
David Pursell80f67022015-08-28 15:08:49 -0700389 }
David Pursella9320582015-08-28 18:31:29 -0700390
391 return child_fd;
David Pursell80f67022015-08-28 15:08:49 -0700392}
393
David Pursella9320582015-08-28 18:31:29 -0700394void* Subprocess::ThreadHandler(void* userdata) {
395 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
David Pursell80f67022015-08-28 15:08:49 -0700396
David Pursella9320582015-08-28 18:31:29 -0700397 adb_thread_setname(android::base::StringPrintf(
398 "shell srvc %d", subprocess->local_socket_fd()));
David Pursell80f67022015-08-28 15:08:49 -0700399
David Pursell0955c662015-08-31 10:42:13 -0700400 subprocess->PassDataStreams();
David Pursella9320582015-08-28 18:31:29 -0700401 subprocess->WaitForExit();
David Pursell80f67022015-08-28 15:08:49 -0700402
David Pursell1ed57f02015-10-06 15:30:03 -0700403 D("deleting Subprocess for PID %d", subprocess->pid());
David Pursella9320582015-08-28 18:31:29 -0700404 delete subprocess;
David Pursell80f67022015-08-28 15:08:49 -0700405
David Pursella9320582015-08-28 18:31:29 -0700406 return nullptr;
David Pursell80f67022015-08-28 15:08:49 -0700407}
408
David Pursell0955c662015-08-31 10:42:13 -0700409void Subprocess::PassDataStreams() {
410 if (!protocol_sfd_.valid()) {
411 return;
412 }
413
414 // Start by trying to read from the protocol FD, stdout, and stderr.
415 fd_set master_read_set, master_write_set;
416 FD_ZERO(&master_read_set);
417 FD_ZERO(&master_write_set);
418 for (ScopedFd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
419 if (sfd->valid()) {
420 FD_SET(sfd->fd(), &master_read_set);
421 }
422 }
423
424 // Pass data until the protocol FD or both the subprocess pipes die, at
425 // which point we can't pass any more data.
426 while (protocol_sfd_.valid() &&
427 (stdinout_sfd_.valid() || stderr_sfd_.valid())) {
428 ScopedFd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
429 if (dead_sfd) {
430 D("closing FD %d", dead_sfd->fd());
431 FD_CLR(dead_sfd->fd(), &master_read_set);
432 FD_CLR(dead_sfd->fd(), &master_write_set);
David Pursell544e7952015-09-14 15:36:26 -0700433 if (dead_sfd == &protocol_sfd_) {
434 // Using SIGHUP is a decent general way to indicate that the
435 // controlling process is going away. If specific signals are
436 // needed (e.g. SIGINT), pass those through the shell protocol
437 // and only fall back on this for unexpected closures.
438 D("protocol FD died, sending SIGHUP to pid %d", pid_);
439 kill(pid_, SIGHUP);
440 }
David Pursell0955c662015-08-31 10:42:13 -0700441 dead_sfd->Reset();
442 }
443 }
444}
445
446namespace {
447
448inline bool ValidAndInSet(const ScopedFd& sfd, fd_set* set) {
449 return sfd.valid() && FD_ISSET(sfd.fd(), set);
450}
451
452} // namespace
453
454ScopedFd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
455 fd_set* master_write_set_ptr) {
456 fd_set read_set, write_set;
457 int select_n = std::max(std::max(protocol_sfd_.fd(), stdinout_sfd_.fd()),
458 stderr_sfd_.fd()) + 1;
459 ScopedFd* dead_sfd = nullptr;
460
461 // Keep calling select() and passing data until an FD closes/errors.
462 while (!dead_sfd) {
463 memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
464 memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
465 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
466 if (errno == EINTR) {
467 continue;
468 } else {
469 PLOG(ERROR) << "select failed, closing subprocess pipes";
470 stdinout_sfd_.Reset();
471 stderr_sfd_.Reset();
472 return nullptr;
473 }
474 }
475
476 // Read stdout, write to protocol FD.
477 if (ValidAndInSet(stdinout_sfd_, &read_set)) {
478 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
479 }
480
481 // Read stderr, write to protocol FD.
482 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
483 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
484 }
485
486 // Read protocol FD, write to stdin.
487 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
488 dead_sfd = PassInput();
489 // If we didn't finish writing, block on stdin write.
490 if (input_bytes_left_) {
491 FD_CLR(protocol_sfd_.fd(), master_read_set_ptr);
492 FD_SET(stdinout_sfd_.fd(), master_write_set_ptr);
493 }
494 }
495
496 // Continue writing to stdin; only happens if a previous write blocked.
497 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
498 dead_sfd = PassInput();
499 // If we finished writing, go back to blocking on protocol read.
500 if (!input_bytes_left_) {
501 FD_SET(protocol_sfd_.fd(), master_read_set_ptr);
502 FD_CLR(stdinout_sfd_.fd(), master_write_set_ptr);
503 }
504 }
505 } // while (!dead_sfd)
506
507 return dead_sfd;
508}
509
510ScopedFd* Subprocess::PassInput() {
511 // Only read a new packet if we've finished writing the last one.
512 if (!input_bytes_left_) {
513 if (!input_->Read()) {
514 // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
515 if (errno != 0) {
516 PLOG(ERROR) << "error reading protocol FD "
517 << protocol_sfd_.fd();
518 }
519 return &protocol_sfd_;
520 }
521
David Pursell1ed57f02015-10-06 15:30:03 -0700522 if (stdinout_sfd_.valid()) {
523 switch (input_->id()) {
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800524 case ShellProtocol::kIdWindowSizeChange:
525 int rows, cols, x_pixels, y_pixels;
526 if (sscanf(input_->data(), "%dx%d,%dx%d",
527 &rows, &cols, &x_pixels, &y_pixels) == 4) {
528 winsize ws;
529 ws.ws_row = rows;
530 ws.ws_col = cols;
531 ws.ws_xpixel = x_pixels;
532 ws.ws_ypixel = y_pixels;
533 ioctl(stdinout_sfd_.fd(), TIOCSWINSZ, &ws);
534 }
535 break;
David Pursell1ed57f02015-10-06 15:30:03 -0700536 case ShellProtocol::kIdStdin:
537 input_bytes_left_ = input_->data_length();
538 break;
539 case ShellProtocol::kIdCloseStdin:
540 if (type_ == SubprocessType::kRaw) {
541 if (adb_shutdown(stdinout_sfd_.fd(), SHUT_WR) == 0) {
542 return nullptr;
543 }
544 PLOG(ERROR) << "failed to shutdown writes to FD "
545 << stdinout_sfd_.fd();
546 return &stdinout_sfd_;
547 } else {
548 // PTYs can't close just input, so rather than close the
549 // FD and risk losing subprocess output, leave it open.
550 // This only happens if the client starts a PTY shell
551 // non-interactively which is rare and unsupported.
552 // If necessary, the client can manually close the shell
553 // with `exit` or by killing the adb client process.
Elliott Hughesc15b17f2015-11-03 11:18:40 -0800554 D("can't close input for PTY FD %d", stdinout_sfd_.fd());
David Pursell1ed57f02015-10-06 15:30:03 -0700555 }
556 break;
557 }
David Pursell0955c662015-08-31 10:42:13 -0700558 }
559 }
560
561 if (input_bytes_left_ > 0) {
562 int index = input_->data_length() - input_bytes_left_;
563 int bytes = adb_write(stdinout_sfd_.fd(), input_->data() + index,
564 input_bytes_left_);
565 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
566 if (bytes < 0) {
567 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_.fd();
568 }
569 // stdin is done, mark this packet as finished and we'll just start
570 // dumping any further data received from the protocol FD.
571 input_bytes_left_ = 0;
572 return &stdinout_sfd_;
573 } else if (bytes > 0) {
574 input_bytes_left_ -= bytes;
575 }
576 }
577
578 return nullptr;
579}
580
581ScopedFd* Subprocess::PassOutput(ScopedFd* sfd, ShellProtocol::Id id) {
582 int bytes = adb_read(sfd->fd(), output_->data(), output_->data_capacity());
583 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
David Pursell1ed57f02015-10-06 15:30:03 -0700584 // read() returns EIO if a PTY closes; don't report this as an error,
585 // it just means the subprocess completed.
586 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
David Pursell0955c662015-08-31 10:42:13 -0700587 PLOG(ERROR) << "error reading output FD " << sfd->fd();
588 }
589 return sfd;
590 }
591
592 if (bytes > 0 && !output_->Write(id, bytes)) {
593 if (errno != 0) {
594 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_.fd();
595 }
596 return &protocol_sfd_;
597 }
598
599 return nullptr;
600}
601
David Pursella9320582015-08-28 18:31:29 -0700602void Subprocess::WaitForExit() {
David Pursell0955c662015-08-31 10:42:13 -0700603 int exit_code = 1;
604
David Pursella9320582015-08-28 18:31:29 -0700605 D("waiting for pid %d", pid_);
David Pursell80f67022015-08-28 15:08:49 -0700606 while (true) {
607 int status;
David Pursella9320582015-08-28 18:31:29 -0700608 if (pid_ == waitpid(pid_, &status, 0)) {
609 D("post waitpid (pid=%d) status=%04x", pid_, status);
David Pursell80f67022015-08-28 15:08:49 -0700610 if (WIFSIGNALED(status)) {
David Pursell0955c662015-08-31 10:42:13 -0700611 exit_code = 0x80 | WTERMSIG(status);
David Pursella9320582015-08-28 18:31:29 -0700612 D("subprocess killed by signal %d", WTERMSIG(status));
David Pursell80f67022015-08-28 15:08:49 -0700613 break;
614 } else if (!WIFEXITED(status)) {
David Pursella9320582015-08-28 18:31:29 -0700615 D("subprocess didn't exit");
David Pursell80f67022015-08-28 15:08:49 -0700616 break;
617 } else if (WEXITSTATUS(status) >= 0) {
David Pursell0955c662015-08-31 10:42:13 -0700618 exit_code = WEXITSTATUS(status);
David Pursella9320582015-08-28 18:31:29 -0700619 D("subprocess exit code = %d", WEXITSTATUS(status));
David Pursell80f67022015-08-28 15:08:49 -0700620 break;
621 }
David Pursella9320582015-08-28 18:31:29 -0700622 }
David Pursell80f67022015-08-28 15:08:49 -0700623 }
David Pursella9320582015-08-28 18:31:29 -0700624
David Pursell0955c662015-08-31 10:42:13 -0700625 // If we have an open protocol FD send an exit packet.
626 if (protocol_sfd_.valid()) {
627 output_->data()[0] = exit_code;
628 if (output_->Write(ShellProtocol::kIdExit, 1)) {
629 D("wrote the exit code packet: %d", exit_code);
630 } else {
631 PLOG(ERROR) << "failed to write the exit code packet";
632 }
633 protocol_sfd_.Reset();
634 }
635
David Pursella9320582015-08-28 18:31:29 -0700636 // Pass the local socket FD to the shell cleanup fdevent.
637 if (SHELL_EXIT_NOTIFY_FD >= 0) {
638 int fd = local_socket_sfd_.fd();
639 if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
640 D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
641 fd, SHELL_EXIT_NOTIFY_FD, pid_);
642 // The shell exit fdevent now owns the FD and will close it once
643 // the last bit of data flushes through.
644 local_socket_sfd_.Release();
645 } else {
646 PLOG(ERROR) << "failed to write fd " << fd
647 << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
648 << ") for pid " << pid_;
649 }
David Pursell80f67022015-08-28 15:08:49 -0700650 }
651}
652
653} // namespace
654
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800655int StartSubprocess(const char* name, const char* terminal_type,
656 SubprocessType type, SubprocessProtocol protocol) {
657 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
David Pursell0955c662015-08-31 10:42:13 -0700658 type == SubprocessType::kRaw ? "raw" : "PTY",
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800659 protocol == SubprocessProtocol::kNone ? "none" : "shell",
660 terminal_type, name);
David Pursell80f67022015-08-28 15:08:49 -0700661
Elliott Hughes18ddf5c2015-11-16 10:55:34 -0800662 Subprocess* subprocess = new Subprocess(name, terminal_type, type, protocol);
David Pursella9320582015-08-28 18:31:29 -0700663 if (!subprocess) {
664 LOG(ERROR) << "failed to allocate new subprocess";
David Pursell80f67022015-08-28 15:08:49 -0700665 return -1;
666 }
667
David Pursella9320582015-08-28 18:31:29 -0700668 if (!subprocess->ForkAndExec()) {
669 LOG(ERROR) << "failed to start subprocess";
670 delete subprocess;
671 return -1;
672 }
673
674 D("subprocess creation successful: local_socket_fd=%d, pid=%d",
675 subprocess->local_socket_fd(), subprocess->pid());
676 return subprocess->local_socket_fd();
David Pursell80f67022015-08-28 15:08:49 -0700677}