Process.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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/DeprecatedString.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. DeprecatedString m_path;
  35. DeprecatedString m_working_directory;
  36. Vector<char const*, 10> m_argv;
  37. ArgvList(DeprecatedString path, size_t size)
  38. : m_path { path }
  39. {
  40. m_argv.ensure_capacity(size + 2);
  41. m_argv.append(m_path.characters());
  42. }
  43. void append(char const* arg)
  44. {
  45. m_argv.append(arg);
  46. }
  47. Span<char const*> get()
  48. {
  49. if (m_argv.is_empty() || m_argv.last() != nullptr)
  50. m_argv.append(nullptr);
  51. return m_argv;
  52. }
  53. void set_working_directory(DeprecatedString const& working_directory)
  54. {
  55. m_working_directory = working_directory;
  56. }
  57. ErrorOr<pid_t> spawn(Process::KeepAsChild keep_as_child)
  58. {
  59. #ifdef AK_OS_SERENITY
  60. posix_spawn_file_actions_t spawn_actions;
  61. posix_spawn_file_actions_init(&spawn_actions);
  62. ScopeGuard cleanup_spawn_actions = [&] {
  63. posix_spawn_file_actions_destroy(&spawn_actions);
  64. };
  65. if (!m_working_directory.is_empty())
  66. posix_spawn_file_actions_addchdir(&spawn_actions, m_working_directory.characters());
  67. auto pid = TRY(System::posix_spawn(m_path.view(), &spawn_actions, nullptr, const_cast<char**>(get().data()), System::environment()));
  68. if (keep_as_child == Process::KeepAsChild::No)
  69. TRY(System::disown(pid));
  70. #else
  71. auto pid = TRY(System::posix_spawn(m_path.view(), nullptr, nullptr, const_cast<char**>(get().data()), System::environment()));
  72. // FIXME: Support keep_as_child outside Serenity.
  73. (void)keep_as_child;
  74. #endif
  75. return pid;
  76. }
  77. };
  78. ErrorOr<pid_t> Process::spawn(StringView path, ReadonlySpan<DeprecatedString> arguments, DeprecatedString working_directory, KeepAsChild keep_as_child)
  79. {
  80. ArgvList argv { path, arguments.size() };
  81. for (auto const& arg : arguments)
  82. argv.append(arg.characters());
  83. argv.set_working_directory(working_directory);
  84. return argv.spawn(keep_as_child);
  85. }
  86. ErrorOr<pid_t> Process::spawn(StringView path, ReadonlySpan<StringView> arguments, DeprecatedString working_directory, KeepAsChild keep_as_child)
  87. {
  88. Vector<DeprecatedString> backing_strings;
  89. backing_strings.ensure_capacity(arguments.size());
  90. ArgvList argv { path, arguments.size() };
  91. for (auto const& arg : arguments) {
  92. backing_strings.append(arg);
  93. argv.append(backing_strings.last().characters());
  94. }
  95. argv.set_working_directory(working_directory);
  96. return argv.spawn(keep_as_child);
  97. }
  98. ErrorOr<pid_t> Process::spawn(StringView path, ReadonlySpan<char const*> arguments, DeprecatedString working_directory, KeepAsChild keep_as_child)
  99. {
  100. ArgvList argv { path, arguments.size() };
  101. for (auto arg : arguments)
  102. argv.append(arg);
  103. argv.set_working_directory(working_directory);
  104. return argv.spawn(keep_as_child);
  105. }
  106. ErrorOr<String> Process::get_name()
  107. {
  108. #if defined(AK_OS_SERENITY)
  109. char buffer[BUFSIZ];
  110. int rc = get_process_name(buffer, BUFSIZ);
  111. if (rc != 0)
  112. return Error::from_syscall("get_process_name"sv, -rc);
  113. return String::from_utf8(StringView { buffer, strlen(buffer) });
  114. #elif defined(AK_LIBC_GLIBC) || (defined(AK_OS_LINUX) && !defined(AK_OS_ANDROID))
  115. return String::from_utf8(StringView { program_invocation_name, strlen(program_invocation_name) });
  116. #elif defined(AK_OS_BSD_GENERIC) || defined(AK_OS_HAIKU)
  117. auto const* progname = getprogname();
  118. return String::from_utf8(StringView { progname, strlen(progname) });
  119. #else
  120. // FIXME: Implement Process::get_name() for other platforms.
  121. return "???"_string;
  122. #endif
  123. }
  124. ErrorOr<void> Process::set_name([[maybe_unused]] StringView name, [[maybe_unused]] SetThreadName set_thread_name)
  125. {
  126. #if defined(AK_OS_SERENITY)
  127. int rc = set_process_name(name.characters_without_null_termination(), name.length());
  128. if (rc != 0)
  129. return Error::from_syscall("set_process_name"sv, -rc);
  130. if (set_thread_name == SetThreadName::No)
  131. return {};
  132. rc = prctl(PR_SET_THREAD_NAME, gettid(), name.characters_without_null_termination(), name.length());
  133. if (rc != 0)
  134. return Error::from_syscall("set_thread_name"sv, -rc);
  135. return {};
  136. #else
  137. // FIXME: Implement Process::set_name() for other platforms.
  138. return {};
  139. #endif
  140. }
  141. ErrorOr<bool> Process::is_being_debugged()
  142. {
  143. #if defined(AK_OS_LINUX)
  144. auto unbuffered_status_file = TRY(Core::File::open("/proc/self/status"sv, Core::File::OpenMode::Read));
  145. auto status_file = TRY(Core::InputBufferedFile::create(move(unbuffered_status_file)));
  146. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  147. while (TRY(status_file->can_read_line())) {
  148. auto line = TRY(status_file->read_line(buffer));
  149. auto const parts = line.split_view(':');
  150. if (parts.size() < 2 || parts[0] != "TracerPid"sv)
  151. continue;
  152. auto tracer_pid = parts[1].to_uint<u32>();
  153. return (tracer_pid != 0UL);
  154. }
  155. return false;
  156. #elif defined(AK_OS_GNU_HURD)
  157. process_t proc = getproc();
  158. if (!MACH_PORT_VALID(proc))
  159. return Error::from_syscall("getproc"sv, -errno);
  160. int flags = PI_FETCH_TASKINFO;
  161. // We're going to ask the proc server for the info about our process,
  162. // and it is going to reply, placing the info into a buffer. It can
  163. // either fill in (overwrite) the buffer we provide to it (called pi_buffer
  164. // below), or allocate (as if with mmap or vm_allocate) a new buffer.
  165. // The buffer is really of type struct procinfo[], but it's transferred
  166. // over IPC as int[]. We pass in a double pointer (int** pi_array) that
  167. // initially points to our pi_buffer, but the call will update it to
  168. // point to the newly allocated buffer if it ends up making one.
  169. struct procinfo pi_buffer = {};
  170. int* pi_array = reinterpret_cast<int*>(&pi_buffer);
  171. mach_msg_type_number_t pi_array_len = sizeof(pi_buffer) / sizeof(int);
  172. data_t waits = nullptr;
  173. mach_msg_type_number_t waits_len = 0;
  174. kern_return_t err = proc_getprocinfo(proc, getpid(), &flags, &pi_array, &pi_array_len, &waits, &waits_len);
  175. mach_port_deallocate(mach_task_self(), proc);
  176. if (err) {
  177. __hurd_fail(static_cast<error_t>(err));
  178. return Error::from_syscall("proc_getprocinfo"sv, -errno);
  179. }
  180. // Now cast the returned buffer pointer back to struct procinfo, and
  181. // read the info we're interested in (the PI_TRACED flag) from there.
  182. VERIFY(pi_array_len >= sizeof(struct procinfo));
  183. struct procinfo* procinfo = reinterpret_cast<struct procinfo*>(pi_array);
  184. bool traced = procinfo->state & PI_TRACED;
  185. // If the returned buffer is not the one we allocated on the stack,
  186. // we should unmap it.
  187. if (procinfo != &pi_buffer)
  188. (void)System::munmap(pi_array, pi_array_len * sizeof(int));
  189. if (waits)
  190. (void)System::munmap(waits, waits_len);
  191. return traced;
  192. #elif defined(AK_OS_MACOS) || defined(AK_OS_FREEBSD)
  193. // https://developer.apple.com/library/archive/qa/qa1361/_index.html
  194. int mib[4] = {};
  195. struct kinfo_proc info = {};
  196. size_t size = sizeof(info);
  197. // Initialize mib, which tells sysctl the info we want, in this case
  198. // we're looking for information about a specific process ID.
  199. mib[0] = CTL_KERN;
  200. mib[1] = KERN_PROC;
  201. mib[2] = KERN_PROC_PID;
  202. mib[3] = getpid();
  203. if (sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0) < 0)
  204. return Error::from_syscall("sysctl"sv, -errno);
  205. // We're being debugged if the P_TRACED flag is set.
  206. # if defined(AK_OS_MACOS)
  207. return ((info.kp_proc.p_flag & P_TRACED) != 0);
  208. # elif defined(AK_OS_FREEBSD)
  209. return ((info.ki_flag & P_TRACED) != 0);
  210. # endif
  211. #endif
  212. // FIXME: Implement this for more platforms.
  213. return Error::from_string_view("Platform does not support checking for debugger"sv);
  214. }
  215. // Forces the process to sleep until a debugger is attached, then breaks.
  216. void Process::wait_for_debugger_and_break()
  217. {
  218. bool should_print_process_info { true };
  219. for (;;) {
  220. auto check = Process::is_being_debugged();
  221. if (check.is_error()) {
  222. dbgln("Cannot wait for debugger: {}. Continuing.", check.release_error());
  223. return;
  224. }
  225. if (check.value()) {
  226. kill(getpid(), SIGTRAP);
  227. return;
  228. }
  229. if (should_print_process_info) {
  230. dbgln("Process {} with pid {} is sleeping, waiting for debugger.", Process::get_name(), getpid());
  231. should_print_process_info = false;
  232. }
  233. ::usleep(100 * 1000);
  234. }
  235. }
  236. }