1 /*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <string.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22 #include <unistd.h>
23
24 #include <string>
25
26 #include "adb.h"
27 #include "adb_io.h"
28 #include "adb_unique_fd.h"
29
30 static constexpr char kRemountCmd[] = "/system/bin/remount";
31
do_remount(int fd,const std::string & cmd)32 static bool do_remount(int fd, const std::string& cmd) {
33 if (getuid() != 0) {
34 WriteFdExactly(fd, "Not running as root. Try \"adb root\" first.\n");
35 return false;
36 }
37
38 auto pid = fork();
39 if (pid < 0) {
40 WriteFdFmt(fd, "Failed to fork to %s: %s\n", kRemountCmd, strerror(errno));
41 return false;
42 }
43
44 if (pid == 0) {
45 // child side of the fork
46 dup2(fd, STDIN_FILENO);
47 dup2(fd, STDOUT_FILENO);
48 dup2(fd, STDERR_FILENO);
49
50 execl(kRemountCmd, kRemountCmd, cmd.empty() ? nullptr : cmd.c_str(), nullptr);
51 _exit(errno);
52 }
53
54 int wstatus = 0;
55 auto ret = waitpid(pid, &wstatus, 0);
56
57 if (ret == -1) {
58 WriteFdFmt(fd, "Failed to wait for %s: %s\n", kRemountCmd, strerror(errno));
59 return false;
60 } else if (ret != pid) {
61 WriteFdFmt(fd, "pid %d and waitpid return %d do not match for %s\n",
62 static_cast<int>(pid), static_cast<int>(ret), kRemountCmd);
63 return false;
64 }
65
66 if (WIFSIGNALED(wstatus)) {
67 WriteFdFmt(fd, "%s terminated with signal %s\n", kRemountCmd,
68 strsignal(WTERMSIG(wstatus)));
69 return false;
70 }
71
72 if (!WIFEXITED(wstatus)) {
73 WriteFdFmt(fd, "%s stopped with status 0x%x\n", kRemountCmd, wstatus);
74 return false;
75 }
76
77 if (WEXITSTATUS(wstatus)) {
78 WriteFdFmt(fd, "%s exited with status %d\n", kRemountCmd, WEXITSTATUS(wstatus));
79 return false;
80 }
81
82 return true;
83 }
84
remount_service(unique_fd fd,const std::string & cmd)85 void remount_service(unique_fd fd, const std::string& cmd) {
86 const char* success = do_remount(fd.get(), cmd) ? "succeeded" : "failed";
87 WriteFdFmt(fd.get(), "remount %s\n", success);
88 }
89