Process.cpp 12 KB

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