1 /* 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 17 // 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 78 #define TRACE_TAG SHELL 79 80 #include "sysdeps.h" 81 82 #include "shell_service.h" 83 84 #include <errno.h> 85 #include <paths.h> 86 #include <pty.h> 87 #include <pwd.h> 88 #include <sys/select.h> 89 #include <termios.h> 90 91 #include <memory> 92 #include <string> 93 #include <thread> 94 #include <unordered_map> 95 #include <vector> 96 97 #include <android-base/logging.h> 98 #include <android-base/properties.h> 99 #include <android-base/stringprintf.h> 100 #include <private/android_logger.h> 101 102 #include "adb.h" 103 #include "adb_io.h" 104 #include "adb_trace.h" 105 #include "adb_unique_fd.h" 106 #include "adb_utils.h" 107 #include "security_log_tags.h" 108 109 namespace { 110 111 // Reads from |fd| until close or failure. 112 std::string ReadAll(int fd) { 113 char buffer[512]; 114 std::string received; 115 116 while (1) { 117 int bytes = adb_read(fd, buffer, sizeof(buffer)); 118 if (bytes <= 0) { 119 break; 120 } 121 received.append(buffer, bytes); 122 } 123 124 return received; 125 } 126 127 // Creates a socketpair and saves the endpoints to |fd1| and |fd2|. 128 bool CreateSocketpair(unique_fd* fd1, unique_fd* fd2) { 129 int sockets[2]; 130 if (adb_socketpair(sockets) < 0) { 131 PLOG(ERROR) << "cannot create socket pair"; 132 return false; 133 } 134 fd1->reset(sockets[0]); 135 fd2->reset(sockets[1]); 136 return true; 137 } 138 139 class Subprocess { 140 public: 141 Subprocess(const std::string& command, const char* terminal_type, 142 SubprocessType type, SubprocessProtocol protocol); 143 ~Subprocess(); 144 145 const std::string& command() const { return command_; } 146 147 int ReleaseLocalSocket() { return local_socket_sfd_.release(); } 148 149 pid_t pid() const { return pid_; } 150 151 // Sets up FDs, forks a subprocess, starts the subprocess manager thread, 152 // and exec's the child. Returns false and sets error on failure. 153 bool ForkAndExec(std::string* _Nonnull error); 154 155 // Start the subprocess manager thread. Consumes the subprocess, regardless of success. 156 // Returns false and sets error on failure. 157 static bool StartThread(std::unique_ptr<Subprocess> subprocess, 158 std::string* _Nonnull error); 159 160 private: 161 // Opens the file at |pts_name|. 162 int OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd); 163 164 static void ThreadHandler(void* userdata); 165 void PassDataStreams(); 166 void WaitForExit(); 167 168 unique_fd* SelectLoop(fd_set* master_read_set_ptr, 169 fd_set* master_write_set_ptr); 170 171 // Input/output stream handlers. Success returns nullptr, failure returns 172 // a pointer to the failed FD. 173 unique_fd* PassInput(); 174 unique_fd* PassOutput(unique_fd* sfd, ShellProtocol::Id id); 175 176 const std::string command_; 177 const std::string terminal_type_; 178 bool make_pty_raw_ = false; 179 SubprocessType type_; 180 SubprocessProtocol protocol_; 181 pid_t pid_ = -1; 182 unique_fd local_socket_sfd_; 183 184 // Shell protocol variables. 185 unique_fd stdinout_sfd_, stderr_sfd_, protocol_sfd_; 186 std::unique_ptr<ShellProtocol> input_, output_; 187 size_t input_bytes_left_ = 0; 188 189 DISALLOW_COPY_AND_ASSIGN(Subprocess); 190 }; 191 192 Subprocess::Subprocess(const std::string& command, const char* terminal_type, 193 SubprocessType type, SubprocessProtocol protocol) 194 : command_(command), 195 terminal_type_(terminal_type ? terminal_type : ""), 196 type_(type), 197 protocol_(protocol) { 198 // If we aren't using the shell protocol we must allocate a PTY to properly close the 199 // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side 200 // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write, 201 // e.g. screenrecord, will never notice the broken pipe and terminate. 202 // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD 203 // with select() and will send SIGHUP manually to the child process. 204 if (protocol_ == SubprocessProtocol::kNone && type_ == SubprocessType::kRaw) { 205 // Disable PTY input/output processing since the client is expecting raw data. 206 D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead"); 207 type_ = SubprocessType::kPty; 208 make_pty_raw_ = true; 209 } 210 } 211 212 Subprocess::~Subprocess() { 213 WaitForExit(); 214 } 215 216 static std::string GetHostName() { 217 char buf[HOST_NAME_MAX]; 218 if (gethostname(buf, sizeof(buf)) != -1 && strcmp(buf, "localhost") != 0) return buf; 219 220 return android::base::GetProperty("ro.product.device", "android"); 221 } 222 223 bool Subprocess::ForkAndExec(std::string* error) { 224 unique_fd child_stdinout_sfd, child_stderr_sfd; 225 unique_fd parent_error_sfd, child_error_sfd; 226 char pts_name[PATH_MAX]; 227 228 if (command_.empty()) { 229 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_INTERACTIVE, ""); 230 } else { 231 __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str()); 232 } 233 234 // Create a socketpair for the fork() child to report any errors back to the parent. Since we 235 // use threads, logging directly from the child might deadlock due to locks held in another 236 // thread during the fork. 237 if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) { 238 *error = android::base::StringPrintf( 239 "failed to create pipe for subprocess error reporting: %s", strerror(errno)); 240 return false; 241 } 242 243 // Construct the environment for the child before we fork. 244 passwd* pw = getpwuid(getuid()); 245 std::unordered_map<std::string, std::string> env; 246 if (environ) { 247 char** current = environ; 248 while (char* env_cstr = *current++) { 249 std::string env_string = env_cstr; 250 char* delimiter = strchr(&env_string[0], '='); 251 252 // Drop any values that don't contain '='. 253 if (delimiter) { 254 *delimiter++ = '\0'; 255 env[env_string.c_str()] = delimiter; 256 } 257 } 258 } 259 260 if (pw != nullptr) { 261 env["HOME"] = pw->pw_dir; 262 env["HOSTNAME"] = GetHostName(); 263 env["LOGNAME"] = pw->pw_name; 264 env["SHELL"] = pw->pw_shell; 265 env["TMPDIR"] = "/data/local/tmp"; 266 env["USER"] = pw->pw_name; 267 } 268 269 if (!terminal_type_.empty()) { 270 env["TERM"] = terminal_type_; 271 } 272 273 std::vector<std::string> joined_env; 274 for (auto it : env) { 275 const char* key = it.first.c_str(); 276 const char* value = it.second.c_str(); 277 joined_env.push_back(android::base::StringPrintf("%s=%s", key, value)); 278 } 279 280 std::vector<const char*> cenv; 281 for (const std::string& str : joined_env) { 282 cenv.push_back(str.c_str()); 283 } 284 cenv.push_back(nullptr); 285 286 if (type_ == SubprocessType::kPty) { 287 int fd; 288 pid_ = forkpty(&fd, pts_name, nullptr, nullptr); 289 if (pid_ > 0) { 290 stdinout_sfd_.reset(fd); 291 } 292 } else { 293 if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) { 294 *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s", 295 strerror(errno)); 296 return false; 297 } 298 // Raw subprocess + shell protocol allows for splitting stderr. 299 if (protocol_ == SubprocessProtocol::kShell && 300 !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) { 301 *error = android::base::StringPrintf("failed to create socketpair for stderr: %s", 302 strerror(errno)); 303 return false; 304 } 305 pid_ = fork(); 306 } 307 308 if (pid_ == -1) { 309 *error = android::base::StringPrintf("fork failed: %s", strerror(errno)); 310 return false; 311 } 312 313 if (pid_ == 0) { 314 // Subprocess child. 315 setsid(); 316 317 if (type_ == SubprocessType::kPty) { 318 child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd)); 319 } 320 321 dup2(child_stdinout_sfd, STDIN_FILENO); 322 dup2(child_stdinout_sfd, STDOUT_FILENO); 323 dup2(child_stderr_sfd != -1 ? child_stderr_sfd : child_stdinout_sfd, STDERR_FILENO); 324 325 // exec doesn't trigger destructors, close the FDs manually. 326 stdinout_sfd_.reset(-1); 327 stderr_sfd_.reset(-1); 328 child_stdinout_sfd.reset(-1); 329 child_stderr_sfd.reset(-1); 330 parent_error_sfd.reset(-1); 331 close_on_exec(child_error_sfd); 332 333 // adbd sets SIGPIPE to SIG_IGN to get EPIPE instead, and Linux propagates that to child 334 // processes, so we need to manually reset back to SIG_DFL here (http://b/35209888). 335 signal(SIGPIPE, SIG_DFL); 336 337 // Increase oom_score_adj from -1000, so that the child is visible to the OOM-killer. 338 // Don't treat failure as an error, because old Android kernels explicitly disabled this. 339 int oom_score_adj_fd = adb_open("/proc/self/oom_score_adj", O_WRONLY | O_CLOEXEC); 340 if (oom_score_adj_fd != -1) { 341 const char* oom_score_adj_value = "-950"; 342 TEMP_FAILURE_RETRY( 343 adb_write(oom_score_adj_fd, oom_score_adj_value, strlen(oom_score_adj_value))); 344 } 345 346 if (command_.empty()) { 347 execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data()); 348 } else { 349 execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data()); 350 } 351 WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: "); 352 WriteFdExactly(child_error_sfd, strerror(errno)); 353 child_error_sfd.reset(-1); 354 _Exit(1); 355 } 356 357 // Subprocess parent. 358 D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d", 359 stdinout_sfd_.get(), stderr_sfd_.get()); 360 361 // Wait to make sure the subprocess exec'd without error. 362 child_error_sfd.reset(-1); 363 std::string error_message = ReadAll(parent_error_sfd); 364 if (!error_message.empty()) { 365 *error = error_message; 366 return false; 367 } 368 369 D("subprocess parent: exec completed"); 370 if (protocol_ == SubprocessProtocol::kNone) { 371 // No protocol: all streams pass through the stdinout FD and hook 372 // directly into the local socket for raw data transfer. 373 local_socket_sfd_.reset(stdinout_sfd_.release()); 374 } else { 375 // Shell protocol: create another socketpair to intercept data. 376 if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) { 377 *error = android::base::StringPrintf( 378 "failed to create socketpair to intercept data: %s", strerror(errno)); 379 kill(pid_, SIGKILL); 380 return false; 381 } 382 D("protocol FD = %d", protocol_sfd_.get()); 383 384 input_ = std::make_unique<ShellProtocol>(protocol_sfd_); 385 output_ = std::make_unique<ShellProtocol>(protocol_sfd_); 386 if (!input_ || !output_) { 387 *error = "failed to allocate shell protocol objects"; 388 kill(pid_, SIGKILL); 389 return false; 390 } 391 392 // Don't let reads/writes to the subprocess block our thread. This isn't 393 // likely but could happen under unusual circumstances, such as if we 394 // write a ton of data to stdin but the subprocess never reads it and 395 // the pipe fills up. 396 for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) { 397 if (fd >= 0) { 398 if (!set_file_block_mode(fd, false)) { 399 *error = android::base::StringPrintf( 400 "failed to set non-blocking mode for fd %d", fd); 401 kill(pid_, SIGKILL); 402 return false; 403 } 404 } 405 } 406 } 407 408 D("subprocess parent: completed"); 409 return true; 410 } 411 412 bool Subprocess::StartThread(std::unique_ptr<Subprocess> subprocess, std::string* error) { 413 Subprocess* raw = subprocess.release(); 414 std::thread(ThreadHandler, raw).detach(); 415 416 return true; 417 } 418 419 int Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) { 420 int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC); 421 if (child_fd == -1) { 422 // Don't use WriteFdFmt; since we're in the fork() child we don't want 423 // to allocate any heap memory to avoid race conditions. 424 const char* messages[] = {"child failed to open pseudo-term slave ", 425 pts_name, ": ", strerror(errno)}; 426 for (const char* message : messages) { 427 WriteFdExactly(*error_sfd, message); 428 } 429 abort(); 430 } 431 432 if (make_pty_raw_) { 433 termios tattr; 434 if (tcgetattr(child_fd, &tattr) == -1) { 435 int saved_errno = errno; 436 WriteFdExactly(*error_sfd, "tcgetattr failed: "); 437 WriteFdExactly(*error_sfd, strerror(saved_errno)); 438 abort(); 439 } 440 441 cfmakeraw(&tattr); 442 if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) { 443 int saved_errno = errno; 444 WriteFdExactly(*error_sfd, "tcsetattr failed: "); 445 WriteFdExactly(*error_sfd, strerror(saved_errno)); 446 abort(); 447 } 448 } 449 450 return child_fd; 451 } 452 453 void Subprocess::ThreadHandler(void* userdata) { 454 Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata); 455 456 adb_thread_setname(android::base::StringPrintf("shell svc %d", subprocess->pid())); 457 458 D("passing data streams for PID %d", subprocess->pid()); 459 subprocess->PassDataStreams(); 460 461 D("deleting Subprocess for PID %d", subprocess->pid()); 462 delete subprocess; 463 } 464 465 void Subprocess::PassDataStreams() { 466 if (protocol_sfd_ == -1) { 467 return; 468 } 469 470 // Start by trying to read from the protocol FD, stdout, and stderr. 471 fd_set master_read_set, master_write_set; 472 FD_ZERO(&master_read_set); 473 FD_ZERO(&master_write_set); 474 for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) { 475 if (*sfd != -1) { 476 FD_SET(*sfd, &master_read_set); 477 } 478 } 479 480 // Pass data until the protocol FD or both the subprocess pipes die, at 481 // which point we can't pass any more data. 482 while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) { 483 unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set); 484 if (dead_sfd) { 485 D("closing FD %d", dead_sfd->get()); 486 FD_CLR(*dead_sfd, &master_read_set); 487 FD_CLR(*dead_sfd, &master_write_set); 488 if (dead_sfd == &protocol_sfd_) { 489 // Using SIGHUP is a decent general way to indicate that the 490 // controlling process is going away. If specific signals are 491 // needed (e.g. SIGINT), pass those through the shell protocol 492 // and only fall back on this for unexpected closures. 493 D("protocol FD died, sending SIGHUP to pid %d", pid_); 494 kill(pid_, SIGHUP); 495 496 // We also need to close the pipes connected to the child process 497 // so that if it ignores SIGHUP and continues to write data it 498 // won't fill up the pipe and block. 499 stdinout_sfd_.reset(); 500 stderr_sfd_.reset(); 501 } 502 dead_sfd->reset(); 503 } 504 } 505 } 506 507 namespace { 508 509 inline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) { 510 return sfd != -1 && FD_ISSET(sfd, set); 511 } 512 513 } // namespace 514 515 unique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr, 516 fd_set* master_write_set_ptr) { 517 fd_set read_set, write_set; 518 int select_n = std::max(std::max(protocol_sfd_, stdinout_sfd_), stderr_sfd_) + 1; 519 unique_fd* dead_sfd = nullptr; 520 521 // Keep calling select() and passing data until an FD closes/errors. 522 while (!dead_sfd) { 523 memcpy(&read_set, master_read_set_ptr, sizeof(read_set)); 524 memcpy(&write_set, master_write_set_ptr, sizeof(write_set)); 525 if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) { 526 if (errno == EINTR) { 527 continue; 528 } else { 529 PLOG(ERROR) << "select failed, closing subprocess pipes"; 530 stdinout_sfd_.reset(-1); 531 stderr_sfd_.reset(-1); 532 return nullptr; 533 } 534 } 535 536 // Read stdout, write to protocol FD. 537 if (ValidAndInSet(stdinout_sfd_, &read_set)) { 538 dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout); 539 } 540 541 // Read stderr, write to protocol FD. 542 if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) { 543 dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr); 544 } 545 546 // Read protocol FD, write to stdin. 547 if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) { 548 dead_sfd = PassInput(); 549 // If we didn't finish writing, block on stdin write. 550 if (input_bytes_left_) { 551 FD_CLR(protocol_sfd_, master_read_set_ptr); 552 FD_SET(stdinout_sfd_, master_write_set_ptr); 553 } 554 } 555 556 // Continue writing to stdin; only happens if a previous write blocked. 557 if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) { 558 dead_sfd = PassInput(); 559 // If we finished writing, go back to blocking on protocol read. 560 if (!input_bytes_left_) { 561 FD_SET(protocol_sfd_, master_read_set_ptr); 562 FD_CLR(stdinout_sfd_, master_write_set_ptr); 563 } 564 } 565 } // while (!dead_sfd) 566 567 return dead_sfd; 568 } 569 570 unique_fd* Subprocess::PassInput() { 571 // Only read a new packet if we've finished writing the last one. 572 if (!input_bytes_left_) { 573 if (!input_->Read()) { 574 // Read() uses ReadFdExactly() which sets errno to 0 on EOF. 575 if (errno != 0) { 576 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_; 577 } 578 return &protocol_sfd_; 579 } 580 581 if (stdinout_sfd_ != -1) { 582 switch (input_->id()) { 583 case ShellProtocol::kIdWindowSizeChange: 584 int rows, cols, x_pixels, y_pixels; 585 if (sscanf(input_->data(), "%dx%d,%dx%d", 586 &rows, &cols, &x_pixels, &y_pixels) == 4) { 587 winsize ws; 588 ws.ws_row = rows; 589 ws.ws_col = cols; 590 ws.ws_xpixel = x_pixels; 591 ws.ws_ypixel = y_pixels; 592 ioctl(stdinout_sfd_, TIOCSWINSZ, &ws); 593 } 594 break; 595 case ShellProtocol::kIdStdin: 596 input_bytes_left_ = input_->data_length(); 597 break; 598 case ShellProtocol::kIdCloseStdin: 599 if (type_ == SubprocessType::kRaw) { 600 if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) { 601 return nullptr; 602 } 603 PLOG(ERROR) << "failed to shutdown writes to FD " 604 << stdinout_sfd_; 605 return &stdinout_sfd_; 606 } else { 607 // PTYs can't close just input, so rather than close the 608 // FD and risk losing subprocess output, leave it open. 609 // This only happens if the client starts a PTY shell 610 // non-interactively which is rare and unsupported. 611 // If necessary, the client can manually close the shell 612 // with `exit` or by killing the adb client process. 613 D("can't close input for PTY FD %d", stdinout_sfd_.get()); 614 } 615 break; 616 } 617 } 618 } 619 620 if (input_bytes_left_ > 0) { 621 int index = input_->data_length() - input_bytes_left_; 622 int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_); 623 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) { 624 if (bytes < 0) { 625 PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_; 626 } 627 // stdin is done, mark this packet as finished and we'll just start 628 // dumping any further data received from the protocol FD. 629 input_bytes_left_ = 0; 630 return &stdinout_sfd_; 631 } else if (bytes > 0) { 632 input_bytes_left_ -= bytes; 633 } 634 } 635 636 return nullptr; 637 } 638 639 unique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) { 640 int bytes = adb_read(*sfd, output_->data(), output_->data_capacity()); 641 if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) { 642 // read() returns EIO if a PTY closes; don't report this as an error, 643 // it just means the subprocess completed. 644 if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) { 645 PLOG(ERROR) << "error reading output FD " << *sfd; 646 } 647 return sfd; 648 } 649 650 if (bytes > 0 && !output_->Write(id, bytes)) { 651 if (errno != 0) { 652 PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_; 653 } 654 return &protocol_sfd_; 655 } 656 657 return nullptr; 658 } 659 660 void Subprocess::WaitForExit() { 661 int exit_code = 1; 662 663 D("waiting for pid %d", pid_); 664 while (true) { 665 int status; 666 if (pid_ == waitpid(pid_, &status, 0)) { 667 D("post waitpid (pid=%d) status=%04x", pid_, status); 668 if (WIFSIGNALED(status)) { 669 exit_code = 0x80 | WTERMSIG(status); 670 D("subprocess killed by signal %d", WTERMSIG(status)); 671 break; 672 } else if (!WIFEXITED(status)) { 673 D("subprocess didn't exit"); 674 break; 675 } else if (WEXITSTATUS(status) >= 0) { 676 exit_code = WEXITSTATUS(status); 677 D("subprocess exit code = %d", WEXITSTATUS(status)); 678 break; 679 } 680 } 681 } 682 683 // If we have an open protocol FD send an exit packet. 684 if (protocol_sfd_ != -1) { 685 output_->data()[0] = exit_code; 686 if (output_->Write(ShellProtocol::kIdExit, 1)) { 687 D("wrote the exit code packet: %d", exit_code); 688 } else { 689 PLOG(ERROR) << "failed to write the exit code packet"; 690 } 691 protocol_sfd_.reset(-1); 692 } 693 } 694 695 } // namespace 696 697 // Create a pipe containing the error. 698 static int ReportError(SubprocessProtocol protocol, const std::string& message) { 699 int pipefd[2]; 700 if (pipe(pipefd) != 0) { 701 LOG(ERROR) << "failed to create pipe to report error"; 702 return -1; 703 } 704 705 std::string buf = android::base::StringPrintf("error: %s\n", message.c_str()); 706 if (protocol == SubprocessProtocol::kShell) { 707 ShellProtocol::Id id = ShellProtocol::kIdStderr; 708 uint32_t length = buf.length(); 709 WriteFdExactly(pipefd[1], &id, sizeof(id)); 710 WriteFdExactly(pipefd[1], &length, sizeof(length)); 711 } 712 713 WriteFdExactly(pipefd[1], buf.data(), buf.length()); 714 715 if (protocol == SubprocessProtocol::kShell) { 716 ShellProtocol::Id id = ShellProtocol::kIdExit; 717 uint32_t length = 1; 718 char exit_code = 126; 719 WriteFdExactly(pipefd[1], &id, sizeof(id)); 720 WriteFdExactly(pipefd[1], &length, sizeof(length)); 721 WriteFdExactly(pipefd[1], &exit_code, sizeof(exit_code)); 722 } 723 724 adb_close(pipefd[1]); 725 return pipefd[0]; 726 } 727 728 int StartSubprocess(const char* name, const char* terminal_type, 729 SubprocessType type, SubprocessProtocol protocol) { 730 D("starting %s subprocess (protocol=%s, TERM=%s): '%s'", 731 type == SubprocessType::kRaw ? "raw" : "PTY", 732 protocol == SubprocessProtocol::kNone ? "none" : "shell", 733 terminal_type, name); 734 735 auto subprocess = std::make_unique<Subprocess>(name, terminal_type, type, protocol); 736 if (!subprocess) { 737 LOG(ERROR) << "failed to allocate new subprocess"; 738 return ReportError(protocol, "failed to allocate new subprocess"); 739 } 740 741 std::string error; 742 if (!subprocess->ForkAndExec(&error)) { 743 LOG(ERROR) << "failed to start subprocess: " << error; 744 return ReportError(protocol, error); 745 } 746 747 unique_fd local_socket(subprocess->ReleaseLocalSocket()); 748 D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(), 749 subprocess->pid()); 750 751 if (!Subprocess::StartThread(std::move(subprocess), &error)) { 752 LOG(ERROR) << "failed to start subprocess management thread: " << error; 753 return ReportError(protocol, error); 754 } 755 756 return local_socket.release(); 757 } 758