180f67029e002a97dd4f752881d820b3161f729f1David Pursell/*
280f67029e002a97dd4f752881d820b3161f729f1David Pursell * Copyright (C) 2015 The Android Open Source Project
380f67029e002a97dd4f752881d820b3161f729f1David Pursell *
480f67029e002a97dd4f752881d820b3161f729f1David Pursell * Licensed under the Apache License, Version 2.0 (the "License");
580f67029e002a97dd4f752881d820b3161f729f1David Pursell * you may not use this file except in compliance with the License.
680f67029e002a97dd4f752881d820b3161f729f1David Pursell * You may obtain a copy of the License at
780f67029e002a97dd4f752881d820b3161f729f1David Pursell *
880f67029e002a97dd4f752881d820b3161f729f1David Pursell *      http://www.apache.org/licenses/LICENSE-2.0
980f67029e002a97dd4f752881d820b3161f729f1David Pursell *
1080f67029e002a97dd4f752881d820b3161f729f1David Pursell * Unless required by applicable law or agreed to in writing, software
1180f67029e002a97dd4f752881d820b3161f729f1David Pursell * distributed under the License is distributed on an "AS IS" BASIS,
1280f67029e002a97dd4f752881d820b3161f729f1David Pursell * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1380f67029e002a97dd4f752881d820b3161f729f1David Pursell * See the License for the specific language governing permissions and
1480f67029e002a97dd4f752881d820b3161f729f1David Pursell * limitations under the License.
1580f67029e002a97dd4f752881d820b3161f729f1David Pursell */
1680f67029e002a97dd4f752881d820b3161f729f1David Pursell
170955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// Functionality for launching and managing shell subprocesses.
180955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//
190955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// There are two types of subprocesses, PTY or raw. PTY is typically used for
200955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// an interactive session, raw for non-interactive. There are also two methods
210955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// of communication with the subprocess, passing raw data or using a simple
220955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// protocol to wrap packets. The protocol allows separating stdout/stderr and
230955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// passing the exit code back, but is not backwards compatible.
240955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   ----------------+--------------------------------------
250955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   Type  Protocol  |   Exit code?  Separate stdout/stderr?
260955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   ----------------+--------------------------------------
270955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   PTY   No        |   No          No
280955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   Raw   No        |   No          No
290955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   PTY   Yes       |   Yes         No
300955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   Raw   Yes       |   Yes         Yes
310955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   ----------------+--------------------------------------
320955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//
330955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// Non-protocol subprocesses work by passing subprocess stdin/out/err through
340955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// a single pipe which is registered with a local socket in adbd. The local
350955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// socket uses the fdevent loop to pass raw data between this pipe and the
360955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// transport, which then passes data back to the adb client. Cleanup is done by
370955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// waiting in a separate thread for the subprocesses to exit and then signaling
380955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// a separate fdevent to close out the local socket from the main loop.
390955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//
400955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// ------------------+-------------------------+------------------------------
410955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   Subprocess      |  adbd subprocess thread |   adbd main fdevent loop
420955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// ------------------+-------------------------+------------------------------
430955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//                   |                         |
440955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   stdin/out/err <----------------------------->       LocalSocket
450955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//      |            |                         |
460955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//      |            |      Block on exit      |
470955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//      |            |           *             |
480955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//      v            |           *             |
490955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//     Exit         --->      Unblock          |
500955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//                   |           |             |
510955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//                   |           v             |
520955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//                   |   Notify shell exit FD --->    Close LocalSocket
530955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// ------------------+-------------------------+------------------------------
540955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//
550955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// The protocol requires the thread to intercept stdin/out/err in order to
560955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// wrap/unwrap data with shell protocol packets.
570955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//
580955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// ------------------+-------------------------+------------------------------
590955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//   Subprocess      |  adbd subprocess thread |   adbd main fdevent loop
600955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// ------------------+-------------------------+------------------------------
610955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//                   |                         |
620955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//     stdin/out   <--->      Protocol       <--->       LocalSocket
630955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//     stderr       --->      Protocol        --->       LocalSocket
640955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//       |           |                         |
650955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//       v           |                         |
660955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//      Exit        --->  Exit code protocol  --->       LocalSocket
670955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//                   |           |             |
680955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//                   |           v             |
690955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//                   |   Notify shell exit FD --->    Close LocalSocket
700955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// ------------------+-------------------------+------------------------------
710955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell//
720955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// An alternate approach is to put the protocol wrapping/unwrapping in the main
730955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// fdevent loop, which has the advantage of being able to re-use the existing
740955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// select() code for handling data streams. However, implementation turned out
750955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// to be more complex due to partial reads and non-blocking I/O so this model
760955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell// was chosen instead.
770955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
78aed3c61c4437ebb05eadfb3bf85d6962c30b9935Yabin Cui#define TRACE_TAG SHELL
7980f67029e002a97dd4f752881d820b3161f729f1David Pursell
806dfef255b8fa77e3b5c0a69b7f276ea8e25e22cdYabin Cui#include "sysdeps.h"
8180f67029e002a97dd4f752881d820b3161f729f1David Pursell
826dfef255b8fa77e3b5c0a69b7f276ea8e25e22cdYabin Cui#include "shell_service.h"
8380f67029e002a97dd4f752881d820b3161f729f1David Pursell
84a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell#include <errno.h>
856debf985aa5127b43f1f79a010dc000f733793b8Mark Salyzyn#include <paths.h>
8680f67029e002a97dd4f752881d820b3161f729f1David Pursell#include <pty.h>
87fbe4332e373208637dd928edf06a0da6cba92febElliott Hughes#include <pwd.h>
880955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell#include <sys/select.h>
8980f67029e002a97dd4f752881d820b3161f729f1David Pursell#include <termios.h>
9080f67029e002a97dd4f752881d820b3161f729f1David Pursell
910955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell#include <memory>
929b3fd6721392b16dee00caeca9586070496471e1Josh Gao#include <string>
939b3fd6721392b16dee00caeca9586070496471e1Josh Gao#include <unordered_map>
949b3fd6721392b16dee00caeca9586070496471e1Josh Gao#include <vector>
950955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
964f71319df011d796a60a43fc1bc68e16fbf7d321Elliott Hughes#include <android-base/logging.h>
974f71319df011d796a60a43fc1bc68e16fbf7d321Elliott Hughes#include <android-base/stringprintf.h>
986debf985aa5127b43f1f79a010dc000f733793b8Mark Salyzyn#include <private/android_logger.h>
9980f67029e002a97dd4f752881d820b3161f729f1David Pursell
10080f67029e002a97dd4f752881d820b3161f729f1David Pursell#include "adb.h"
10180f67029e002a97dd4f752881d820b3161f729f1David Pursell#include "adb_io.h"
10280f67029e002a97dd4f752881d820b3161f729f1David Pursell#include "adb_trace.h"
103924d35a8d5f82e2d2f7e4dcedaa60791306b5fb5Josh Gao#include "adb_unique_fd.h"
1046dfef255b8fa77e3b5c0a69b7f276ea8e25e22cdYabin Cui#include "adb_utils.h"
105d61a25c17204b74b81558cb5d67c347f1e87fef1Rubin Xu#include "security_log_tags.h"
10680f67029e002a97dd4f752881d820b3161f729f1David Pursell
10780f67029e002a97dd4f752881d820b3161f729f1David Pursellnamespace {
10880f67029e002a97dd4f752881d820b3161f729f1David Pursell
109a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell// Reads from |fd| until close or failure.
110a932058504ee20d28f1a5b3c17c377543e4eb281David Pursellstd::string ReadAll(int fd) {
111a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    char buffer[512];
112a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    std::string received;
11380f67029e002a97dd4f752881d820b3161f729f1David Pursell
114a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    while (1) {
115a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        int bytes = adb_read(fd, buffer, sizeof(buffer));
116a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        if (bytes <= 0) {
117a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell            break;
11880f67029e002a97dd4f752881d820b3161f729f1David Pursell        }
119a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        received.append(buffer, bytes);
120a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    }
12180f67029e002a97dd4f752881d820b3161f729f1David Pursell
122a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    return received;
123a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell}
12480f67029e002a97dd4f752881d820b3161f729f1David Pursell
125a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell// Creates a socketpair and saves the endpoints to |fd1| and |fd2|.
1262ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughesbool CreateSocketpair(unique_fd* fd1, unique_fd* fd2) {
127a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    int sockets[2];
128a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (adb_socketpair(sockets) < 0) {
129a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        PLOG(ERROR) << "cannot create socket pair";
130a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        return false;
13180f67029e002a97dd4f752881d820b3161f729f1David Pursell    }
1322ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    fd1->reset(sockets[0]);
1332ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    fd2->reset(sockets[1]);
134a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    return true;
13580f67029e002a97dd4f752881d820b3161f729f1David Pursell}
13680f67029e002a97dd4f752881d820b3161f729f1David Pursell
137a932058504ee20d28f1a5b3c17c377543e4eb281David Pursellclass Subprocess {
138a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell  public:
13918ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes    Subprocess(const std::string& command, const char* terminal_type,
14018ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes               SubprocessType type, SubprocessProtocol protocol);
141a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    ~Subprocess();
14280f67029e002a97dd4f752881d820b3161f729f1David Pursell
143a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    const std::string& command() const { return command_; }
144a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
145cd5d7376dceb14b5bb5d84540192b63b3c86b4d3Josh Gao    int ReleaseLocalSocket() { return local_socket_sfd_.release(); }
146a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
147a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    pid_t pid() const { return pid_; }
148a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
149a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    // Sets up FDs, forks a subprocess, starts the subprocess manager thread,
150344778da411ebb47966961f3a70ca0848425194fJosh Gao    // and exec's the child. Returns false and sets error on failure.
1514323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    bool ForkAndExec(std::string* _Nonnull error);
152a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
153344778da411ebb47966961f3a70ca0848425194fJosh Gao    // Start the subprocess manager thread. Consumes the subprocess, regardless of success.
154344778da411ebb47966961f3a70ca0848425194fJosh Gao    // Returns false and sets error on failure.
155344778da411ebb47966961f3a70ca0848425194fJosh Gao    static bool StartThread(std::unique_ptr<Subprocess> subprocess,
156344778da411ebb47966961f3a70ca0848425194fJosh Gao                            std::string* _Nonnull error);
157344778da411ebb47966961f3a70ca0848425194fJosh Gao
158a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell  private:
159a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    // Opens the file at |pts_name|.
1602ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    int OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd);
161a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
162b5fea14e13bb6e41b36f374c954dc55faeef4627Josh Gao    static void ThreadHandler(void* userdata);
1630955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    void PassDataStreams();
164a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    void WaitForExit();
165a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
1662ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    unique_fd* SelectLoop(fd_set* master_read_set_ptr,
1672ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                          fd_set* master_write_set_ptr);
1680955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
1690955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // Input/output stream handlers. Success returns nullptr, failure returns
1700955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // a pointer to the failed FD.
1712ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    unique_fd* PassInput();
1722ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    unique_fd* PassOutput(unique_fd* sfd, ShellProtocol::Id id);
1730955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
174a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    const std::string command_;
17518ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes    const std::string terminal_type_;
17657dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    bool make_pty_raw_ = false;
177a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    SubprocessType type_;
1780955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    SubprocessProtocol protocol_;
179a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    pid_t pid_ = -1;
1802ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    unique_fd local_socket_sfd_;
181a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
1820955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // Shell protocol variables.
1832ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    unique_fd stdinout_sfd_, stderr_sfd_, protocol_sfd_;
1840955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    std::unique_ptr<ShellProtocol> input_, output_;
1850955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    size_t input_bytes_left_ = 0;
1860955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
187a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    DISALLOW_COPY_AND_ASSIGN(Subprocess);
188a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell};
189a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
19018ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott HughesSubprocess::Subprocess(const std::string& command, const char* terminal_type,
19118ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes                       SubprocessType type, SubprocessProtocol protocol)
19218ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes    : command_(command),
19318ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes      terminal_type_(terminal_type ? terminal_type : ""),
19418ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes      type_(type),
19518ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes      protocol_(protocol) {
19657dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    // If we aren't using the shell protocol we must allocate a PTY to properly close the
19757dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    // subprocess. PTYs automatically send SIGHUP to the slave-side process when the master side
19857dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    // of the PTY closes, which we rely on. If we use a raw pipe, processes that don't read/write,
19957dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    // e.g. screenrecord, will never notice the broken pipe and terminate.
20057dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    // The shell protocol doesn't require a PTY because it's always monitoring the local socket FD
20157dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    // with select() and will send SIGHUP manually to the child process.
20257dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    if (protocol_ == SubprocessProtocol::kNone && type_ == SubprocessType::kRaw) {
20357dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        // Disable PTY input/output processing since the client is expecting raw data.
20457dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        D("Can't create raw subprocess without shell protocol, using PTY in raw mode instead");
20557dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        type_ = SubprocessType::kPty;
20657dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        make_pty_raw_ = true;
20757dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    }
208a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell}
209a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
210a932058504ee20d28f1a5b3c17c377543e4eb281David PursellSubprocess::~Subprocess() {
211c65fae9ef56163d17bcc86b6b6324be2b56b4aa5Josh Gao    WaitForExit();
212a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell}
213a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
2144323507a7eecb2384a872086ab933948bd8cbe80Josh Gaobool Subprocess::ForkAndExec(std::string* error) {
2152ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    unique_fd child_stdinout_sfd, child_stderr_sfd;
2162ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    unique_fd parent_error_sfd, child_error_sfd;
217a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    char pts_name[PATH_MAX];
218a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
219d61a25c17204b74b81558cb5d67c347f1e87fef1Rubin Xu    if (command_.empty()) {
220d61a25c17204b74b81558cb5d67c347f1e87fef1Rubin Xu        __android_log_security_bswrite(SEC_TAG_ADB_SHELL_INTERACTIVE, "");
221d61a25c17204b74b81558cb5d67c347f1e87fef1Rubin Xu    } else {
222d61a25c17204b74b81558cb5d67c347f1e87fef1Rubin Xu        __android_log_security_bswrite(SEC_TAG_ADB_SHELL_CMD, command_.c_str());
223d61a25c17204b74b81558cb5d67c347f1e87fef1Rubin Xu    }
224d61a25c17204b74b81558cb5d67c347f1e87fef1Rubin Xu
2259b3fd6721392b16dee00caeca9586070496471e1Josh Gao    // Create a socketpair for the fork() child to report any errors back to the parent. Since we
2269b3fd6721392b16dee00caeca9586070496471e1Josh Gao    // use threads, logging directly from the child might deadlock due to locks held in another
2279b3fd6721392b16dee00caeca9586070496471e1Josh Gao    // thread during the fork.
228a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (!CreateSocketpair(&parent_error_sfd, &child_error_sfd)) {
2294323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        *error = android::base::StringPrintf(
2304323507a7eecb2384a872086ab933948bd8cbe80Josh Gao            "failed to create pipe for subprocess error reporting: %s", strerror(errno));
2314323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        return false;
23280f67029e002a97dd4f752881d820b3161f729f1David Pursell    }
23380f67029e002a97dd4f752881d820b3161f729f1David Pursell
2349b3fd6721392b16dee00caeca9586070496471e1Josh Gao    // Construct the environment for the child before we fork.
2359b3fd6721392b16dee00caeca9586070496471e1Josh Gao    passwd* pw = getpwuid(getuid());
2369b3fd6721392b16dee00caeca9586070496471e1Josh Gao    std::unordered_map<std::string, std::string> env;
237e03c988748d860527248d4aca01bb7903d3799aaJosh Gao    if (environ) {
238e03c988748d860527248d4aca01bb7903d3799aaJosh Gao        char** current = environ;
239e03c988748d860527248d4aca01bb7903d3799aaJosh Gao        while (char* env_cstr = *current++) {
240e03c988748d860527248d4aca01bb7903d3799aaJosh Gao            std::string env_string = env_cstr;
24180fd4549e39aa5c14229d1b2f46fe3f98f148f51Dan Austin            char* delimiter = strchr(&env_string[0], '=');
242e03c988748d860527248d4aca01bb7903d3799aaJosh Gao
243e03c988748d860527248d4aca01bb7903d3799aaJosh Gao            // Drop any values that don't contain '='.
244e03c988748d860527248d4aca01bb7903d3799aaJosh Gao            if (delimiter) {
245e03c988748d860527248d4aca01bb7903d3799aaJosh Gao                *delimiter++ = '\0';
246e03c988748d860527248d4aca01bb7903d3799aaJosh Gao                env[env_string.c_str()] = delimiter;
247e03c988748d860527248d4aca01bb7903d3799aaJosh Gao            }
248e03c988748d860527248d4aca01bb7903d3799aaJosh Gao        }
2499b3fd6721392b16dee00caeca9586070496471e1Josh Gao    }
2509b3fd6721392b16dee00caeca9586070496471e1Josh Gao
2519b3fd6721392b16dee00caeca9586070496471e1Josh Gao    if (pw != nullptr) {
2529b3fd6721392b16dee00caeca9586070496471e1Josh Gao        // TODO: $HOSTNAME? Normally bash automatically sets that, but mksh doesn't.
2539b3fd6721392b16dee00caeca9586070496471e1Josh Gao        env["HOME"] = pw->pw_dir;
2549b3fd6721392b16dee00caeca9586070496471e1Josh Gao        env["LOGNAME"] = pw->pw_name;
2559b3fd6721392b16dee00caeca9586070496471e1Josh Gao        env["USER"] = pw->pw_name;
2569b3fd6721392b16dee00caeca9586070496471e1Josh Gao        env["SHELL"] = pw->pw_shell;
2579b3fd6721392b16dee00caeca9586070496471e1Josh Gao    }
2589b3fd6721392b16dee00caeca9586070496471e1Josh Gao
2599b3fd6721392b16dee00caeca9586070496471e1Josh Gao    if (!terminal_type_.empty()) {
2609b3fd6721392b16dee00caeca9586070496471e1Josh Gao        env["TERM"] = terminal_type_;
2619b3fd6721392b16dee00caeca9586070496471e1Josh Gao    }
2629b3fd6721392b16dee00caeca9586070496471e1Josh Gao
2639b3fd6721392b16dee00caeca9586070496471e1Josh Gao    std::vector<std::string> joined_env;
2649b3fd6721392b16dee00caeca9586070496471e1Josh Gao    for (auto it : env) {
2659b3fd6721392b16dee00caeca9586070496471e1Josh Gao        const char* key = it.first.c_str();
2669b3fd6721392b16dee00caeca9586070496471e1Josh Gao        const char* value = it.second.c_str();
2679b3fd6721392b16dee00caeca9586070496471e1Josh Gao        joined_env.push_back(android::base::StringPrintf("%s=%s", key, value));
2689b3fd6721392b16dee00caeca9586070496471e1Josh Gao    }
2699b3fd6721392b16dee00caeca9586070496471e1Josh Gao
2709b3fd6721392b16dee00caeca9586070496471e1Josh Gao    std::vector<const char*> cenv;
2719b3fd6721392b16dee00caeca9586070496471e1Josh Gao    for (const std::string& str : joined_env) {
2729b3fd6721392b16dee00caeca9586070496471e1Josh Gao        cenv.push_back(str.c_str());
2739b3fd6721392b16dee00caeca9586070496471e1Josh Gao    }
2749b3fd6721392b16dee00caeca9586070496471e1Josh Gao    cenv.push_back(nullptr);
2759b3fd6721392b16dee00caeca9586070496471e1Josh Gao
276a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (type_ == SubprocessType::kPty) {
277a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        int fd;
278a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        pid_ = forkpty(&fd, pts_name, nullptr, nullptr);
279fcb063ce378419ad1511d3395d44701b4ebaceb0Josh Gao        if (pid_ > 0) {
2802ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes          stdinout_sfd_.reset(fd);
281fcb063ce378419ad1511d3395d44701b4ebaceb0Josh Gao        }
282a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    } else {
2830955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (!CreateSocketpair(&stdinout_sfd_, &child_stdinout_sfd)) {
2844323507a7eecb2384a872086ab933948bd8cbe80Josh Gao            *error = android::base::StringPrintf("failed to create socketpair for stdin/out: %s",
2854323507a7eecb2384a872086ab933948bd8cbe80Josh Gao                                                 strerror(errno));
2860955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            return false;
2870955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
2880955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // Raw subprocess + shell protocol allows for splitting stderr.
2890955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (protocol_ == SubprocessProtocol::kShell &&
2900955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell                !CreateSocketpair(&stderr_sfd_, &child_stderr_sfd)) {
2914323507a7eecb2384a872086ab933948bd8cbe80Josh Gao            *error = android::base::StringPrintf("failed to create socketpair for stderr: %s",
2924323507a7eecb2384a872086ab933948bd8cbe80Josh Gao                                                 strerror(errno));
293a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell            return false;
294a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        }
295a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        pid_ = fork();
296a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    }
297a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
298a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (pid_ == -1) {
2994323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        *error = android::base::StringPrintf("fork failed: %s", strerror(errno));
300a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        return false;
30180f67029e002a97dd4f752881d820b3161f729f1David Pursell    }
30280f67029e002a97dd4f752881d820b3161f729f1David Pursell
303a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (pid_ == 0) {
304a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        // Subprocess child.
305284f07bd9d90386525abde6832e29c5539cd3c4dElliott Hughes        setsid();
30680f67029e002a97dd4f752881d820b3161f729f1David Pursell
307a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        if (type_ == SubprocessType::kPty) {
3082ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            child_stdinout_sfd.reset(OpenPtyChildFd(pts_name, &child_error_sfd));
309a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        }
310a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
3112ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        dup2(child_stdinout_sfd, STDIN_FILENO);
3122ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        dup2(child_stdinout_sfd, STDOUT_FILENO);
3132ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        dup2(child_stderr_sfd != -1 ? child_stderr_sfd : child_stdinout_sfd, STDERR_FILENO);
31480f67029e002a97dd4f752881d820b3161f729f1David Pursell
315a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        // exec doesn't trigger destructors, close the FDs manually.
3162ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        stdinout_sfd_.reset(-1);
3172ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        stderr_sfd_.reset(-1);
3182ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        child_stdinout_sfd.reset(-1);
3192ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        child_stderr_sfd.reset(-1);
3202ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        parent_error_sfd.reset(-1);
3212ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        close_on_exec(child_error_sfd);
32280f67029e002a97dd4f752881d820b3161f729f1David Pursell
3239eb551868bc9b8ab775767b620a017d3f93ca6c7Elliott Hughes        // adbd sets SIGPIPE to SIG_IGN to get EPIPE instead, and Linux propagates that to child
3249eb551868bc9b8ab775767b620a017d3f93ca6c7Elliott Hughes        // processes, so we need to manually reset back to SIG_DFL here (http://b/35209888).
3259eb551868bc9b8ab775767b620a017d3f93ca6c7Elliott Hughes        signal(SIGPIPE, SIG_DFL);
3269eb551868bc9b8ab775767b620a017d3f93ca6c7Elliott Hughes
327b5028e46b0d97c84144f660b5e47f7fd4a716fe5Josh Gao        if (command_.empty()) {
3289b3fd6721392b16dee00caeca9586070496471e1Josh Gao            execle(_PATH_BSHELL, _PATH_BSHELL, "-", nullptr, cenv.data());
329a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        } else {
3309b3fd6721392b16dee00caeca9586070496471e1Josh Gao            execle(_PATH_BSHELL, _PATH_BSHELL, "-c", command_.c_str(), nullptr, cenv.data());
331a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        }
3322ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        WriteFdExactly(child_error_sfd, "exec '" _PATH_BSHELL "' failed: ");
3332ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        WriteFdExactly(child_error_sfd, strerror(errno));
3342ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        child_error_sfd.reset(-1);
3359b3fd6721392b16dee00caeca9586070496471e1Josh Gao        _Exit(1);
33680f67029e002a97dd4f752881d820b3161f729f1David Pursell    }
337a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
338a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    // Subprocess parent.
3390955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    D("subprocess parent: stdin/stdout FD = %d, stderr FD = %d",
3402ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes      stdinout_sfd_.get(), stderr_sfd_.get());
341a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
342a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    // Wait to make sure the subprocess exec'd without error.
3432ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    child_error_sfd.reset(-1);
3442ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    std::string error_message = ReadAll(parent_error_sfd);
345a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (!error_message.empty()) {
3464323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        *error = error_message;
347a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        return false;
348a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    }
349a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
3509b3fd6721392b16dee00caeca9586070496471e1Josh Gao    D("subprocess parent: exec completed");
3510955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    if (protocol_ == SubprocessProtocol::kNone) {
3520955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // No protocol: all streams pass through the stdinout FD and hook
3530955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // directly into the local socket for raw data transfer.
3542ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        local_socket_sfd_.reset(stdinout_sfd_.release());
3550955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    } else {
3560955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // Shell protocol: create another socketpair to intercept data.
3570955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (!CreateSocketpair(&protocol_sfd_, &local_socket_sfd_)) {
3584323507a7eecb2384a872086ab933948bd8cbe80Josh Gao            *error = android::base::StringPrintf(
3594323507a7eecb2384a872086ab933948bd8cbe80Josh Gao                "failed to create socketpair to intercept data: %s", strerror(errno));
3604323507a7eecb2384a872086ab933948bd8cbe80Josh Gao            kill(pid_, SIGKILL);
3610955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            return false;
3620955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
3632ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        D("protocol FD = %d", protocol_sfd_.get());
3640955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
3652ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        input_.reset(new ShellProtocol(protocol_sfd_));
3662ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        output_.reset(new ShellProtocol(protocol_sfd_));
3670955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (!input_ || !output_) {
3684323507a7eecb2384a872086ab933948bd8cbe80Josh Gao            *error = "failed to allocate shell protocol objects";
3694323507a7eecb2384a872086ab933948bd8cbe80Josh Gao            kill(pid_, SIGKILL);
3700955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            return false;
3710955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
3720955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
3730955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // Don't let reads/writes to the subprocess block our thread. This isn't
3740955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // likely but could happen under unusual circumstances, such as if we
3750955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // write a ton of data to stdin but the subprocess never reads it and
3760955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // the pipe fills up.
3772ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        for (int fd : {stdinout_sfd_.get(), stderr_sfd_.get()}) {
3780955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            if (fd >= 0) {
3796dfef255b8fa77e3b5c0a69b7f276ea8e25e22cdYabin Cui                if (!set_file_block_mode(fd, false)) {
3804323507a7eecb2384a872086ab933948bd8cbe80Josh Gao                    *error = android::base::StringPrintf(
3814323507a7eecb2384a872086ab933948bd8cbe80Josh Gao                        "failed to set non-blocking mode for fd %d", fd);
3824323507a7eecb2384a872086ab933948bd8cbe80Josh Gao                    kill(pid_, SIGKILL);
3830955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell                    return false;
3840955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell                }
3850955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            }
3860955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
3870955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
388a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
389344778da411ebb47966961f3a70ca0848425194fJosh Gao    D("subprocess parent: completed");
390344778da411ebb47966961f3a70ca0848425194fJosh Gao    return true;
391344778da411ebb47966961f3a70ca0848425194fJosh Gao}
392344778da411ebb47966961f3a70ca0848425194fJosh Gao
393344778da411ebb47966961f3a70ca0848425194fJosh Gaobool Subprocess::StartThread(std::unique_ptr<Subprocess> subprocess, std::string* error) {
394344778da411ebb47966961f3a70ca0848425194fJosh Gao    Subprocess* raw = subprocess.release();
395344778da411ebb47966961f3a70ca0848425194fJosh Gao    if (!adb_thread_create(ThreadHandler, raw)) {
3964323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        *error =
3974323507a7eecb2384a872086ab933948bd8cbe80Josh Gao            android::base::StringPrintf("failed to create subprocess thread: %s", strerror(errno));
398344778da411ebb47966961f3a70ca0848425194fJosh Gao        kill(raw->pid_, SIGKILL);
399a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        return false;
400a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    }
401a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
402a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    return true;
40380f67029e002a97dd4f752881d820b3161f729f1David Pursell}
40480f67029e002a97dd4f752881d820b3161f729f1David Pursell
4052ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughesint Subprocess::OpenPtyChildFd(const char* pts_name, unique_fd* error_sfd) {
406a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    int child_fd = adb_open(pts_name, O_RDWR | O_CLOEXEC);
407a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (child_fd == -1) {
408a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        // Don't use WriteFdFmt; since we're in the fork() child we don't want
409a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        // to allocate any heap memory to avoid race conditions.
410a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        const char* messages[] = {"child failed to open pseudo-term slave ",
411a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell                                  pts_name, ": ", strerror(errno)};
412a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        for (const char* message : messages) {
4132ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            WriteFdExactly(*error_sfd, message);
414a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        }
4154abdeee073aecd2130e82f301ceff03dbd27fd72Josh Gao        abort();
416a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    }
417a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
41857dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    if (make_pty_raw_) {
41957dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        termios tattr;
42057dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        if (tcgetattr(child_fd, &tattr) == -1) {
42157dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell            int saved_errno = errno;
4222ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            WriteFdExactly(*error_sfd, "tcgetattr failed: ");
4232ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            WriteFdExactly(*error_sfd, strerror(saved_errno));
4244abdeee073aecd2130e82f301ceff03dbd27fd72Josh Gao            abort();
42557dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        }
42657dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell
42757dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        cfmakeraw(&tattr);
42857dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        if (tcsetattr(child_fd, TCSADRAIN, &tattr) == -1) {
42957dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell            int saved_errno = errno;
4302ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            WriteFdExactly(*error_sfd, "tcsetattr failed: ");
4312ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            WriteFdExactly(*error_sfd, strerror(saved_errno));
4324abdeee073aecd2130e82f301ceff03dbd27fd72Josh Gao            abort();
43357dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell        }
43457dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell    }
43557dd5ae1e3004daec664263e24dc4dcf4475bb02David Pursell
436a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    return child_fd;
437a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell}
438a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
439b5fea14e13bb6e41b36f374c954dc55faeef4627Josh Gaovoid Subprocess::ThreadHandler(void* userdata) {
440a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    Subprocess* subprocess = reinterpret_cast<Subprocess*>(userdata);
441a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
442a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    adb_thread_setname(android::base::StringPrintf(
443cd5d7376dceb14b5bb5d84540192b63b3c86b4d3Josh Gao            "shell srvc %d", subprocess->pid()));
444a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
445344778da411ebb47966961f3a70ca0848425194fJosh Gao    D("passing data streams for PID %d", subprocess->pid());
4460955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    subprocess->PassDataStreams();
447a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
4481ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell    D("deleting Subprocess for PID %d", subprocess->pid());
449a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    delete subprocess;
450a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell}
45180f67029e002a97dd4f752881d820b3161f729f1David Pursell
4520955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursellvoid Subprocess::PassDataStreams() {
4532ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    if (protocol_sfd_ == -1) {
4540955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        return;
4550955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
4560955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
4570955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // Start by trying to read from the protocol FD, stdout, and stderr.
4580955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    fd_set master_read_set, master_write_set;
4590955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    FD_ZERO(&master_read_set);
4600955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    FD_ZERO(&master_write_set);
4612ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    for (unique_fd* sfd : {&protocol_sfd_, &stdinout_sfd_, &stderr_sfd_}) {
4622ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        if (*sfd != -1) {
4632ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            FD_SET(*sfd, &master_read_set);
4640955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
4650955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
4660955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
4670955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // Pass data until the protocol FD or both the subprocess pipes die, at
4680955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // which point we can't pass any more data.
4692ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    while (protocol_sfd_ != -1 && (stdinout_sfd_ != -1 || stderr_sfd_ != -1)) {
4702ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        unique_fd* dead_sfd = SelectLoop(&master_read_set, &master_write_set);
4710955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (dead_sfd) {
4722ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            D("closing FD %d", dead_sfd->get());
4732ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            FD_CLR(*dead_sfd, &master_read_set);
4742ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            FD_CLR(*dead_sfd, &master_write_set);
475544e795fbb8a750f67796d7d0cad898f3f5f711cDavid Pursell            if (dead_sfd == &protocol_sfd_) {
476544e795fbb8a750f67796d7d0cad898f3f5f711cDavid Pursell                // Using SIGHUP is a decent general way to indicate that the
477544e795fbb8a750f67796d7d0cad898f3f5f711cDavid Pursell                // controlling process is going away. If specific signals are
478544e795fbb8a750f67796d7d0cad898f3f5f711cDavid Pursell                // needed (e.g. SIGINT), pass those through the shell protocol
479544e795fbb8a750f67796d7d0cad898f3f5f711cDavid Pursell                // and only fall back on this for unexpected closures.
480544e795fbb8a750f67796d7d0cad898f3f5f711cDavid Pursell                D("protocol FD died, sending SIGHUP to pid %d", pid_);
481544e795fbb8a750f67796d7d0cad898f3f5f711cDavid Pursell                kill(pid_, SIGHUP);
482f2aa186c7b0792ef4d3e106e2a03be5c3c215118David Pursell
483f2aa186c7b0792ef4d3e106e2a03be5c3c215118David Pursell                // We also need to close the pipes connected to the child process
484f2aa186c7b0792ef4d3e106e2a03be5c3c215118David Pursell                // so that if it ignores SIGHUP and continues to write data it
485f2aa186c7b0792ef4d3e106e2a03be5c3c215118David Pursell                // won't fill up the pipe and block.
4865d1b1a8b91a35f465e5af146bcfd5d7b4346854cJosh Gao                stdinout_sfd_.reset();
4875d1b1a8b91a35f465e5af146bcfd5d7b4346854cJosh Gao                stderr_sfd_.reset();
488544e795fbb8a750f67796d7d0cad898f3f5f711cDavid Pursell            }
4895d1b1a8b91a35f465e5af146bcfd5d7b4346854cJosh Gao            dead_sfd->reset();
4900955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
4910955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
4920955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell}
4930955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
4940955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursellnamespace {
4950955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
4962ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughesinline bool ValidAndInSet(const unique_fd& sfd, fd_set* set) {
4972ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    return sfd != -1 && FD_ISSET(sfd, set);
4980955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell}
4990955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5000955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell}   // namespace
5010955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5022ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughesunique_fd* Subprocess::SelectLoop(fd_set* master_read_set_ptr,
5032ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                                  fd_set* master_write_set_ptr) {
5040955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    fd_set read_set, write_set;
5052ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    int select_n = std::max(std::max(protocol_sfd_, stdinout_sfd_), stderr_sfd_) + 1;
5062ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    unique_fd* dead_sfd = nullptr;
5070955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5080955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // Keep calling select() and passing data until an FD closes/errors.
5090955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    while (!dead_sfd) {
5100955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        memcpy(&read_set, master_read_set_ptr, sizeof(read_set));
5110955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        memcpy(&write_set, master_write_set_ptr, sizeof(write_set));
5120955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (select(select_n, &read_set, &write_set, nullptr, nullptr) < 0) {
5130955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            if (errno == EINTR) {
5140955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell                continue;
5150955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            } else {
5160955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell                PLOG(ERROR) << "select failed, closing subprocess pipes";
5172ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                stdinout_sfd_.reset(-1);
5182ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                stderr_sfd_.reset(-1);
5190955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell                return nullptr;
5200955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            }
5210955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
5220955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5230955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // Read stdout, write to protocol FD.
5240955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (ValidAndInSet(stdinout_sfd_, &read_set)) {
5250955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            dead_sfd = PassOutput(&stdinout_sfd_, ShellProtocol::kIdStdout);
5260955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
5270955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5280955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // Read stderr, write to protocol FD.
5290955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (!dead_sfd && ValidAndInSet(stderr_sfd_, &read_set)) {
5300955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            dead_sfd = PassOutput(&stderr_sfd_, ShellProtocol::kIdStderr);
5310955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
5320955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5330955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // Read protocol FD, write to stdin.
5340955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (!dead_sfd && ValidAndInSet(protocol_sfd_, &read_set)) {
5350955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            dead_sfd = PassInput();
5360955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            // If we didn't finish writing, block on stdin write.
5370955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            if (input_bytes_left_) {
5382ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                FD_CLR(protocol_sfd_, master_read_set_ptr);
5392ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                FD_SET(stdinout_sfd_, master_write_set_ptr);
5400955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            }
5410955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
5420955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5430955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        // Continue writing to stdin; only happens if a previous write blocked.
5440955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (!dead_sfd && ValidAndInSet(stdinout_sfd_, &write_set)) {
5450955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            dead_sfd = PassInput();
5460955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            // If we finished writing, go back to blocking on protocol read.
5470955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            if (!input_bytes_left_) {
5482ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                FD_SET(protocol_sfd_, master_read_set_ptr);
5492ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                FD_CLR(stdinout_sfd_, master_write_set_ptr);
5500955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            }
5510955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
5520955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }  // while (!dead_sfd)
5530955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5540955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    return dead_sfd;
5550955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell}
5560955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5572ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughesunique_fd* Subprocess::PassInput() {
5580955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // Only read a new packet if we've finished writing the last one.
5590955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    if (!input_bytes_left_) {
5600955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (!input_->Read()) {
5610955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            // Read() uses ReadFdExactly() which sets errno to 0 on EOF.
5620955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            if (errno != 0) {
5632ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
5640955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            }
5650955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            return &protocol_sfd_;
5660955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
5670955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
5682ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        if (stdinout_sfd_ != -1) {
5691ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell            switch (input_->id()) {
570c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                case ShellProtocol::kIdWindowSizeChange:
571c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                    int rows, cols, x_pixels, y_pixels;
572c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                    if (sscanf(input_->data(), "%dx%d,%dx%d",
573c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                               &rows, &cols, &x_pixels, &y_pixels) == 4) {
574c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                        winsize ws;
575c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                        ws.ws_row = rows;
576c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                        ws.ws_col = cols;
577c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                        ws.ws_xpixel = x_pixels;
578c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                        ws.ws_ypixel = y_pixels;
5792ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                        ioctl(stdinout_sfd_, TIOCSWINSZ, &ws);
580c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                    }
581c15b17f1acfcdbda8602ab135371f7b7238b4b39Elliott Hughes                    break;
5821ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                case ShellProtocol::kIdStdin:
5831ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                    input_bytes_left_ = input_->data_length();
5841ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                    break;
5851ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                case ShellProtocol::kIdCloseStdin:
5861ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                    if (type_ == SubprocessType::kRaw) {
5872ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                        if (adb_shutdown(stdinout_sfd_, SHUT_WR) == 0) {
5881ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                            return nullptr;
5891ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        }
5901ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        PLOG(ERROR) << "failed to shutdown writes to FD "
5912ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                                    << stdinout_sfd_;
5921ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        return &stdinout_sfd_;
5931ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                    } else {
5941ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        // PTYs can't close just input, so rather than close the
5951ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        // FD and risk losing subprocess output, leave it open.
5961ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        // This only happens if the client starts a PTY shell
5971ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        // non-interactively which is rare and unsupported.
5981ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        // If necessary, the client can manually close the shell
5991ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                        // with `exit` or by killing the adb client process.
6002ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                        D("can't close input for PTY FD %d", stdinout_sfd_.get());
6011ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                    }
6021ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell                    break;
6031ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell            }
6040955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
6050955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
6060955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
6070955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    if (input_bytes_left_ > 0) {
6080955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        int index = input_->data_length() - input_bytes_left_;
6092ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        int bytes = adb_write(stdinout_sfd_, input_->data() + index, input_bytes_left_);
6100955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
6110955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            if (bytes < 0) {
6122ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes                PLOG(ERROR) << "error reading stdin FD " << stdinout_sfd_;
6130955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            }
6140955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            // stdin is done, mark this packet as finished and we'll just start
6150955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            // dumping any further data received from the protocol FD.
6160955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            input_bytes_left_ = 0;
6170955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            return &stdinout_sfd_;
6180955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        } else if (bytes > 0) {
6190955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            input_bytes_left_ -= bytes;
6200955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
6210955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
6220955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
6230955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    return nullptr;
6240955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell}
6250955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
6262ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughesunique_fd* Subprocess::PassOutput(unique_fd* sfd, ShellProtocol::Id id) {
6272ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    int bytes = adb_read(*sfd, output_->data(), output_->data_capacity());
6280955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    if (bytes == 0 || (bytes < 0 && errno != EAGAIN)) {
6291ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell        // read() returns EIO if a PTY closes; don't report this as an error,
6301ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell        // it just means the subprocess completed.
6311ed57f0dc333c0bc0800e222c569cca8a71deb89David Pursell        if (bytes < 0 && !(type_ == SubprocessType::kPty && errno == EIO)) {
6322ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            PLOG(ERROR) << "error reading output FD " << *sfd;
6330955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
6340955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        return sfd;
6350955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
6360955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
6370955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    if (bytes > 0 && !output_->Write(id, bytes)) {
6380955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (errno != 0) {
6392ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            PLOG(ERROR) << "error reading protocol FD " << protocol_sfd_;
6400955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
6410955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        return &protocol_sfd_;
6420955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
6430955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
6440955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    return nullptr;
6450955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell}
6460955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
647a932058504ee20d28f1a5b3c17c377543e4eb281David Pursellvoid Subprocess::WaitForExit() {
6480955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    int exit_code = 1;
6490955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
650a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    D("waiting for pid %d", pid_);
65180f67029e002a97dd4f752881d820b3161f729f1David Pursell    while (true) {
65280f67029e002a97dd4f752881d820b3161f729f1David Pursell        int status;
653a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        if (pid_ == waitpid(pid_, &status, 0)) {
654a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell            D("post waitpid (pid=%d) status=%04x", pid_, status);
65580f67029e002a97dd4f752881d820b3161f729f1David Pursell            if (WIFSIGNALED(status)) {
6560955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell                exit_code = 0x80 | WTERMSIG(status);
657a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell                D("subprocess killed by signal %d", WTERMSIG(status));
65880f67029e002a97dd4f752881d820b3161f729f1David Pursell                break;
65980f67029e002a97dd4f752881d820b3161f729f1David Pursell            } else if (!WIFEXITED(status)) {
660a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell                D("subprocess didn't exit");
66180f67029e002a97dd4f752881d820b3161f729f1David Pursell                break;
66280f67029e002a97dd4f752881d820b3161f729f1David Pursell            } else if (WEXITSTATUS(status) >= 0) {
6630955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell                exit_code = WEXITSTATUS(status);
664a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell                D("subprocess exit code = %d", WEXITSTATUS(status));
66580f67029e002a97dd4f752881d820b3161f729f1David Pursell                break;
66680f67029e002a97dd4f752881d820b3161f729f1David Pursell            }
667a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        }
66880f67029e002a97dd4f752881d820b3161f729f1David Pursell    }
669a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell
6700955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    // If we have an open protocol FD send an exit packet.
6712ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes    if (protocol_sfd_ != -1) {
6720955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        output_->data()[0] = exit_code;
6730955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        if (output_->Write(ShellProtocol::kIdExit, 1)) {
6740955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            D("wrote the exit code packet: %d", exit_code);
6750955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        } else {
6760955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell            PLOG(ERROR) << "failed to write the exit code packet";
6770955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell        }
6782ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        protocol_sfd_.reset(-1);
6790955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell    }
6800955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell
681a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    // Pass the local socket FD to the shell cleanup fdevent.
682a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (SHELL_EXIT_NOTIFY_FD >= 0) {
6832ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes        int fd = local_socket_sfd_;
684a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        if (WriteFdExactly(SHELL_EXIT_NOTIFY_FD, &fd, sizeof(fd))) {
685a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell            D("passed fd %d to SHELL_EXIT_NOTIFY_FD (%d) for pid %d",
686a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell              fd, SHELL_EXIT_NOTIFY_FD, pid_);
687a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell            // The shell exit fdevent now owns the FD and will close it once
688a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell            // the last bit of data flushes through.
6892ce86e527b9593b97d14b9f07aa85b60000564a2Elliott Hughes            static_cast<void>(local_socket_sfd_.release());
690a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        } else {
691a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell            PLOG(ERROR) << "failed to write fd " << fd
692a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell                        << " to SHELL_EXIT_NOTIFY_FD (" << SHELL_EXIT_NOTIFY_FD
693a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell                        << ") for pid " << pid_;
694a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        }
69580f67029e002a97dd4f752881d820b3161f729f1David Pursell    }
69680f67029e002a97dd4f752881d820b3161f729f1David Pursell}
69780f67029e002a97dd4f752881d820b3161f729f1David Pursell
69880f67029e002a97dd4f752881d820b3161f729f1David Pursell}  // namespace
69980f67029e002a97dd4f752881d820b3161f729f1David Pursell
7004323507a7eecb2384a872086ab933948bd8cbe80Josh Gao// Create a pipe containing the error.
7014323507a7eecb2384a872086ab933948bd8cbe80Josh Gaostatic int ReportError(SubprocessProtocol protocol, const std::string& message) {
7024323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    int pipefd[2];
7034323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    if (pipe(pipefd) != 0) {
7044323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        LOG(ERROR) << "failed to create pipe to report error";
7054323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        return -1;
7064323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    }
7074323507a7eecb2384a872086ab933948bd8cbe80Josh Gao
7084323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    std::string buf = android::base::StringPrintf("error: %s\n", message.c_str());
7094323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    if (protocol == SubprocessProtocol::kShell) {
7104323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        ShellProtocol::Id id = ShellProtocol::kIdStderr;
7114323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        uint32_t length = buf.length();
7124323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        WriteFdExactly(pipefd[1], &id, sizeof(id));
7134323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        WriteFdExactly(pipefd[1], &length, sizeof(length));
7144323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    }
7154323507a7eecb2384a872086ab933948bd8cbe80Josh Gao
7164323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    WriteFdExactly(pipefd[1], buf.data(), buf.length());
7174323507a7eecb2384a872086ab933948bd8cbe80Josh Gao
7184323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    if (protocol == SubprocessProtocol::kShell) {
7194323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        ShellProtocol::Id id = ShellProtocol::kIdExit;
7204323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        uint32_t length = 1;
7214323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        char exit_code = 126;
7224323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        WriteFdExactly(pipefd[1], &id, sizeof(id));
7234323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        WriteFdExactly(pipefd[1], &length, sizeof(length));
7244323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        WriteFdExactly(pipefd[1], &exit_code, sizeof(exit_code));
7254323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    }
7264323507a7eecb2384a872086ab933948bd8cbe80Josh Gao
7274323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    adb_close(pipefd[1]);
7284323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    return pipefd[0];
7294323507a7eecb2384a872086ab933948bd8cbe80Josh Gao}
7304323507a7eecb2384a872086ab933948bd8cbe80Josh Gao
73118ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughesint StartSubprocess(const char* name, const char* terminal_type,
73218ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes                    SubprocessType type, SubprocessProtocol protocol) {
73318ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes    D("starting %s subprocess (protocol=%s, TERM=%s): '%s'",
7340955c66b226db7a7f34613f834f7b0a145fd407dDavid Pursell      type == SubprocessType::kRaw ? "raw" : "PTY",
73518ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes      protocol == SubprocessProtocol::kNone ? "none" : "shell",
73618ddf5c6a233bd56d20548fd834c0ecbf8216410Elliott Hughes      terminal_type, name);
73780f67029e002a97dd4f752881d820b3161f729f1David Pursell
738344778da411ebb47966961f3a70ca0848425194fJosh Gao    auto subprocess = std::make_unique<Subprocess>(name, terminal_type, type, protocol);
739a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell    if (!subprocess) {
740a932058504ee20d28f1a5b3c17c377543e4eb281David Pursell        LOG(ERROR) << "failed to allocate new subprocess";
7414323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        return ReportError(protocol, "failed to allocate new subprocess");
74280f67029e002a97dd4f752881d820b3161f729f1David Pursell    }
74380f67029e002a97dd4f752881d820b3161f729f1David Pursell
7444323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    std::string error;
7454323507a7eecb2384a872086ab933948bd8cbe80Josh Gao    if (!subprocess->ForkAndExec(&error)) {
7464323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        LOG(ERROR) << "failed to start subprocess: " << error;
7474323507a7eecb2384a872086ab933948bd8cbe80Josh Gao        return ReportError(protocol, error);
74880f67029e002a97dd4f752881d820b3161f729f1David Pursell    }
74980f67029e002a97dd4f752881d820b3161f729f1David Pursell
750e31a7a4ce4a294e6ceafc30efd964dea35366131Josh Gao    unique_fd local_socket(subprocess->ReleaseLocalSocket());
751e31a7a4ce4a294e6ceafc30efd964dea35366131Josh Gao    D("subprocess creation successful: local_socket_fd=%d, pid=%d", local_socket.get(),
752e31a7a4ce4a294e6ceafc30efd964dea35366131Josh Gao      subprocess->pid());
753344778da411ebb47966961f3a70ca0848425194fJosh Gao
754344778da411ebb47966961f3a70ca0848425194fJosh Gao    if (!Subprocess::StartThread(std::move(subprocess), &error)) {
755344778da411ebb47966961f3a70ca0848425194fJosh Gao        LOG(ERROR) << "failed to start subprocess management thread: " << error;
756344778da411ebb47966961f3a70ca0848425194fJosh Gao        return ReportError(protocol, error);
757344778da411ebb47966961f3a70ca0848425194fJosh Gao    }
758344778da411ebb47966961f3a70ca0848425194fJosh Gao
759e31a7a4ce4a294e6ceafc30efd964dea35366131Josh Gao    return local_socket.release();
76080f67029e002a97dd4f752881d820b3161f729f1David Pursell}
761