Process.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <andreas@ladybird.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/System.h>
  17. #include <errno.h>
  18. #include <signal.h>
  19. #include <spawn.h>
  20. #include <unistd.h>
  21. #if defined(AK_OS_SERENITY)
  22. # include <serenity.h>
  23. # include <sys/prctl.h>
  24. # include <syscall.h>
  25. #elif defined(AK_OS_BSD_GENERIC) && !defined(AK_OS_SOLARIS)
  26. # include <sys/sysctl.h>
  27. #elif defined(AK_OS_GNU_HURD)
  28. extern "C" {
  29. # include <hurd.h>
  30. }
  31. #endif
  32. #if defined(AK_OS_FREEBSD)
  33. # include <sys/user.h>
  34. #endif
  35. namespace Core {
  36. struct ArgvList {
  37. ByteString m_path;
  38. Vector<char const*, 10> m_argv;
  39. ArgvList(ByteString path, size_t size)
  40. : m_path { path }
  41. {
  42. m_argv.ensure_capacity(size + 2);
  43. m_argv.append(m_path.characters());
  44. }
  45. void append(char const* arg)
  46. {
  47. m_argv.append(arg);
  48. }
  49. Span<char const*> get()
  50. {
  51. if (m_argv.is_empty() || m_argv.last() != nullptr)
  52. m_argv.append(nullptr);
  53. return m_argv;
  54. }
  55. };
  56. Process::Process(Process&& other)
  57. : m_pid(exchange(other.m_pid, 0))
  58. , m_should_disown(exchange(other.m_should_disown, false))
  59. {
  60. }
  61. Process& Process::operator=(Process&& other)
  62. {
  63. m_pid = exchange(other.m_pid, 0);
  64. m_should_disown = exchange(other.m_should_disown, false);
  65. return *this;
  66. }
  67. Process::~Process()
  68. {
  69. (void)disown();
  70. }
  71. Process Process::current()
  72. {
  73. auto p = Process { getpid() };
  74. p.m_should_disown = false;
  75. return p;
  76. }
  77. ErrorOr<Process> Process::spawn(ProcessSpawnOptions const& options)
  78. {
  79. #define CHECK(invocation) \
  80. if (int returned_errno = (invocation)) \
  81. return Error::from_errno(returned_errno);
  82. posix_spawn_file_actions_t spawn_actions;
  83. CHECK(posix_spawn_file_actions_init(&spawn_actions));
  84. ScopeGuard cleanup_spawn_actions = [&] {
  85. posix_spawn_file_actions_destroy(&spawn_actions);
  86. };
  87. if (options.working_directory.has_value()) {
  88. #ifdef AK_OS_SERENITY
  89. CHECK(posix_spawn_file_actions_addchdir(&spawn_actions, options.working_directory->characters()));
  90. #else
  91. // FIXME: Support ProcessSpawnOptions::working_directory n platforms that support it.
  92. TODO();
  93. #endif
  94. }
  95. for (auto const& file_action : options.file_actions) {
  96. TRY(file_action.visit(
  97. [&](FileAction::OpenFile const& action) -> ErrorOr<void> {
  98. CHECK(posix_spawn_file_actions_addopen(
  99. &spawn_actions,
  100. action.fd,
  101. action.path.characters(),
  102. File::open_mode_to_options(action.mode | Core::File::OpenMode::KeepOnExec),
  103. action.permissions));
  104. return {};
  105. },
  106. [&](FileAction::CloseFile const& action) -> ErrorOr<void> {
  107. CHECK(posix_spawn_file_actions_addclose(&spawn_actions, action.fd));
  108. return {};
  109. },
  110. [&](FileAction::DupFd const& action) -> ErrorOr<void> {
  111. CHECK(posix_spawn_file_actions_adddup2(&spawn_actions, action.write_fd, action.fd));
  112. return {};
  113. }));
  114. }
  115. #undef CHECK
  116. ArgvList argv_list(options.executable, options.arguments.size());
  117. for (auto const& argument : options.arguments)
  118. argv_list.append(argument.characters());
  119. pid_t pid;
  120. if (options.search_for_executable_in_path) {
  121. pid = TRY(System::posix_spawnp(options.executable.view(), &spawn_actions, nullptr, const_cast<char**>(argv_list.get().data()), Core::Environment::raw_environ()));
  122. } else {
  123. pid = TRY(System::posix_spawn(options.executable.view(), &spawn_actions, nullptr, const_cast<char**>(argv_list.get().data()), Core::Environment::raw_environ()));
  124. }
  125. return Process { pid };
  126. }
  127. ErrorOr<Process> Process::spawn(StringView path, ReadonlySpan<ByteString> arguments, ByteString working_directory, KeepAsChild keep_as_child)
  128. {
  129. auto process = TRY(spawn({
  130. .executable = path,
  131. .arguments = Vector<ByteString> { arguments },
  132. .working_directory = working_directory.is_empty() ? Optional<ByteString> {} : Optional<ByteString> { working_directory },
  133. }));
  134. if (keep_as_child == KeepAsChild::No)
  135. TRY(process.disown());
  136. return process;
  137. }
  138. ErrorOr<Process> Process::spawn(StringView path, ReadonlySpan<StringView> arguments, ByteString working_directory, KeepAsChild keep_as_child)
  139. {
  140. Vector<ByteString> backing_strings;
  141. backing_strings.ensure_capacity(arguments.size());
  142. for (auto const& argument : arguments)
  143. backing_strings.append(argument);
  144. auto process = TRY(spawn({
  145. .executable = path,
  146. .arguments = backing_strings,
  147. .working_directory = working_directory.is_empty() ? Optional<ByteString> {} : Optional<ByteString> { working_directory },
  148. }));
  149. if (keep_as_child == KeepAsChild::No)
  150. TRY(process.disown());
  151. return process;
  152. }
  153. ErrorOr<String> Process::get_name()
  154. {
  155. #if defined(AK_OS_SERENITY)
  156. char buffer[BUFSIZ];
  157. int rc = get_process_name(buffer, BUFSIZ);
  158. if (rc != 0)
  159. return Error::from_syscall("get_process_name"sv, -rc);
  160. return String::from_utf8(StringView { buffer, strlen(buffer) });
  161. #elif defined(AK_LIBC_GLIBC) || (defined(AK_OS_LINUX) && !defined(AK_OS_ANDROID))
  162. return String::from_utf8(StringView { program_invocation_name, strlen(program_invocation_name) });
  163. #elif defined(AK_OS_BSD_GENERIC) || defined(AK_OS_HAIKU)
  164. auto const* progname = getprogname();
  165. return String::from_utf8(StringView { progname, strlen(progname) });
  166. #else
  167. // FIXME: Implement Process::get_name() for other platforms.
  168. return "???"_string;
  169. #endif
  170. }
  171. ErrorOr<void> Process::set_name([[maybe_unused]] StringView name, [[maybe_unused]] SetThreadName set_thread_name)
  172. {
  173. #if defined(AK_OS_SERENITY)
  174. int rc = set_process_name(name.characters_without_null_termination(), name.length());
  175. if (rc != 0)
  176. return Error::from_syscall("set_process_name"sv, -rc);
  177. if (set_thread_name == SetThreadName::No)
  178. return {};
  179. rc = prctl(PR_SET_THREAD_NAME, gettid(), name.characters_without_null_termination(), name.length());
  180. if (rc != 0)
  181. return Error::from_syscall("set_thread_name"sv, -rc);
  182. return {};
  183. #else
  184. // FIXME: Implement Process::set_name() for other platforms.
  185. return {};
  186. #endif
  187. }
  188. ErrorOr<bool> Process::is_being_debugged()
  189. {
  190. #if defined(AK_OS_LINUX)
  191. auto unbuffered_status_file = TRY(Core::File::open("/proc/self/status"sv, Core::File::OpenMode::Read));
  192. auto status_file = TRY(Core::InputBufferedFile::create(move(unbuffered_status_file)));
  193. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  194. while (TRY(status_file->can_read_line())) {
  195. auto line = TRY(status_file->read_line(buffer));
  196. auto const parts = line.split_view(':');
  197. if (parts.size() < 2 || parts[0] != "TracerPid"sv)
  198. continue;
  199. auto tracer_pid = parts[1].to_number<u32>();
  200. return (tracer_pid != 0UL);
  201. }
  202. return false;
  203. #elif defined(AK_OS_GNU_HURD)
  204. process_t proc = getproc();
  205. if (!MACH_PORT_VALID(proc))
  206. return Error::from_syscall("getproc"sv, -errno);
  207. int flags = PI_FETCH_TASKINFO;
  208. // We're going to ask the proc server for the info about our process,
  209. // and it is going to reply, placing the info into a buffer. It can
  210. // either fill in (overwrite) the buffer we provide to it (called pi_buffer
  211. // below), or allocate (as if with mmap or vm_allocate) a new buffer.
  212. // The buffer is really of type struct procinfo[], but it's transferred
  213. // over IPC as int[]. We pass in a double pointer (int** pi_array) that
  214. // initially points to our pi_buffer, but the call will update it to
  215. // point to the newly allocated buffer if it ends up making one.
  216. struct procinfo pi_buffer = {};
  217. int* pi_array = reinterpret_cast<int*>(&pi_buffer);
  218. mach_msg_type_number_t pi_array_len = sizeof(pi_buffer) / sizeof(int);
  219. data_t waits = nullptr;
  220. mach_msg_type_number_t waits_len = 0;
  221. kern_return_t err = proc_getprocinfo(proc, getpid(), &flags, &pi_array, &pi_array_len, &waits, &waits_len);
  222. mach_port_deallocate(mach_task_self(), proc);
  223. if (err) {
  224. __hurd_fail(static_cast<error_t>(err));
  225. return Error::from_syscall("proc_getprocinfo"sv, -errno);
  226. }
  227. // Now cast the returned buffer pointer back to struct procinfo, and
  228. // read the info we're interested in (the PI_TRACED flag) from there.
  229. VERIFY(pi_array_len >= sizeof(struct procinfo));
  230. struct procinfo* procinfo = reinterpret_cast<struct procinfo*>(pi_array);
  231. bool traced = procinfo->state & PI_TRACED;
  232. // If the returned buffer is not the one we allocated on the stack,
  233. // we should unmap it.
  234. if (procinfo != &pi_buffer)
  235. (void)System::munmap(pi_array, pi_array_len * sizeof(int));
  236. if (waits)
  237. (void)System::munmap(waits, waits_len);
  238. return traced;
  239. #elif defined(AK_OS_MACOS) || defined(AK_OS_FREEBSD)
  240. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  241. int mib[4] = {};
  242. struct kinfo_proc info = {};
  243. size_t size = sizeof(info);
  244. // Initialize mib, which tells sysctl the info we want, in this case
  245. // we're looking for information about a specific process ID.
  246. mib[0] = CTL_KERN;
  247. mib[1] = KERN_PROC;
  248. mib[2] = KERN_PROC_PID;
  249. mib[3] = getpid();
  250. if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0) < 0)
  251. return Error::from_syscall("sysctl"sv, -errno);
  252. // We're being debugged if the P_TRACED flag is set.
  253. # if defined(AK_OS_MACOS)
  254. return ((info.kp_proc.p_flag & P_TRACED) != 0);
  255. # elif defined(AK_OS_FREEBSD)
  256. return ((info.ki_flag & P_TRACED) != 0);
  257. # endif
  258. #endif
  259. // FIXME: Implement this for more platforms.
  260. return Error::from_string_literal("Platform does not support checking for debugger");
  261. }
  262. // Forces the process to sleep until a debugger is attached, then breaks.
  263. void Process::wait_for_debugger_and_break()
  264. {
  265. bool should_print_process_info { true };
  266. for (;;) {
  267. auto check = Process::is_being_debugged();
  268. if (check.is_error()) {
  269. dbgln("Cannot wait for debugger: {}. Continuing.", check.release_error());
  270. return;
  271. }
  272. if (check.value()) {
  273. kill(getpid(), SIGTRAP);
  274. return;
  275. }
  276. if (should_print_process_info) {
  277. dbgln("Process {} with pid {} is sleeping, waiting for debugger.", Process::get_name(), getpid());
  278. should_print_process_info = false;
  279. }
  280. ::usleep(100 * 1000);
  281. }
  282. }
  283. pid_t Process::pid() const
  284. {
  285. return m_pid;
  286. }
  287. ErrorOr<void> Process::disown()
  288. {
  289. if (m_pid != 0 && m_should_disown) {
  290. #ifdef AK_OS_SERENITY
  291. TRY(System::disown(m_pid));
  292. #else
  293. // FIXME: Support disown outside Serenity.
  294. #endif
  295. m_should_disown = false;
  296. return {};
  297. } else {
  298. return Error::from_errno(EINVAL);
  299. }
  300. }
  301. ErrorOr<int> Process::wait_for_termination()
  302. {
  303. VERIFY(m_pid > 0);
  304. int exit_code = -1;
  305. int status;
  306. if (waitpid(m_pid, &status, 0) == -1)
  307. return Error::from_syscall("waitpid"sv, -errno);
  308. if (WIFEXITED(status)) {
  309. exit_code = WEXITSTATUS(status);
  310. } else if (WIFSIGNALED(status)) {
  311. exit_code = 128 + WTERMSIG(status);
  312. } else if (WIFSTOPPED(status)) {
  313. // This is only possible if the child process is being traced by us.
  314. VERIFY_NOT_REACHED();
  315. } else {
  316. VERIFY_NOT_REACHED();
  317. }
  318. m_should_disown = false;
  319. return exit_code;
  320. }
  321. }