Process.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022-2023, MacDue <macdue@dueutil.tech>
  4. * Copyright (c) 2023-2024, Sam Atkins <atkinssj@serenityos.org>
  5. * Copyright (c) 2024, Tim Flynn <trflynn89@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/ByteString.h>
  10. #include <AK/ScopeGuard.h>
  11. #include <AK/String.h>
  12. #include <AK/Vector.h>
  13. #include <LibCore/Environment.h>
  14. #include <LibCore/File.h>
  15. #include <LibCore/Process.h>
  16. #include <LibCore/Socket.h>
  17. #include <LibCore/SocketAddress.h>
  18. #include <LibCore/StandardPaths.h>
  19. #include <LibCore/System.h>
  20. #include <errno.h>
  21. #include <signal.h>
  22. #include <spawn.h>
  23. #include <unistd.h>
  24. #if defined(AK_OS_SERENITY)
  25. # include <serenity.h>
  26. # include <sys/prctl.h>
  27. # include <syscall.h>
  28. #elif defined(AK_OS_BSD_GENERIC) && !defined(AK_OS_SOLARIS)
  29. # include <sys/sysctl.h>
  30. #elif defined(AK_OS_GNU_HURD)
  31. extern "C" {
  32. # include <hurd.h>
  33. }
  34. #endif
  35. #if defined(AK_OS_FREEBSD)
  36. # include <sys/user.h>
  37. #endif
  38. namespace Core {
  39. struct ArgvList {
  40. ByteString m_path;
  41. Vector<char const*, 10> m_argv;
  42. ArgvList(ByteString path, size_t size)
  43. : m_path { path }
  44. {
  45. m_argv.ensure_capacity(size + 2);
  46. m_argv.append(m_path.characters());
  47. }
  48. void append(char const* arg)
  49. {
  50. m_argv.append(arg);
  51. }
  52. Span<char const*> get()
  53. {
  54. if (m_argv.is_empty() || m_argv.last() != nullptr)
  55. m_argv.append(nullptr);
  56. return m_argv;
  57. }
  58. };
  59. ErrorOr<Process> Process::spawn(ProcessSpawnOptions const& options)
  60. {
  61. #define CHECK(invocation) \
  62. if (int returned_errno = (invocation)) \
  63. return Error::from_errno(returned_errno);
  64. posix_spawn_file_actions_t spawn_actions;
  65. CHECK(posix_spawn_file_actions_init(&spawn_actions));
  66. ScopeGuard cleanup_spawn_actions = [&] {
  67. posix_spawn_file_actions_destroy(&spawn_actions);
  68. };
  69. if (options.working_directory.has_value()) {
  70. #ifdef AK_OS_SERENITY
  71. CHECK(posix_spawn_file_actions_addchdir(&spawn_actions, options.working_directory->characters()));
  72. #else
  73. // FIXME: Support ProcessSpawnOptions::working_directory n platforms that support it.
  74. TODO();
  75. #endif
  76. }
  77. for (auto const& file_action : options.file_actions) {
  78. TRY(file_action.visit(
  79. [&](FileAction::OpenFile const& action) -> ErrorOr<void> {
  80. CHECK(posix_spawn_file_actions_addopen(
  81. &spawn_actions,
  82. action.fd,
  83. action.path.characters(),
  84. File::open_mode_to_options(action.mode | Core::File::OpenMode::KeepOnExec),
  85. action.permissions));
  86. return {};
  87. },
  88. [&](FileAction::CloseFile const& action) -> ErrorOr<void> {
  89. CHECK(posix_spawn_file_actions_addclose(&spawn_actions, action.fd));
  90. return {};
  91. }));
  92. }
  93. #undef CHECK
  94. ArgvList argv_list(options.executable, options.arguments.size());
  95. for (auto const& argument : options.arguments)
  96. argv_list.append(argument.characters());
  97. pid_t pid;
  98. if (options.search_for_executable_in_path) {
  99. pid = TRY(System::posix_spawnp(options.executable.view(), &spawn_actions, nullptr, const_cast<char**>(argv_list.get().data()), Core::Environment::raw_environ()));
  100. } else {
  101. pid = TRY(System::posix_spawn(options.executable.view(), &spawn_actions, nullptr, const_cast<char**>(argv_list.get().data()), Core::Environment::raw_environ()));
  102. }
  103. return Process { pid };
  104. }
  105. ErrorOr<pid_t> Process::spawn(StringView path, ReadonlySpan<ByteString> arguments, ByteString working_directory, KeepAsChild keep_as_child)
  106. {
  107. auto process = TRY(spawn({
  108. .executable = path,
  109. .arguments = Vector<ByteString> { arguments },
  110. .working_directory = working_directory.is_empty() ? Optional<ByteString> {} : Optional<ByteString> { working_directory },
  111. }));
  112. if (keep_as_child == KeepAsChild::No)
  113. TRY(process.disown());
  114. else {
  115. // FIXME: This won't be needed if return value is changed to Process.
  116. process.m_should_disown = false;
  117. }
  118. return process.pid();
  119. }
  120. ErrorOr<pid_t> Process::spawn(StringView path, ReadonlySpan<StringView> arguments, ByteString working_directory, KeepAsChild keep_as_child)
  121. {
  122. Vector<ByteString> backing_strings;
  123. backing_strings.ensure_capacity(arguments.size());
  124. for (auto const& argument : arguments)
  125. backing_strings.append(argument);
  126. auto process = TRY(spawn({
  127. .executable = path,
  128. .arguments = backing_strings,
  129. .working_directory = working_directory.is_empty() ? Optional<ByteString> {} : Optional<ByteString> { working_directory },
  130. }));
  131. if (keep_as_child == KeepAsChild::No)
  132. TRY(process.disown());
  133. else
  134. process.m_should_disown = false;
  135. return process.pid();
  136. }
  137. ErrorOr<pid_t> Process::spawn(StringView path, ReadonlySpan<char const*> arguments, ByteString working_directory, KeepAsChild keep_as_child)
  138. {
  139. Vector<ByteString> backing_strings;
  140. backing_strings.ensure_capacity(arguments.size());
  141. for (auto const& argument : arguments)
  142. backing_strings.append(argument);
  143. auto process = TRY(spawn({
  144. .executable = path,
  145. .arguments = backing_strings,
  146. .working_directory = working_directory.is_empty() ? Optional<ByteString> {} : Optional<ByteString> { working_directory },
  147. }));
  148. if (keep_as_child == KeepAsChild::No)
  149. TRY(process.disown());
  150. else
  151. process.m_should_disown = false;
  152. return process.pid();
  153. }
  154. ErrorOr<String> Process::get_name()
  155. {
  156. #if defined(AK_OS_SERENITY)
  157. char buffer[BUFSIZ];
  158. int rc = get_process_name(buffer, BUFSIZ);
  159. if (rc != 0)
  160. return Error::from_syscall("get_process_name"sv, -rc);
  161. return String::from_utf8(StringView { buffer, strlen(buffer) });
  162. #elif defined(AK_LIBC_GLIBC) || (defined(AK_OS_LINUX) && !defined(AK_OS_ANDROID))
  163. return String::from_utf8(StringView { program_invocation_name, strlen(program_invocation_name) });
  164. #elif defined(AK_OS_BSD_GENERIC) || defined(AK_OS_HAIKU)
  165. auto const* progname = getprogname();
  166. return String::from_utf8(StringView { progname, strlen(progname) });
  167. #else
  168. // FIXME: Implement Process::get_name() for other platforms.
  169. return "???"_string;
  170. #endif
  171. }
  172. ErrorOr<void> Process::set_name([[maybe_unused]] StringView name, [[maybe_unused]] SetThreadName set_thread_name)
  173. {
  174. #if defined(AK_OS_SERENITY)
  175. int rc = set_process_name(name.characters_without_null_termination(), name.length());
  176. if (rc != 0)
  177. return Error::from_syscall("set_process_name"sv, -rc);
  178. if (set_thread_name == SetThreadName::No)
  179. return {};
  180. rc = prctl(PR_SET_THREAD_NAME, gettid(), name.characters_without_null_termination(), name.length());
  181. if (rc != 0)
  182. return Error::from_syscall("set_thread_name"sv, -rc);
  183. return {};
  184. #else
  185. // FIXME: Implement Process::set_name() for other platforms.
  186. return {};
  187. #endif
  188. }
  189. ErrorOr<bool> Process::is_being_debugged()
  190. {
  191. #if defined(AK_OS_LINUX)
  192. auto unbuffered_status_file = TRY(Core::File::open("/proc/self/status"sv, Core::File::OpenMode::Read));
  193. auto status_file = TRY(Core::InputBufferedFile::create(move(unbuffered_status_file)));
  194. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  195. while (TRY(status_file->can_read_line())) {
  196. auto line = TRY(status_file->read_line(buffer));
  197. auto const parts = line.split_view(':');
  198. if (parts.size() < 2 || parts[0] != "TracerPid"sv)
  199. continue;
  200. auto tracer_pid = parts[1].to_number<u32>();
  201. return (tracer_pid != 0UL);
  202. }
  203. return false;
  204. #elif defined(AK_OS_GNU_HURD)
  205. process_t proc = getproc();
  206. if (!MACH_PORT_VALID(proc))
  207. return Error::from_syscall("getproc"sv, -errno);
  208. int flags = PI_FETCH_TASKINFO;
  209. // We're going to ask the proc server for the info about our process,
  210. // and it is going to reply, placing the info into a buffer. It can
  211. // either fill in (overwrite) the buffer we provide to it (called pi_buffer
  212. // below), or allocate (as if with mmap or vm_allocate) a new buffer.
  213. // The buffer is really of type struct procinfo[], but it's transferred
  214. // over IPC as int[]. We pass in a double pointer (int** pi_array) that
  215. // initially points to our pi_buffer, but the call will update it to
  216. // point to the newly allocated buffer if it ends up making one.
  217. struct procinfo pi_buffer = {};
  218. int* pi_array = reinterpret_cast<int*>(&pi_buffer);
  219. mach_msg_type_number_t pi_array_len = sizeof(pi_buffer) / sizeof(int);
  220. data_t waits = nullptr;
  221. mach_msg_type_number_t waits_len = 0;
  222. kern_return_t err = proc_getprocinfo(proc, getpid(), &flags, &pi_array, &pi_array_len, &waits, &waits_len);
  223. mach_port_deallocate(mach_task_self(), proc);
  224. if (err) {
  225. __hurd_fail(static_cast<error_t>(err));
  226. return Error::from_syscall("proc_getprocinfo"sv, -errno);
  227. }
  228. // Now cast the returned buffer pointer back to struct procinfo, and
  229. // read the info we're interested in (the PI_TRACED flag) from there.
  230. VERIFY(pi_array_len >= sizeof(struct procinfo));
  231. struct procinfo* procinfo = reinterpret_cast<struct procinfo*>(pi_array);
  232. bool traced = procinfo->state & PI_TRACED;
  233. // If the returned buffer is not the one we allocated on the stack,
  234. // we should unmap it.
  235. if (procinfo != &pi_buffer)
  236. (void)System::munmap(pi_array, pi_array_len * sizeof(int));
  237. if (waits)
  238. (void)System::munmap(waits, waits_len);
  239. return traced;
  240. #elif defined(AK_OS_MACOS) || defined(AK_OS_FREEBSD)
  241. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  242. int mib[4] = {};
  243. struct kinfo_proc info = {};
  244. size_t size = sizeof(info);
  245. // Initialize mib, which tells sysctl the info we want, in this case
  246. // we're looking for information about a specific process ID.
  247. mib[0] = CTL_KERN;
  248. mib[1] = KERN_PROC;
  249. mib[2] = KERN_PROC_PID;
  250. mib[3] = getpid();
  251. if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0) < 0)
  252. return Error::from_syscall("sysctl"sv, -errno);
  253. // We're being debugged if the P_TRACED flag is set.
  254. # if defined(AK_OS_MACOS)
  255. return ((info.kp_proc.p_flag & P_TRACED) != 0);
  256. # elif defined(AK_OS_FREEBSD)
  257. return ((info.ki_flag & P_TRACED) != 0);
  258. # endif
  259. #endif
  260. // FIXME: Implement this for more platforms.
  261. return Error::from_string_view("Platform does not support checking for debugger"sv);
  262. }
  263. // Forces the process to sleep until a debugger is attached, then breaks.
  264. void Process::wait_for_debugger_and_break()
  265. {
  266. bool should_print_process_info { true };
  267. for (;;) {
  268. auto check = Process::is_being_debugged();
  269. if (check.is_error()) {
  270. dbgln("Cannot wait for debugger: {}. Continuing.", check.release_error());
  271. return;
  272. }
  273. if (check.value()) {
  274. kill(getpid(), SIGTRAP);
  275. return;
  276. }
  277. if (should_print_process_info) {
  278. dbgln("Process {} with pid {} is sleeping, waiting for debugger.", Process::get_name(), getpid());
  279. should_print_process_info = false;
  280. }
  281. ::usleep(100 * 1000);
  282. }
  283. }
  284. ErrorOr<void> Process::disown()
  285. {
  286. if (m_pid != 0 && m_should_disown) {
  287. #ifdef AK_OS_SERENITY
  288. TRY(System::disown(m_pid));
  289. #else
  290. // FIXME: Support disown outside Serenity.
  291. #endif
  292. m_should_disown = false;
  293. return {};
  294. } else {
  295. return Error::from_errno(EINVAL);
  296. }
  297. }
  298. ErrorOr<bool> Process::wait_for_termination()
  299. {
  300. VERIFY(m_pid > 0);
  301. bool exited_with_code_0 = true;
  302. int status;
  303. if (waitpid(m_pid, &status, 0) == -1)
  304. return Error::from_syscall("waitpid"sv, errno);
  305. if (WIFEXITED(status)) {
  306. exited_with_code_0 &= WEXITSTATUS(status) == 0;
  307. } else if (WIFSIGNALED(status)) {
  308. exited_with_code_0 = false;
  309. } else if (WIFSTOPPED(status)) {
  310. // This is only possible if the child process is being traced by us.
  311. VERIFY_NOT_REACHED();
  312. } else {
  313. VERIFY_NOT_REACHED();
  314. }
  315. m_should_disown = false;
  316. return exited_with_code_0;
  317. }
  318. ErrorOr<IPCProcess::ProcessAndIPCSocket> IPCProcess::spawn_and_connect_to_process(ProcessSpawnOptions const& options)
  319. {
  320. int socket_fds[2] {};
  321. TRY(System::socketpair(AF_LOCAL, SOCK_STREAM, 0, socket_fds));
  322. ArmedScopeGuard guard_fd_0 { [&] { MUST(System::close(socket_fds[0])); } };
  323. ArmedScopeGuard guard_fd_1 { [&] { MUST(System::close(socket_fds[1])); } };
  324. auto& file_actions = const_cast<ProcessSpawnOptions&>(options).file_actions;
  325. file_actions.append(FileAction::CloseFile { socket_fds[0] });
  326. auto takeover_string = MUST(String::formatted("{}:{}", options.name, socket_fds[1]));
  327. TRY(Environment::set("SOCKET_TAKEOVER"sv, takeover_string, Environment::Overwrite::Yes));
  328. auto process = TRY(Process::spawn(options));
  329. auto ipc_socket = TRY(LocalSocket::adopt_fd(socket_fds[0]));
  330. guard_fd_0.disarm();
  331. TRY(ipc_socket->set_blocking(true));
  332. return ProcessAndIPCSocket { move(process), move(ipc_socket) };
  333. }
  334. static ErrorOr<Optional<pid_t>> get_process_pid(StringView process_name, StringView pid_path)
  335. {
  336. if (System::stat(pid_path).is_error())
  337. return OptionalNone {};
  338. Optional<pid_t> pid;
  339. {
  340. auto pid_file = File::open(pid_path, File::OpenMode::Read);
  341. if (pid_file.is_error()) {
  342. warnln("Could not open {} PID file '{}': {}", process_name, pid_path, pid_file.error());
  343. return pid_file.release_error();
  344. }
  345. auto contents = pid_file.value()->read_until_eof();
  346. if (contents.is_error()) {
  347. warnln("Could not read {} PID file '{}': {}", process_name, pid_path, contents.error());
  348. return contents.release_error();
  349. }
  350. pid = StringView { contents.value() }.to_number<pid_t>();
  351. }
  352. if (!pid.has_value()) {
  353. warnln("{} PID file '{}' exists, but with an invalid PID", process_name, pid_path);
  354. TRY(System::unlink(pid_path));
  355. return OptionalNone {};
  356. }
  357. if (kill(*pid, 0) < 0) {
  358. warnln("{} PID file '{}' exists with PID {}, but process cannot be found", process_name, pid_path, *pid);
  359. TRY(System::unlink(pid_path));
  360. return OptionalNone {};
  361. }
  362. return pid;
  363. }
  364. // This is heavily based on how SystemServer's Service creates its socket.
  365. static ErrorOr<int> create_ipc_socket(ByteString const& socket_path)
  366. {
  367. if (!System::stat(socket_path).is_error())
  368. TRY(System::unlink(socket_path));
  369. #ifdef SOCK_NONBLOCK
  370. auto socket_fd = TRY(System::socket(AF_LOCAL, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
  371. #else
  372. auto socket_fd = TRY(System::socket(AF_LOCAL, SOCK_STREAM, 0));
  373. int option = 1;
  374. TRY(System::ioctl(socket_fd, FIONBIO, &option));
  375. TRY(System::fcntl(socket_fd, F_SETFD, FD_CLOEXEC));
  376. #endif
  377. #if !defined(AK_OS_BSD_GENERIC) && !defined(AK_OS_GNU_HURD)
  378. TRY(System::fchmod(socket_fd, 0600));
  379. #endif
  380. auto socket_address = SocketAddress::local(socket_path);
  381. auto socket_address_un = socket_address.to_sockaddr_un().release_value();
  382. TRY(System::bind(socket_fd, reinterpret_cast<sockaddr*>(&socket_address_un), sizeof(socket_address_un)));
  383. TRY(System::listen(socket_fd, 16));
  384. return socket_fd;
  385. }
  386. struct ProcessPaths {
  387. ByteString socket_path;
  388. ByteString pid_path;
  389. };
  390. static ErrorOr<ProcessPaths> paths_for_process(StringView process_name)
  391. {
  392. auto runtime_directory = TRY(StandardPaths::runtime_directory());
  393. auto socket_path = ByteString::formatted("{}/{}.socket", runtime_directory, process_name);
  394. auto pid_path = ByteString::formatted("{}/{}.pid", runtime_directory, process_name);
  395. return ProcessPaths { move(socket_path), move(pid_path) };
  396. }
  397. ErrorOr<IPCProcess::ProcessAndIPCSocket> IPCProcess::spawn_singleton_and_connect_to_process(ProcessSpawnOptions const& options)
  398. {
  399. auto [socket_path, pid_path] = TRY(paths_for_process(options.name));
  400. Process process { -1 };
  401. if (auto existing_pid = TRY(get_process_pid(options.name, pid_path)); existing_pid.has_value()) {
  402. process = Process { *existing_pid };
  403. } else {
  404. auto ipc_fd = TRY(create_ipc_socket(socket_path));
  405. sigset_t original_set;
  406. sigset_t setting_set;
  407. sigfillset(&setting_set);
  408. (void)pthread_sigmask(SIG_BLOCK, &setting_set, &original_set);
  409. // FIXME: Roll this daemon implementation into `Process::disown`.
  410. if (auto pid = TRY(System::fork()); pid == 0) {
  411. (void)pthread_sigmask(SIG_SETMASK, &original_set, nullptr);
  412. TRY(System::setsid());
  413. TRY(System::signal(SIGCHLD, SIG_IGN));
  414. auto& arguments = const_cast<Vector<ByteString>&>(options.arguments);
  415. arguments.append("--pid-file"sv);
  416. arguments.append(pid_path);
  417. auto takeover_string = ByteString::formatted("{}:{}", options.name, TRY(System::dup(ipc_fd)));
  418. TRY(Environment::set("SOCKET_TAKEOVER"sv, takeover_string, Environment::Overwrite::Yes));
  419. auto process = TRY(Process::spawn(options));
  420. {
  421. auto pid_file = TRY(File::open(pid_path, File::OpenMode::Write));
  422. TRY(pid_file->write_until_depleted(ByteString::number(process.pid())));
  423. }
  424. TRY(System::kill(getpid(), SIGTERM));
  425. } else {
  426. auto wait_err = System::waitpid(pid);
  427. (void)pthread_sigmask(SIG_SETMASK, &original_set, nullptr);
  428. TRY(wait_err);
  429. }
  430. auto pid = TRY(get_process_pid(options.name, pid_path));
  431. VERIFY(pid.has_value());
  432. process = Process { *pid };
  433. }
  434. auto ipc_socket = TRY(LocalSocket::connect(socket_path));
  435. TRY(ipc_socket->set_blocking(true));
  436. return ProcessAndIPCSocket { move(process), move(ipc_socket) };
  437. }
  438. }