Process.cpp 16 KB

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