| 6 |
| 7 | #include <crt_externs.h> |
| 8 | #include <mach/mach.h> |
| 9 | #include <os/availability.h> |
| 10 | #include <spawn.h> |
| 11 | #include <string.h> |
| 12 | #include <sys/syscall.h> |
| 13 | #include <sys/wait.h> |
| 14 |
| 15 | #include "base/command_line.h" |
| 16 | #include "base/files/scoped_file.h" |
| 17 | #include "base/logging.h" |
| 18 | #include "base/posix/eintr_wrapper.h" |
| 19 | #include "base/process/environment_internal.h" |
| 20 | #include "base/threading/scoped_blocking_call.h" |
| 21 | #include "base/threading/thread_restrictions.h" |
| 22 | #include "base/trace_event/trace_event.h" |
| 23 |
| 24 | extern "C" { |
| 25 | // Changes the current thread's directory to a path or directory file |
| 26 | // descriptor. libpthread only exposes a syscall wrapper starting in |
| 27 | // macOS 10.12, but the system call dates back to macOS 10.5. On older OSes, |
| 28 | // the syscall is issued directly. |
| 29 | int pthread_chdir_np(const char* dir) API_AVAILABLE(macosx(10.12)); |
| 30 | int pthread_fchdir_np(int fd) API_AVAILABLE(macosx(10.12)); |
| 31 |
| 32 | int responsibility_spawnattrs_setdisclaim(posix_spawnattr_t attrs, int disclaim) |
| 33 | API_AVAILABLE(macosx(10.14)); |
| 34 | } // extern "C" |
| 35 |
| 36 | namespace base { |
| 37 |
| 38 | // Friend and derived class of ScopedAllowBaseSyncPrimitives which allows |
| 39 | // GetAppOutputInternal() to join a process. GetAppOutputInternal() can't itself |
| 40 | // be a friend of ScopedAllowBaseSyncPrimitives because it is in the anonymous |
| 41 | // namespace. |
| 42 | class GetAppOutputScopedAllowBaseSyncPrimitives |
| 43 | : public base::ScopedAllowBaseSyncPrimitives {}; |
| 44 |
| 45 | namespace { |
| 46 |
| 47 | // DPSXCHECK is a Debug Posix Spawn Check macro. The posix_spawn* family of |
| 48 | // functions return an errno value, as opposed to setting errno directly. This |
| 49 | // macro emulates a DPCHECK(). |
| 50 | #define DPSXCHECK(expr) \ |
| 51 | do { \ |
| 52 | int rv = (expr); \ |
| 53 | DCHECK_EQ(rv, 0) << #expr << ": -" << rv << " " << strerror(rv); \ |
| 54 | } while (0) |
| 55 |
| 56 | class PosixSpawnAttr { |
| 57 | public: |
| 58 | PosixSpawnAttr() { DPSXCHECK(posix_spawnattr_init(&attr_)); } |
| 59 |
| 60 | ~PosixSpawnAttr() { DPSXCHECK(posix_spawnattr_destroy(&attr_)); } |
| 61 |
| 62 | posix_spawnattr_t* get() { return &attr_; } |
| 63 |
| 64 | private: |
| 65 | posix_spawnattr_t attr_; |
| 66 | }; |
| 67 |
| 68 | class PosixSpawnFileActions { |
| 69 | public: |
| 70 | PosixSpawnFileActions() { |
| 71 | DPSXCHECK(posix_spawn_file_actions_init(&file_actions_)); |
| 72 | } |
| 73 |
| 74 | ~PosixSpawnFileActions() { |
| 75 | DPSXCHECK(posix_spawn_file_actions_destroy(&file_actions_)); |
| 76 | } |
| 77 |
| 78 | void Open(int filedes, const char* path, int mode) { |
| 79 | DPSXCHECK(posix_spawn_file_actions_addopen(&file_actions_, filedes, path, |
| 80 | mode, 0)); |
| 81 | } |
| 82 |
| 83 | void Dup2(int filedes, int newfiledes) { |
| 84 | DPSXCHECK( |
| 85 | posix_spawn_file_actions_adddup2(&file_actions_, filedes, newfiledes)); |
| 86 | } |
| 87 |
| 88 | void Inherit(int filedes) { |
| 89 | DPSXCHECK(posix_spawn_file_actions_addinherit_np(&file_actions_, filedes)); |
| 90 | } |
| 91 |
| 92 | const posix_spawn_file_actions_t* get() const { return &file_actions_; } |
| 93 |
| 94 | private: |
| 95 | posix_spawn_file_actions_t file_actions_; |
| 96 |
| 97 | DISALLOW_COPY_AND_ASSIGN(PosixSpawnFileActions); |
| 98 | }; |
| 99 |
| 100 | int ChangeCurrentThreadDirectory(const char* path) { |
| 101 | if (__builtin_available(macOS 10.12, *)) { |
| 102 | return pthread_chdir_np(path); |
| 103 | } else { |
| 104 | return syscall(SYS___pthread_chdir, path); |
| 105 | } |
| 106 | } |
| 107 |
| 108 | // The recommended way to unset a per-thread cwd is to set a new value to an |
| 109 | // invalid file descriptor, per libpthread-218.1.3/private/private.h. |
| 110 | int ResetCurrentThreadDirectory() { |
| 111 | if (__builtin_available(macOS 10.12, *)) { |
| 112 | return pthread_fchdir_np(-1); |
| 113 | } else { |
| 114 | return syscall(SYS___pthread_fchdir, -1); |
| 115 | } |
| 116 | } |
| 117 |
| 118 | struct GetAppOutputOptions { |
| 119 | // Whether to pipe stderr to stdout in |output|. |
| 120 | bool include_stderr = false; |
| 121 | // Caller-supplied string poiter for the output. |
| 122 | std::string* output = nullptr; |
| 123 | // Result exit code of Process::Wait(). |
| 124 | int exit_code = 0; |
| 125 | }; |
| 126 |
| 127 | bool GetAppOutputInternal(const std::vector<std::string>& argv, |
| 128 | GetAppOutputOptions* gao_options) { |
| 129 | ScopedFD read_fd, write_fd; |
| 130 | { |
| 131 | int pipefds[2]; |
| 132 | if (pipe(pipefds) != 0) { |
| 133 | DPLOG(ERROR) << "pipe"; |
| 134 | return false; |
| 135 | } |
| 136 | read_fd.reset(pipefds[0]); |
| 137 | write_fd.reset(pipefds[1]); |
| 138 | } |
| 139 |
| 140 | LaunchOptions launch_options; |
| 141 | launch_options.fds_to_remap.emplace_back(write_fd.get(), STDOUT_FILENO); |
| 142 | if (gao_options->include_stderr) { |
| 143 | launch_options.fds_to_remap.emplace_back(write_fd.get(), STDERR_FILENO); |
| 144 | } |
| 145 |
| 146 | Process process = LaunchProcess(argv, launch_options); |
| 147 |
| 148 | // Close the parent process' write descriptor, so that EOF is generated in |
| 149 | // read loop below. |
| 150 | write_fd.reset(); |
| 151 |
| 152 | // Read the child's output before waiting for its exit, otherwise the pipe |
| 153 | // buffer may fill up if the process is producing a lot of output. |
| 154 | std::string* output = gao_options->output; |
| 155 | output->clear(); |
| 156 |
| 157 | const size_t kBufferSize = 1024; |
| 158 | size_t total_bytes_read = 0; |
| 159 | ssize_t read_this_pass = 0; |
| 160 | do { |
| 161 | output->resize(output->size() + kBufferSize); |
| 162 | read_this_pass = HANDLE_EINTR( |
| 163 | read(read_fd.get(), &(*output)[total_bytes_read], kBufferSize)); |
| 164 | if (read_this_pass >= 0) { |
| 165 | total_bytes_read += read_this_pass; |
| 166 | output->resize(total_bytes_read); |
| 167 | } |
| 168 | } while (read_this_pass > 0); |
| 169 |
| 170 | // Reap the child process. |
| 171 | GetAppOutputScopedAllowBaseSyncPrimitives allow_wait; |
| 172 | if (!process.WaitForExit(&gao_options->exit_code)) { |
| 173 | return false; |
| 174 | } |
| 175 |
| 176 | return read_this_pass == 0; |
| 177 | } |
| 178 |
| 179 | } // namespace |
| 180 |
| 181 | Process LaunchProcess(const CommandLine& cmdline, |
| 182 | const LaunchOptions& options) { |
| 183 | return LaunchProcess(cmdline.argv(), options); |
| 184 | } |
| 185 |
| 186 | Process LaunchProcess(const std::vector<std::string>& argv, |
| 187 | const LaunchOptions& options) { |
| 188 | TRACE_EVENT0("base", "LaunchProcess"); |
| 189 |
| 190 | PosixSpawnAttr attr; |
| 191 |
| 192 | short flags = POSIX_SPAWN_CLOEXEC_DEFAULT; |
| 193 | if (options.new_process_group) { |
| 194 | flags |= POSIX_SPAWN_SETPGROUP; |
| 195 | DPSXCHECK(posix_spawnattr_setpgroup(attr.get(), 0)); |
| 196 | } |
| 197 | DPSXCHECK(posix_spawnattr_setflags(attr.get(), flags)); |
| 198 |
| 199 | PosixSpawnFileActions file_actions; |
| 200 |
| 201 | // Process file descriptors for the child. By default, LaunchProcess will |
| 202 | // open stdin to /dev/null and inherit stdout and stderr. |
| 203 | bool inherit_stdout = true, inherit_stderr = true; |
| 204 | bool null_stdin = true; |
| 205 | for (const auto& dup2_pair : options.fds_to_remap) { |
| 206 | if (dup2_pair.second == STDIN_FILENO) { |
| 207 | null_stdin = false; |
| 208 | } else if (dup2_pair.second == STDOUT_FILENO) { |
| 209 | inherit_stdout = false; |
| 210 | } else if (dup2_pair.second == STDERR_FILENO) { |
| 211 | inherit_stderr = false; |
| 212 | } |
| 213 |
| 214 | if (dup2_pair.first == dup2_pair.second) { |
| 215 | file_actions.Inherit(dup2_pair.second); |
| 216 | } else { |
| 217 | file_actions.Dup2(dup2_pair.first, dup2_pair.second); |
| 218 | } |
| 219 | } |
| 220 |
| 221 | if (null_stdin) { |
| 222 | file_actions.Open(STDIN_FILENO, "/dev/null", O_RDONLY); |
| 223 | } |
| 224 | if (inherit_stdout) { |
| 225 | file_actions.Inherit(STDOUT_FILENO); |
| 226 | } |
| 227 | if (inherit_stderr) { |
| 228 | file_actions.Inherit(STDERR_FILENO); |
| 229 | } |
| 230 |
| 231 | if (options.disclaim_responsibility) { |
| 232 | if (__builtin_available(macOS 10.14, *)) { |
| 233 | DPSXCHECK(responsibility_spawnattrs_setdisclaim(attr.get(), 1)); |
| 234 | } |
| 235 | } |
| 236 |
| 237 | std::vector<char*> argv_cstr; |
| 238 | argv_cstr.reserve(argv.size() + 1); |
| 239 | for (const auto& arg : argv) |
| 240 | argv_cstr.push_back(const_cast<char*>(arg.c_str())); |
| 241 | argv_cstr.push_back(nullptr); |
| 242 |
| 243 | std::unique_ptr<char*[]> owned_environ; |
| 244 | char* empty_environ = nullptr; |
| 245 | char** new_environ = |
| 246 | options.clear_environment ? &empty_environ : *_NSGetEnviron(); |
| 247 | if (!options.environment.empty()) { |
| 248 | owned_environ = |
| 249 | internal::AlterEnvironment(new_environ, options.environment); |
| 250 | new_environ = owned_environ.get(); |
| 251 | } |
| 252 |
| 253 | const char* executable_path = !options.real_path.empty() |
| 254 | ? options.real_path.value().c_str() |
| 255 | : argv_cstr[0]; |
| 256 |
| 257 | // If the new program has specified its PWD, change the thread-specific |
| 258 | // working directory. The new process will inherit it during posix_spawnp(). |
| 259 | if (!options.current_directory.empty()) { |
| 260 | int rv = |
| 261 | ChangeCurrentThreadDirectory(options.current_directory.value().c_str()); |
| 262 | if (rv != 0) { |
| 263 | DPLOG(ERROR) << "pthread_chdir_np"; |
| 264 | return Process(); |
| 265 | } |
| 266 | } |
| 267 |
| 268 | int rv; |
| 269 | pid_t pid; |
| 270 | { |
| 271 | // If |options.mach_ports_for_rendezvous| is specified : the server's lock |
| 272 | // must be held for the duration of posix_spawnp() so that new child's PID |
| 273 | // can be recorded with the set of ports. |
| 274 | const bool has_mac_ports_for_rendezvous = |
| 275 | !options.mach_ports_for_rendezvous.empty(); |
| 276 | AutoLockMaybe rendezvous_lock( |
| 277 | has_mac_ports_for_rendezvous |
| 278 | ? &MachPortRendezvousServer::GetInstance()->GetLock() |
| 279 | : nullptr); |
| 280 |
| 281 | // Use posix_spawnp as some callers expect to have PATH consulted. |
| 282 | rv = posix_spawnp(&pid, executable_path, file_actions.get(), attr.get(), |
| 283 | &argv_cstr[0], new_environ); |
| 284 |
| 285 | if (has_mac_ports_for_rendezvous) { |
| 286 | auto* rendezvous = MachPortRendezvousServer::GetInstance(); |
| 287 | if (rv == 0) { |
| 288 | rendezvous->RegisterPortsForPid(pid, options.mach_ports_for_rendezvous); |
| 289 | } else { |
| 290 | // Because |options| is const-ref, the collection has to be copied here. |
| 291 | // The caller expects to relinquish ownership of any strong rights if |
| 292 | // LaunchProcess() were to succeed, so these rights should be manually |
| 293 | // destroyed on failure. |
| 294 | MachPortsForRendezvous ports = options.mach_ports_for_rendezvous; |
| 295 | for (auto& port : ports) { |
| 296 | port.second.Destroy(); |
| 297 | } |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 |
| 302 | // Restore the thread's working directory if it was changed. |
| 303 | if (!options.current_directory.empty()) { |
| 304 | ResetCurrentThreadDirectory(); |
| 305 | } |
| 306 |
| 307 | if (rv != 0) { |
| 308 | DLOG(ERROR) << "posix_spawnp(" << executable_path << "): -" << rv << " " |
| 309 | << strerror(rv); |
| 310 | return Process(); |
| 311 | } |
| 312 |
| 313 | if (options.wait) { |
| 314 | // While this isn't strictly disk IO, waiting for another process to |
| 315 | // finish is the sort of thing ThreadRestrictions is trying to prevent. |
| 316 | ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK); |
| 317 | pid_t ret = HANDLE_EINTR(waitpid(pid, nullptr, 0)); |
| 318 | DPCHECK(ret > 0); |
| 319 | } |
| 320 |
| 321 | return Process(pid); |
| 322 | } |
| 323 |
| 324 | bool GetAppOutput(const CommandLine& cl, std::string* output) { |
| 325 | return GetAppOutput(cl.argv(), output); |
| 326 | } |
| 327 |
| 328 | bool GetAppOutputAndError(const CommandLine& cl, std::string* output) { |
| 329 | return GetAppOutputAndError(cl.argv(), output); |
| 330 | } |
| 331 |
| 332 | bool GetAppOutputWithExitCode(const CommandLine& cl, |
| 333 | std::string* output, |
| 334 | int* exit_code) { |
| 335 | GetAppOutputOptions options; |
| 336 | options.output = output; |
| 337 | bool rv = GetAppOutputInternal(cl.argv(), &options); |
| 338 | *exit_code = options.exit_code; |
| 339 | return rv; |
| 340 | } |
| 341 |
| 342 | bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) { |
| 343 | GetAppOutputOptions options; |
| 344 | options.output = output; |
| 345 | return GetAppOutputInternal(argv, &options) && |
| 346 | options.exit_code == EXIT_SUCCESS; |
| 347 | } |
| 348 |
| 349 | bool GetAppOutputAndError(const std::vector<std::string>& argv, |
| 350 | std::string* output) { |
| 351 | GetAppOutputOptions options; |
| 352 | options.include_stderr = true; |
| 353 | options.output = output; |
| 354 | return GetAppOutputInternal(argv, &options) && |
| 355 | options.exit_code == EXIT_SUCCESS; |
| 356 | } |
| 357 |
| 358 | void RaiseProcessToHighPriority() { |
| 359 | // Historically this has not been implemented on POSIX and macOS. This could |
| 360 | // influence the Mach task policy in the future. |
| 361 | } |
| 362 |
| 363 | } // namespace base |
| 364 |