execve.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/ScopeGuard.h>
  8. #include <AK/TemporaryChange.h>
  9. #include <AK/WeakPtr.h>
  10. #include <Kernel/Debug.h>
  11. #include <Kernel/FileSystem/Custody.h>
  12. #include <Kernel/FileSystem/OpenFileDescription.h>
  13. #include <Kernel/Memory/AllocationStrategy.h>
  14. #include <Kernel/Memory/MemoryManager.h>
  15. #include <Kernel/Memory/PageDirectory.h>
  16. #include <Kernel/Memory/Region.h>
  17. #include <Kernel/Memory/SharedInodeVMObject.h>
  18. #include <Kernel/Panic.h>
  19. #include <Kernel/PerformanceManager.h>
  20. #include <Kernel/Process.h>
  21. #include <Kernel/Random.h>
  22. #include <Kernel/Scheduler.h>
  23. #include <Kernel/Time/TimeManagement.h>
  24. #include <LibC/limits.h>
  25. #include <LibELF/AuxiliaryVector.h>
  26. #include <LibELF/Image.h>
  27. #include <LibELF/Validation.h>
  28. namespace Kernel {
  29. extern Memory::Region* g_signal_trampoline_region;
  30. struct LoadResult {
  31. OwnPtr<Memory::AddressSpace> space;
  32. FlatPtr load_base { 0 };
  33. FlatPtr entry_eip { 0 };
  34. size_t size { 0 };
  35. WeakPtr<Memory::Region> tls_region;
  36. size_t tls_size { 0 };
  37. size_t tls_alignment { 0 };
  38. WeakPtr<Memory::Region> stack_region;
  39. };
  40. static constexpr size_t auxiliary_vector_size = 15;
  41. static Array<ELF::AuxiliaryValue, auxiliary_vector_size> generate_auxiliary_vector(FlatPtr load_base, FlatPtr entry_eip, UserID uid, UserID euid, GroupID gid, GroupID egid, StringView executable_path, Optional<Process::ScopedDescriptionAllocation> const& main_program_fd_allocation);
  42. static bool validate_stack_size(NonnullOwnPtrVector<KString> const& arguments, NonnullOwnPtrVector<KString>& environment)
  43. {
  44. size_t total_arguments_size = 0;
  45. size_t total_environment_size = 0;
  46. for (auto const& a : arguments)
  47. total_arguments_size += a.length() + 1;
  48. for (auto const& e : environment)
  49. total_environment_size += e.length() + 1;
  50. total_arguments_size += sizeof(char*) * (arguments.size() + 1);
  51. total_environment_size += sizeof(char*) * (environment.size() + 1);
  52. constexpr size_t max_arguments_size = Thread::default_userspace_stack_size / 8;
  53. constexpr size_t max_environment_size = Thread::default_userspace_stack_size / 8;
  54. if (total_arguments_size > max_arguments_size)
  55. return false;
  56. if (total_environment_size > max_environment_size)
  57. return false;
  58. // FIXME: This doesn't account for the size of the auxiliary vector
  59. return true;
  60. }
  61. static ErrorOr<FlatPtr> make_userspace_context_for_main_thread([[maybe_unused]] ThreadRegisters& regs, Memory::Region& region, NonnullOwnPtrVector<KString> const& arguments,
  62. NonnullOwnPtrVector<KString> const& environment, Array<ELF::AuxiliaryValue, auxiliary_vector_size> auxiliary_values)
  63. {
  64. FlatPtr new_sp = region.range().end().get();
  65. // Add some bits of randomness to the user stack pointer.
  66. new_sp -= round_up_to_power_of_two(get_fast_random<u32>() % 4096, 16);
  67. auto push_on_new_stack = [&new_sp](FlatPtr value) {
  68. new_sp -= sizeof(FlatPtr);
  69. Userspace<FlatPtr*> stack_ptr = new_sp;
  70. auto result = copy_to_user(stack_ptr, &value);
  71. VERIFY(!result.is_error());
  72. };
  73. auto push_aux_value_on_new_stack = [&new_sp](auxv_t value) {
  74. new_sp -= sizeof(auxv_t);
  75. Userspace<auxv_t*> stack_ptr = new_sp;
  76. auto result = copy_to_user(stack_ptr, &value);
  77. VERIFY(!result.is_error());
  78. };
  79. auto push_string_on_new_stack = [&new_sp](StringView string) {
  80. new_sp -= round_up_to_power_of_two(string.length() + 1, sizeof(FlatPtr));
  81. Userspace<FlatPtr*> stack_ptr = new_sp;
  82. auto result = copy_to_user(stack_ptr, string.characters_without_null_termination(), string.length() + 1);
  83. VERIFY(!result.is_error());
  84. };
  85. Vector<FlatPtr> argv_entries;
  86. for (auto const& argument : arguments) {
  87. push_string_on_new_stack(argument.view());
  88. TRY(argv_entries.try_append(new_sp));
  89. }
  90. Vector<FlatPtr> env_entries;
  91. for (auto const& variable : environment) {
  92. push_string_on_new_stack(variable.view());
  93. TRY(env_entries.try_append(new_sp));
  94. }
  95. for (auto& value : auxiliary_values) {
  96. if (!value.optional_string.is_empty()) {
  97. push_string_on_new_stack(value.optional_string);
  98. value.auxv.a_un.a_ptr = (void*)new_sp;
  99. }
  100. if (value.auxv.a_type == ELF::AuxiliaryValue::Random) {
  101. u8 random_bytes[16] {};
  102. get_fast_random_bytes({ random_bytes, sizeof(random_bytes) });
  103. push_string_on_new_stack({ random_bytes, sizeof(random_bytes) });
  104. value.auxv.a_un.a_ptr = (void*)new_sp;
  105. }
  106. }
  107. for (ssize_t i = auxiliary_values.size() - 1; i >= 0; --i) {
  108. auto& value = auxiliary_values[i];
  109. push_aux_value_on_new_stack(value.auxv);
  110. }
  111. push_on_new_stack(0);
  112. for (ssize_t i = env_entries.size() - 1; i >= 0; --i)
  113. push_on_new_stack(env_entries[i]);
  114. FlatPtr envp = new_sp;
  115. push_on_new_stack(0);
  116. for (ssize_t i = argv_entries.size() - 1; i >= 0; --i)
  117. push_on_new_stack(argv_entries[i]);
  118. FlatPtr argv = new_sp;
  119. // NOTE: The stack needs to be 16-byte aligned.
  120. new_sp -= new_sp % 16;
  121. #if ARCH(I386)
  122. // GCC assumes that the return address has been pushed to the stack when it enters the function,
  123. // so we need to reserve an extra pointer's worth of bytes below this to make GCC's stack alignment
  124. // calculations work
  125. new_sp -= sizeof(void*);
  126. push_on_new_stack(envp);
  127. push_on_new_stack(argv);
  128. push_on_new_stack(argv_entries.size());
  129. #else
  130. regs.rdi = argv_entries.size();
  131. regs.rsi = argv;
  132. regs.rdx = envp;
  133. #endif
  134. VERIFY(new_sp % 16 == 0);
  135. // FIXME: The way we're setting up the stack and passing arguments to the entry point isn't ABI-compliant
  136. return new_sp;
  137. }
  138. struct RequiredLoadRange {
  139. FlatPtr start { 0 };
  140. FlatPtr end { 0 };
  141. };
  142. static ErrorOr<RequiredLoadRange> get_required_load_range(OpenFileDescription& program_description)
  143. {
  144. auto& inode = *(program_description.inode());
  145. auto vmobject = TRY(Memory::SharedInodeVMObject::try_create_with_inode(inode));
  146. size_t executable_size = inode.size();
  147. size_t rounded_executable_size = TRY(Memory::page_round_up(executable_size));
  148. auto region = TRY(MM.allocate_kernel_region_with_vmobject(*vmobject, rounded_executable_size, "ELF memory range calculation", Memory::Region::Access::Read));
  149. auto elf_image = ELF::Image(region->vaddr().as_ptr(), executable_size);
  150. if (!elf_image.is_valid()) {
  151. return EINVAL;
  152. }
  153. RequiredLoadRange range {};
  154. elf_image.for_each_program_header([&range](const auto& pheader) {
  155. if (pheader.type() != PT_LOAD)
  156. return;
  157. auto region_start = (FlatPtr)pheader.vaddr().as_ptr();
  158. auto region_end = region_start + pheader.size_in_memory();
  159. if (range.start == 0 || region_start < range.start)
  160. range.start = region_start;
  161. if (range.end == 0 || region_end > range.end)
  162. range.end = region_end;
  163. });
  164. VERIFY(range.end > range.start);
  165. return range;
  166. };
  167. static ErrorOr<FlatPtr> get_load_offset(const ElfW(Ehdr) & main_program_header, OpenFileDescription& main_program_description, OpenFileDescription* interpreter_description)
  168. {
  169. constexpr FlatPtr load_range_start = 0x08000000;
  170. constexpr FlatPtr load_range_size = 65536 * PAGE_SIZE; // 2**16 * PAGE_SIZE = 256MB
  171. constexpr FlatPtr minimum_load_offset_randomization_size = 10 * MiB;
  172. auto random_load_offset_in_range([](auto start, auto size) {
  173. return Memory::page_round_down(start + get_good_random<FlatPtr>() % size);
  174. });
  175. if (main_program_header.e_type == ET_DYN) {
  176. return random_load_offset_in_range(load_range_start, load_range_size);
  177. }
  178. if (main_program_header.e_type != ET_EXEC)
  179. return EINVAL;
  180. auto main_program_load_range = TRY(get_required_load_range(main_program_description));
  181. RequiredLoadRange selected_range {};
  182. if (interpreter_description) {
  183. auto interpreter_load_range = TRY(get_required_load_range(*interpreter_description));
  184. auto interpreter_size_in_memory = interpreter_load_range.end - interpreter_load_range.start;
  185. auto interpreter_load_range_end = load_range_start + load_range_size - interpreter_size_in_memory;
  186. // No intersection
  187. if (main_program_load_range.end < load_range_start || main_program_load_range.start > interpreter_load_range_end)
  188. return random_load_offset_in_range(load_range_start, load_range_size);
  189. RequiredLoadRange first_available_part = { load_range_start, main_program_load_range.start };
  190. RequiredLoadRange second_available_part = { main_program_load_range.end, interpreter_load_range_end };
  191. // Select larger part
  192. if (first_available_part.end - first_available_part.start > second_available_part.end - second_available_part.start)
  193. selected_range = first_available_part;
  194. else
  195. selected_range = second_available_part;
  196. } else
  197. selected_range = main_program_load_range;
  198. // If main program is too big and leaves us without enough space for adequate loader randomization
  199. if (selected_range.end - selected_range.start < minimum_load_offset_randomization_size)
  200. return E2BIG;
  201. return random_load_offset_in_range(selected_range.start, selected_range.end - selected_range.start);
  202. }
  203. enum class ShouldAllocateTls {
  204. No,
  205. Yes,
  206. };
  207. enum class ShouldAllowSyscalls {
  208. No,
  209. Yes,
  210. };
  211. static ErrorOr<LoadResult> load_elf_object(NonnullOwnPtr<Memory::AddressSpace> new_space, OpenFileDescription& object_description,
  212. FlatPtr load_offset, ShouldAllocateTls should_allocate_tls, ShouldAllowSyscalls should_allow_syscalls)
  213. {
  214. auto& inode = *(object_description.inode());
  215. auto vmobject = TRY(Memory::SharedInodeVMObject::try_create_with_inode(inode));
  216. if (vmobject->writable_mappings()) {
  217. dbgln("Refusing to execute a write-mapped program");
  218. return ETXTBSY;
  219. }
  220. size_t executable_size = inode.size();
  221. size_t rounded_executable_size = TRY(Memory::page_round_up(executable_size));
  222. auto executable_region = TRY(MM.allocate_kernel_region_with_vmobject(*vmobject, rounded_executable_size, "ELF loading", Memory::Region::Access::Read));
  223. auto elf_image = ELF::Image(executable_region->vaddr().as_ptr(), executable_size);
  224. if (!elf_image.is_valid())
  225. return ENOEXEC;
  226. Memory::Region* master_tls_region { nullptr };
  227. size_t master_tls_size = 0;
  228. size_t master_tls_alignment = 0;
  229. FlatPtr load_base_address = 0;
  230. auto elf_name = TRY(object_description.pseudo_path());
  231. VERIFY(!Processor::in_critical());
  232. Memory::MemoryManager::enter_address_space(*new_space);
  233. auto load_tls_section = [&](auto& program_header) -> ErrorOr<void> {
  234. VERIFY(should_allocate_tls == ShouldAllocateTls::Yes);
  235. VERIFY(program_header.size_in_memory());
  236. if (!elf_image.is_within_image(program_header.raw_data(), program_header.size_in_image())) {
  237. dbgln("Shenanigans! ELF PT_TLS header sneaks outside of executable.");
  238. return ENOEXEC;
  239. }
  240. auto range = TRY(new_space->try_allocate_range({}, program_header.size_in_memory()));
  241. auto region_name = TRY(KString::formatted("{} (master-tls)", elf_name));
  242. master_tls_region = TRY(new_space->allocate_region(range, region_name->view(), PROT_READ | PROT_WRITE, AllocationStrategy::Reserve));
  243. master_tls_size = program_header.size_in_memory();
  244. master_tls_alignment = program_header.alignment();
  245. TRY(copy_to_user(master_tls_region->vaddr().as_ptr(), program_header.raw_data(), program_header.size_in_image()));
  246. return {};
  247. };
  248. auto load_writable_section = [&](auto& program_header) -> ErrorOr<void> {
  249. // Writable section: create a copy in memory.
  250. VERIFY(program_header.alignment() % PAGE_SIZE == 0);
  251. if (!elf_image.is_within_image(program_header.raw_data(), program_header.size_in_image())) {
  252. dbgln("Shenanigans! Writable ELF PT_LOAD header sneaks outside of executable.");
  253. return ENOEXEC;
  254. }
  255. int prot = 0;
  256. if (program_header.is_readable())
  257. prot |= PROT_READ;
  258. if (program_header.is_writable())
  259. prot |= PROT_WRITE;
  260. auto region_name = TRY(KString::formatted("{} (data-{}{})", elf_name, program_header.is_readable() ? "r" : "", program_header.is_writable() ? "w" : ""));
  261. auto range_base = VirtualAddress { Memory::page_round_down(program_header.vaddr().offset(load_offset).get()) };
  262. size_t rounded_range_end = TRY(Memory::page_round_up(program_header.vaddr().offset(load_offset).offset(program_header.size_in_memory()).get()));
  263. auto range_end = VirtualAddress { rounded_range_end };
  264. auto range = TRY(new_space->try_allocate_range(range_base, range_end.get() - range_base.get(), program_header.alignment()));
  265. auto region = TRY(new_space->allocate_region(range, region_name->view(), prot, AllocationStrategy::Reserve));
  266. // It's not always the case with PIE executables (and very well shouldn't be) that the
  267. // virtual address in the program header matches the one we end up giving the process.
  268. // In order to copy the data image correctly into memory, we need to copy the data starting at
  269. // the right initial page offset into the pages allocated for the elf_alloc-XX section.
  270. // FIXME: There's an opportunity to munmap, or at least mprotect, the padding space between
  271. // the .text and .data PT_LOAD sections of the executable.
  272. // Accessing it would definitely be a bug.
  273. auto page_offset = program_header.vaddr();
  274. page_offset.mask(~PAGE_MASK);
  275. TRY(copy_to_user((u8*)region->vaddr().as_ptr() + page_offset.get(), program_header.raw_data(), program_header.size_in_image()));
  276. return {};
  277. };
  278. auto load_section = [&](auto& program_header) -> ErrorOr<void> {
  279. if (program_header.size_in_memory() == 0)
  280. return {};
  281. if (program_header.is_writable())
  282. return load_writable_section(program_header);
  283. // Non-writable section: map the executable itself in memory.
  284. VERIFY(program_header.alignment() % PAGE_SIZE == 0);
  285. int prot = 0;
  286. if (program_header.is_readable())
  287. prot |= PROT_READ;
  288. if (program_header.is_writable())
  289. prot |= PROT_WRITE;
  290. if (program_header.is_executable())
  291. prot |= PROT_EXEC;
  292. auto range_base = VirtualAddress { Memory::page_round_down(program_header.vaddr().offset(load_offset).get()) };
  293. size_t rounded_range_end = TRY(Memory::page_round_up(program_header.vaddr().offset(load_offset).offset(program_header.size_in_memory()).get()));
  294. auto range_end = VirtualAddress { rounded_range_end };
  295. auto range = TRY(new_space->try_allocate_range(range_base, range_end.get() - range_base.get(), program_header.alignment()));
  296. auto region = TRY(new_space->allocate_region_with_vmobject(range, *vmobject, program_header.offset(), elf_name->view(), prot, true));
  297. if (should_allow_syscalls == ShouldAllowSyscalls::Yes)
  298. region->set_syscall_region(true);
  299. if (program_header.offset() == 0)
  300. load_base_address = (FlatPtr)region->vaddr().as_ptr();
  301. return {};
  302. };
  303. auto load_elf_program_header = [&](auto& program_header) -> ErrorOr<void> {
  304. if (program_header.type() == PT_TLS)
  305. return load_tls_section(program_header);
  306. if (program_header.type() == PT_LOAD)
  307. return load_section(program_header);
  308. // NOTE: We ignore other program header types.
  309. return {};
  310. };
  311. TRY([&] {
  312. ErrorOr<void> result;
  313. elf_image.for_each_program_header([&](ELF::Image::ProgramHeader const& program_header) {
  314. result = load_elf_program_header(program_header);
  315. return result.is_error() ? IterationDecision::Break : IterationDecision::Continue;
  316. });
  317. return result;
  318. }());
  319. if (!elf_image.entry().offset(load_offset).get()) {
  320. dbgln("do_exec: Failure loading program, entry pointer is invalid! {})", elf_image.entry().offset(load_offset));
  321. return ENOEXEC;
  322. }
  323. auto stack_range = TRY(new_space->try_allocate_range({}, Thread::default_userspace_stack_size));
  324. auto* stack_region = TRY(new_space->allocate_region(stack_range, "Stack (Main thread)", PROT_READ | PROT_WRITE, AllocationStrategy::Reserve));
  325. stack_region->set_stack(true);
  326. return LoadResult {
  327. move(new_space),
  328. load_base_address,
  329. elf_image.entry().offset(load_offset).get(),
  330. executable_size,
  331. AK::try_make_weak_ptr(master_tls_region),
  332. master_tls_size,
  333. master_tls_alignment,
  334. stack_region->make_weak_ptr()
  335. };
  336. }
  337. ErrorOr<LoadResult>
  338. Process::load(NonnullRefPtr<OpenFileDescription> main_program_description,
  339. RefPtr<OpenFileDescription> interpreter_description, const ElfW(Ehdr) & main_program_header)
  340. {
  341. auto new_space = TRY(Memory::AddressSpace::try_create(nullptr));
  342. ScopeGuard space_guard([&]() {
  343. Memory::MemoryManager::enter_process_address_space(*this);
  344. });
  345. auto load_offset = TRY(get_load_offset(main_program_header, main_program_description, interpreter_description));
  346. if (interpreter_description.is_null()) {
  347. auto load_result = TRY(load_elf_object(move(new_space), main_program_description, load_offset, ShouldAllocateTls::Yes, ShouldAllowSyscalls::No));
  348. m_master_tls_region = load_result.tls_region;
  349. m_master_tls_size = load_result.tls_size;
  350. m_master_tls_alignment = load_result.tls_alignment;
  351. return load_result;
  352. }
  353. auto interpreter_load_result = TRY(load_elf_object(move(new_space), *interpreter_description, load_offset, ShouldAllocateTls::No, ShouldAllowSyscalls::Yes));
  354. // TLS allocation will be done in userspace by the loader
  355. VERIFY(!interpreter_load_result.tls_region);
  356. VERIFY(!interpreter_load_result.tls_alignment);
  357. VERIFY(!interpreter_load_result.tls_size);
  358. return interpreter_load_result;
  359. }
  360. ErrorOr<void> Process::do_exec(NonnullRefPtr<OpenFileDescription> main_program_description, NonnullOwnPtrVector<KString> arguments, NonnullOwnPtrVector<KString> environment,
  361. RefPtr<OpenFileDescription> interpreter_description, Thread*& new_main_thread, u32& prev_flags, const ElfW(Ehdr) & main_program_header)
  362. {
  363. VERIFY(is_user_process());
  364. VERIFY(!Processor::in_critical());
  365. // Although we *could* handle a pseudo_path here, trying to execute something that doesn't have
  366. // a custody (e.g. BlockDevice or RandomDevice) is pretty suspicious anyway.
  367. auto path = TRY(main_program_description->original_absolute_path());
  368. dbgln_if(EXEC_DEBUG, "do_exec: {}", path);
  369. // FIXME: How much stack space does process startup need?
  370. if (!validate_stack_size(arguments, environment))
  371. return E2BIG;
  372. // FIXME: split_view() currently allocates (Vector) without checking for failure.
  373. auto parts = path->view().split_view('/');
  374. if (parts.is_empty())
  375. return ENOENT;
  376. auto new_process_name = TRY(KString::try_create(parts.last()));
  377. auto new_main_thread_name = TRY(new_process_name->try_clone());
  378. auto load_result = TRY(load(main_program_description, interpreter_description, main_program_header));
  379. // NOTE: We don't need the interpreter executable description after this point.
  380. // We destroy it here to prevent it from getting destroyed when we return from this function.
  381. // That's important because when we're returning from this function, we're in a very delicate
  382. // state where we can't block (e.g by trying to acquire a mutex in description teardown.)
  383. bool has_interpreter = interpreter_description;
  384. interpreter_description = nullptr;
  385. auto signal_trampoline_range = TRY(load_result.space->try_allocate_range({}, PAGE_SIZE));
  386. auto* signal_trampoline_region = TRY(load_result.space->allocate_region_with_vmobject(signal_trampoline_range, g_signal_trampoline_region->vmobject(), 0, "Signal trampoline", PROT_READ | PROT_EXEC, true));
  387. signal_trampoline_region->set_syscall_region(true);
  388. // (For dynamically linked executable) Allocate an FD for passing the main executable to the dynamic loader.
  389. Optional<ScopedDescriptionAllocation> main_program_fd_allocation;
  390. if (has_interpreter)
  391. main_program_fd_allocation = TRY(allocate_fd());
  392. // We commit to the new executable at this point. There is no turning back!
  393. // Prevent other processes from attaching to us with ptrace while we're doing this.
  394. MutexLocker ptrace_locker(ptrace_lock());
  395. // Disable profiling temporarily in case it's running on this process.
  396. auto was_profiling = m_profiling;
  397. TemporaryChange profiling_disabler(m_profiling, false);
  398. kill_threads_except_self();
  399. bool executable_is_setid = false;
  400. if (!(main_program_description->custody()->mount_flags() & MS_NOSUID)) {
  401. auto main_program_metadata = main_program_description->metadata();
  402. if (main_program_metadata.is_setuid()) {
  403. executable_is_setid = true;
  404. ProtectedDataMutationScope scope { *this };
  405. m_protected_values.euid = main_program_metadata.uid;
  406. m_protected_values.suid = main_program_metadata.uid;
  407. }
  408. if (main_program_metadata.is_setgid()) {
  409. executable_is_setid = true;
  410. ProtectedDataMutationScope scope { *this };
  411. m_protected_values.egid = main_program_metadata.gid;
  412. m_protected_values.sgid = main_program_metadata.gid;
  413. }
  414. }
  415. set_dumpable(!executable_is_setid);
  416. // We make sure to enter the new address space before destroying the old one.
  417. // This ensures that the process always has a valid page directory.
  418. Memory::MemoryManager::enter_address_space(*load_result.space);
  419. m_space = load_result.space.release_nonnull();
  420. m_executable = main_program_description->custody();
  421. m_arguments = move(arguments);
  422. m_environment = move(environment);
  423. m_veil_state = VeilState::None;
  424. m_unveiled_paths.clear();
  425. m_unveiled_paths.set_metadata({ "/", UnveilAccess::None, false });
  426. for (auto& property : m_coredump_properties)
  427. property = {};
  428. auto* current_thread = Thread::current();
  429. current_thread->reset_signals_for_exec();
  430. clear_futex_queues_on_exec();
  431. m_fds.with_exclusive([&](auto& fds) {
  432. fds.change_each([&](auto& file_description_metadata) {
  433. if (file_description_metadata.is_valid() && file_description_metadata.flags() & FD_CLOEXEC)
  434. file_description_metadata = {};
  435. });
  436. });
  437. if (main_program_fd_allocation.has_value()) {
  438. main_program_description->set_readable(true);
  439. m_fds.with_exclusive([&](auto& fds) { fds[main_program_fd_allocation->fd].set(move(main_program_description), FD_CLOEXEC); });
  440. }
  441. new_main_thread = nullptr;
  442. if (&current_thread->process() == this) {
  443. new_main_thread = current_thread;
  444. } else {
  445. for_each_thread([&](auto& thread) {
  446. new_main_thread = &thread;
  447. return IterationDecision::Break;
  448. });
  449. }
  450. VERIFY(new_main_thread);
  451. auto auxv = generate_auxiliary_vector(load_result.load_base, load_result.entry_eip, uid(), euid(), gid(), egid(), path->view(), main_program_fd_allocation);
  452. // NOTE: We create the new stack before disabling interrupts since it will zero-fault
  453. // and we don't want to deal with faults after this point.
  454. auto new_userspace_sp = TRY(make_userspace_context_for_main_thread(new_main_thread->regs(), *load_result.stack_region.unsafe_ptr(), m_arguments, m_environment, move(auxv)));
  455. if (wait_for_tracer_at_next_execve()) {
  456. // Make sure we release the ptrace lock here or the tracer will block forever.
  457. ptrace_locker.unlock();
  458. Thread::current()->send_urgent_signal_to_self(SIGSTOP);
  459. } else {
  460. // Unlock regardless before disabling interrupts.
  461. // Ensure we always unlock after checking ptrace status to avoid TOCTOU ptrace issues
  462. ptrace_locker.unlock();
  463. }
  464. // We enter a critical section here because we don't want to get interrupted between do_exec()
  465. // and Processor::assume_context() or the next context switch.
  466. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  467. Processor::enter_critical();
  468. prev_flags = cpu_flags();
  469. cli();
  470. // NOTE: Be careful to not trigger any page faults below!
  471. m_name = move(new_process_name);
  472. new_main_thread->set_name(move(new_main_thread_name));
  473. {
  474. ProtectedDataMutationScope scope { *this };
  475. m_protected_values.promises = m_protected_values.execpromises.load();
  476. m_protected_values.has_promises = m_protected_values.has_execpromises.load();
  477. m_protected_values.execpromises = 0;
  478. m_protected_values.has_execpromises = false;
  479. m_protected_values.signal_trampoline = signal_trampoline_region->vaddr();
  480. // FIXME: PID/TID ISSUE
  481. m_protected_values.pid = new_main_thread->tid().value();
  482. }
  483. auto tsr_result = new_main_thread->make_thread_specific_region({});
  484. if (tsr_result.is_error()) {
  485. // FIXME: We cannot fail this late. Refactor this so the allocation happens before we commit to the new executable.
  486. VERIFY_NOT_REACHED();
  487. }
  488. new_main_thread->reset_fpu_state();
  489. auto& regs = new_main_thread->m_regs;
  490. #if ARCH(I386)
  491. regs.cs = GDT_SELECTOR_CODE3 | 3;
  492. regs.ds = GDT_SELECTOR_DATA3 | 3;
  493. regs.es = GDT_SELECTOR_DATA3 | 3;
  494. regs.ss = GDT_SELECTOR_DATA3 | 3;
  495. regs.fs = GDT_SELECTOR_DATA3 | 3;
  496. regs.gs = GDT_SELECTOR_TLS | 3;
  497. regs.eip = load_result.entry_eip;
  498. regs.esp = new_userspace_sp;
  499. #else
  500. regs.rip = load_result.entry_eip;
  501. regs.rsp = new_userspace_sp;
  502. #endif
  503. regs.cr3 = address_space().page_directory().cr3();
  504. {
  505. TemporaryChange profiling_disabler(m_profiling, was_profiling);
  506. PerformanceManager::add_process_exec_event(*this);
  507. }
  508. u32 lock_count_to_restore;
  509. [[maybe_unused]] auto rc = big_lock().force_unlock_exclusive_if_locked(lock_count_to_restore);
  510. VERIFY_INTERRUPTS_DISABLED();
  511. VERIFY(Processor::in_critical());
  512. return {};
  513. }
  514. static Array<ELF::AuxiliaryValue, auxiliary_vector_size> generate_auxiliary_vector(FlatPtr load_base, FlatPtr entry_eip, UserID uid, UserID euid, GroupID gid, GroupID egid, StringView executable_path, Optional<Process::ScopedDescriptionAllocation> const& main_program_fd_allocation)
  515. {
  516. return { {
  517. // PHDR/EXECFD
  518. // PH*
  519. { ELF::AuxiliaryValue::PageSize, PAGE_SIZE },
  520. { ELF::AuxiliaryValue::BaseAddress, (void*)load_base },
  521. { ELF::AuxiliaryValue::Entry, (void*)entry_eip },
  522. // NOTELF
  523. { ELF::AuxiliaryValue::Uid, (long)uid.value() },
  524. { ELF::AuxiliaryValue::EUid, (long)euid.value() },
  525. { ELF::AuxiliaryValue::Gid, (long)gid.value() },
  526. { ELF::AuxiliaryValue::EGid, (long)egid.value() },
  527. { ELF::AuxiliaryValue::Platform, Processor::platform_string() },
  528. // FIXME: This is platform specific
  529. { ELF::AuxiliaryValue::HwCap, (long)CPUID(1).edx() },
  530. { ELF::AuxiliaryValue::ClockTick, (long)TimeManagement::the().ticks_per_second() },
  531. // FIXME: Also take into account things like extended filesystem permissions? That's what linux does...
  532. { ELF::AuxiliaryValue::Secure, ((uid != euid) || (gid != egid)) ? 1 : 0 },
  533. { ELF::AuxiliaryValue::Random, nullptr },
  534. { ELF::AuxiliaryValue::ExecFilename, executable_path },
  535. main_program_fd_allocation.has_value() ? ELF::AuxiliaryValue { ELF::AuxiliaryValue::ExecFileDescriptor, main_program_fd_allocation->fd } : ELF::AuxiliaryValue { ELF::AuxiliaryValue::Ignore, 0L },
  536. { ELF::AuxiliaryValue::Null, 0L },
  537. } };
  538. }
  539. static ErrorOr<NonnullOwnPtrVector<KString>> find_shebang_interpreter_for_executable(char const first_page[], size_t nread)
  540. {
  541. int word_start = 2;
  542. size_t word_length = 0;
  543. if (nread > 2 && first_page[0] == '#' && first_page[1] == '!') {
  544. NonnullOwnPtrVector<KString> interpreter_words;
  545. for (size_t i = 2; i < nread; ++i) {
  546. if (first_page[i] == '\n') {
  547. break;
  548. }
  549. if (first_page[i] != ' ') {
  550. ++word_length;
  551. }
  552. if (first_page[i] == ' ') {
  553. if (word_length > 0) {
  554. auto word = TRY(KString::try_create(StringView { &first_page[word_start], word_length }));
  555. TRY(interpreter_words.try_append(move(word)));
  556. }
  557. word_length = 0;
  558. word_start = i + 1;
  559. }
  560. }
  561. if (word_length > 0) {
  562. auto word = TRY(KString::try_create(StringView { &first_page[word_start], word_length }));
  563. TRY(interpreter_words.try_append(move(word)));
  564. }
  565. if (!interpreter_words.is_empty())
  566. return interpreter_words;
  567. }
  568. return ENOEXEC;
  569. }
  570. ErrorOr<RefPtr<OpenFileDescription>> Process::find_elf_interpreter_for_executable(StringView path, ElfW(Ehdr) const& main_executable_header, size_t main_executable_header_size, size_t file_size)
  571. {
  572. // Not using ErrorOr here because we'll want to do the same thing in userspace in the RTLD
  573. StringBuilder interpreter_path_builder;
  574. if (!TRY(ELF::validate_program_headers(main_executable_header, file_size, { &main_executable_header, main_executable_header_size }, &interpreter_path_builder))) {
  575. dbgln("exec({}): File has invalid ELF Program headers", path);
  576. return ENOEXEC;
  577. }
  578. auto interpreter_path = interpreter_path_builder.string_view();
  579. if (!interpreter_path.is_empty()) {
  580. dbgln_if(EXEC_DEBUG, "exec({}): Using program interpreter {}", path, interpreter_path);
  581. auto interpreter_description = TRY(VirtualFileSystem::the().open(interpreter_path, O_EXEC, 0, current_directory()));
  582. auto interp_metadata = interpreter_description->metadata();
  583. VERIFY(interpreter_description->inode());
  584. // Validate the program interpreter as a valid elf binary.
  585. // If your program interpreter is a #! file or something, it's time to stop playing games :)
  586. if (interp_metadata.size < (int)sizeof(ElfW(Ehdr)))
  587. return ENOEXEC;
  588. char first_page[PAGE_SIZE] = {};
  589. auto first_page_buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)&first_page);
  590. auto nread = TRY(interpreter_description->read(first_page_buffer, sizeof(first_page)));
  591. if (nread < sizeof(ElfW(Ehdr)))
  592. return ENOEXEC;
  593. auto* elf_header = (ElfW(Ehdr)*)first_page;
  594. if (!ELF::validate_elf_header(*elf_header, interp_metadata.size)) {
  595. dbgln("exec({}): Interpreter ({}) has invalid ELF header", path, interpreter_path);
  596. return ENOEXEC;
  597. }
  598. // Not using ErrorOr here because we'll want to do the same thing in userspace in the RTLD
  599. StringBuilder interpreter_interpreter_path_builder;
  600. if (!TRY(ELF::validate_program_headers(*elf_header, interp_metadata.size, { first_page, nread }, &interpreter_interpreter_path_builder))) {
  601. dbgln("exec({}): Interpreter ({}) has invalid ELF Program headers", path, interpreter_path);
  602. return ENOEXEC;
  603. }
  604. auto interpreter_interpreter_path = interpreter_interpreter_path_builder.string_view();
  605. if (!interpreter_interpreter_path.is_empty()) {
  606. dbgln("exec({}): Interpreter ({}) has its own interpreter ({})! No thank you!", path, interpreter_path, interpreter_interpreter_path);
  607. return ELOOP;
  608. }
  609. return interpreter_description;
  610. }
  611. if (main_executable_header.e_type == ET_REL) {
  612. // We can't exec an ET_REL, that's just an object file from the compiler
  613. return ENOEXEC;
  614. }
  615. if (main_executable_header.e_type == ET_DYN) {
  616. // If it's ET_DYN with no PT_INTERP, then it's a dynamic executable responsible
  617. // for its own relocation (i.e. it's /usr/lib/Loader.so)
  618. if (path != "/usr/lib/Loader.so")
  619. dbgln("exec({}): WARNING - Dynamic ELF executable without a PT_INTERP header, and isn't /usr/lib/Loader.so", path);
  620. return nullptr;
  621. }
  622. // No interpreter, but, path refers to a valid elf image
  623. return nullptr;
  624. }
  625. ErrorOr<void> Process::exec(NonnullOwnPtr<KString> path, NonnullOwnPtrVector<KString> arguments, NonnullOwnPtrVector<KString> environment, Thread*& new_main_thread, u32& prev_flags, int recursion_depth)
  626. {
  627. if (recursion_depth > 2) {
  628. dbgln("exec({}): SHENANIGANS! recursed too far trying to find #! interpreter", path);
  629. return ELOOP;
  630. }
  631. // Open the file to check what kind of binary format it is
  632. // Currently supported formats:
  633. // - #! interpreted file
  634. // - ELF32
  635. // * ET_EXEC binary that just gets loaded
  636. // * ET_DYN binary that requires a program interpreter
  637. //
  638. auto description = TRY(VirtualFileSystem::the().open(path->view(), O_EXEC, 0, current_directory()));
  639. auto metadata = description->metadata();
  640. if (!metadata.is_regular_file())
  641. return EACCES;
  642. // Always gonna need at least 3 bytes. these are for #!X
  643. if (metadata.size < 3)
  644. return ENOEXEC;
  645. VERIFY(description->inode());
  646. // Read the first page of the program into memory so we can validate the binfmt of it
  647. char first_page[PAGE_SIZE];
  648. auto first_page_buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)&first_page);
  649. auto nread = TRY(description->read(first_page_buffer, sizeof(first_page)));
  650. // 1) #! interpreted file
  651. auto shebang_result = find_shebang_interpreter_for_executable(first_page, nread);
  652. if (!shebang_result.is_error()) {
  653. auto shebang_words = shebang_result.release_value();
  654. auto shebang_path = TRY(shebang_words.first().try_clone());
  655. arguments.ptr_at(0) = move(path);
  656. TRY(arguments.try_prepend(move(shebang_words)));
  657. return exec(move(shebang_path), move(arguments), move(environment), new_main_thread, prev_flags, ++recursion_depth);
  658. }
  659. // #2) ELF32 for i386
  660. if (nread < sizeof(ElfW(Ehdr)))
  661. return ENOEXEC;
  662. auto const* main_program_header = (ElfW(Ehdr)*)first_page;
  663. if (!ELF::validate_elf_header(*main_program_header, metadata.size)) {
  664. dbgln("exec({}): File has invalid ELF header", path);
  665. return ENOEXEC;
  666. }
  667. auto interpreter_description = TRY(find_elf_interpreter_for_executable(path->view(), *main_program_header, nread, metadata.size));
  668. return do_exec(move(description), move(arguments), move(environment), move(interpreter_description), new_main_thread, prev_flags, *main_program_header);
  669. }
  670. ErrorOr<FlatPtr> Process::sys$execve(Userspace<const Syscall::SC_execve_params*> user_params)
  671. {
  672. VERIFY_PROCESS_BIG_LOCK_ACQUIRED(this);
  673. TRY(require_promise(Pledge::exec));
  674. Thread* new_main_thread = nullptr;
  675. u32 prev_flags = 0;
  676. // NOTE: Be extremely careful with allocating any kernel memory in this function.
  677. // On success, the kernel stack will be lost.
  678. // The explicit block scope below is specifically placed to minimize the number
  679. // of stack locals in this function.
  680. {
  681. auto params = TRY(copy_typed_from_user(user_params));
  682. if (params.arguments.length > ARG_MAX || params.environment.length > ARG_MAX)
  683. return E2BIG;
  684. // NOTE: The caller is expected to always pass at least one argument by convention,
  685. // the program path that was passed as params.path.
  686. if (params.arguments.length == 0)
  687. return EINVAL;
  688. auto path = TRY(get_syscall_path_argument(params.path));
  689. auto copy_user_strings = [](const auto& list, auto& output) -> ErrorOr<void> {
  690. if (!list.length)
  691. return {};
  692. Checked<size_t> size = sizeof(*list.strings);
  693. size *= list.length;
  694. if (size.has_overflow())
  695. return EOVERFLOW;
  696. Vector<Syscall::StringArgument, 32> strings;
  697. TRY(strings.try_resize(list.length));
  698. TRY(copy_from_user(strings.data(), list.strings, size.value()));
  699. for (size_t i = 0; i < list.length; ++i) {
  700. auto string = TRY(try_copy_kstring_from_user(strings[i]));
  701. TRY(output.try_append(move(string)));
  702. }
  703. return {};
  704. };
  705. NonnullOwnPtrVector<KString> arguments;
  706. TRY(copy_user_strings(params.arguments, arguments));
  707. NonnullOwnPtrVector<KString> environment;
  708. TRY(copy_user_strings(params.environment, environment));
  709. TRY(exec(move(path), move(arguments), move(environment), new_main_thread, prev_flags));
  710. }
  711. // NOTE: If we're here, the exec has succeeded and we've got a new executable image!
  712. // We will not return normally from this function. Instead, the next time we
  713. // get scheduled, it'll be at the entry point of the new executable.
  714. VERIFY_INTERRUPTS_DISABLED();
  715. VERIFY(Processor::in_critical());
  716. auto* current_thread = Thread::current();
  717. if (current_thread == new_main_thread) {
  718. // We need to enter the scheduler lock before changing the state
  719. // and it will be released after the context switch into that
  720. // thread. We should also still be in our critical section
  721. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  722. VERIFY(Processor::in_critical() == 1);
  723. g_scheduler_lock.lock();
  724. current_thread->set_state(Thread::State::Running);
  725. Processor::assume_context(*current_thread, prev_flags);
  726. VERIFY_NOT_REACHED();
  727. }
  728. // NOTE: This code path is taken in the non-syscall case, i.e when the kernel spawns
  729. // a userspace process directly (such as /bin/SystemServer on startup)
  730. if (prev_flags & 0x200)
  731. sti();
  732. Processor::leave_critical();
  733. return 0;
  734. }
  735. }