execve.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/LexicalPath.h>
  27. #include <AK/ScopeGuard.h>
  28. #include <AK/TemporaryChange.h>
  29. #include <Kernel/FileSystem/Custody.h>
  30. #include <Kernel/FileSystem/FileDescription.h>
  31. #include <Kernel/Process.h>
  32. #include <Kernel/Profiling.h>
  33. #include <Kernel/Random.h>
  34. #include <Kernel/Time/TimeManagement.h>
  35. #include <Kernel/VM/AllocationStrategy.h>
  36. #include <Kernel/VM/MemoryManager.h>
  37. #include <Kernel/VM/PageDirectory.h>
  38. #include <Kernel/VM/Region.h>
  39. #include <Kernel/VM/SharedInodeVMObject.h>
  40. #include <LibC/limits.h>
  41. #include <LibELF/AuxiliaryVector.h>
  42. #include <LibELF/Image.h>
  43. #include <LibELF/Validation.h>
  44. //#define EXEC_DEBUG
  45. namespace Kernel {
  46. static Vector<ELF::AuxiliaryValue> generate_auxiliary_vector(FlatPtr load_base, FlatPtr entry_eip, uid_t uid, uid_t euid, gid_t gid, gid_t egid, String executable_path, int main_program_fd);
  47. static bool validate_stack_size(const Vector<String>& arguments, const Vector<String>& environment)
  48. {
  49. size_t total_blob_size = 0;
  50. for (auto& a : arguments)
  51. total_blob_size += a.length() + 1;
  52. for (auto& e : environment)
  53. total_blob_size += e.length() + 1;
  54. size_t total_meta_size = sizeof(char*) * (arguments.size() + 1) + sizeof(char*) * (environment.size() + 1);
  55. // FIXME: This doesn't account for the size of the auxiliary vector
  56. return (total_blob_size + total_meta_size) < Thread::default_userspace_stack_size;
  57. }
  58. static KResultOr<FlatPtr> make_userspace_stack_for_main_thread(Region& region, Vector<String> arguments, Vector<String> environment, Vector<ELF::AuxiliaryValue> auxiliary_values)
  59. {
  60. FlatPtr new_esp = region.vaddr().offset(Thread::default_userspace_stack_size).get();
  61. auto push_on_new_stack = [&new_esp](u32 value) {
  62. new_esp -= 4;
  63. Userspace<u32*> stack_ptr = new_esp;
  64. return copy_to_user(stack_ptr, &value);
  65. };
  66. auto push_aux_value_on_new_stack = [&new_esp](auxv_t value) {
  67. new_esp -= sizeof(auxv_t);
  68. Userspace<auxv_t*> stack_ptr = new_esp;
  69. return copy_to_user(stack_ptr, &value);
  70. };
  71. auto push_string_on_new_stack = [&new_esp](const String& string) {
  72. new_esp -= round_up_to_power_of_two(string.length() + 1, 4);
  73. Userspace<u32*> stack_ptr = new_esp;
  74. return copy_to_user(stack_ptr, string.characters(), string.length() + 1);
  75. };
  76. Vector<FlatPtr> argv_entries;
  77. for (auto& argument : arguments) {
  78. push_string_on_new_stack(argument);
  79. argv_entries.append(new_esp);
  80. }
  81. Vector<FlatPtr> env_entries;
  82. for (auto& variable : environment) {
  83. push_string_on_new_stack(variable);
  84. env_entries.append(new_esp);
  85. }
  86. for (auto& value : auxiliary_values) {
  87. if (!value.optional_string.is_empty()) {
  88. push_string_on_new_stack(value.optional_string);
  89. value.auxv.a_un.a_ptr = (void*)new_esp;
  90. }
  91. }
  92. for (ssize_t i = auxiliary_values.size() - 1; i >= 0; --i) {
  93. auto& value = auxiliary_values[i];
  94. push_aux_value_on_new_stack(value.auxv);
  95. }
  96. push_on_new_stack(0);
  97. for (ssize_t i = env_entries.size() - 1; i >= 0; --i)
  98. push_on_new_stack(env_entries[i]);
  99. FlatPtr envp = new_esp;
  100. push_on_new_stack(0);
  101. for (ssize_t i = argv_entries.size() - 1; i >= 0; --i)
  102. push_on_new_stack(argv_entries[i]);
  103. FlatPtr argv = new_esp;
  104. // NOTE: The stack needs to be 16-byte aligned.
  105. new_esp -= new_esp % 16;
  106. push_on_new_stack((FlatPtr)envp);
  107. push_on_new_stack((FlatPtr)argv);
  108. push_on_new_stack((FlatPtr)argv_entries.size());
  109. push_on_new_stack(0);
  110. return new_esp;
  111. }
  112. KResultOr<Process::LoadResult> Process::load_elf_object(FileDescription& object_description, FlatPtr load_offset, ShouldAllocateTls should_allocate_tls)
  113. {
  114. auto& inode = *(object_description.inode());
  115. auto vmobject = SharedInodeVMObject::create_with_inode(inode);
  116. if (vmobject->writable_mappings()) {
  117. dbgln("Refusing to execute a write-mapped program");
  118. return KResult(-ETXTBSY);
  119. }
  120. size_t executable_size = inode.size();
  121. auto region = MM.allocate_kernel_region_with_vmobject(*vmobject, PAGE_ROUND_UP(executable_size), "ELF loading", Region::Access::Read);
  122. if (!region) {
  123. dbgln("Could not allocate memory for ELF loading");
  124. return KResult(-ENOMEM);
  125. }
  126. auto elf_image = ELF::Image(region->vaddr().as_ptr(), executable_size);
  127. if (!elf_image.is_valid())
  128. return KResult(-ENOEXEC);
  129. Region* master_tls_region { nullptr };
  130. size_t master_tls_size = 0;
  131. size_t master_tls_alignment = 0;
  132. FlatPtr load_base_address = 0;
  133. String elf_name = object_description.absolute_path();
  134. ASSERT(!Processor::current().in_critical());
  135. KResult ph_load_result = KSuccess;
  136. elf_image.for_each_program_header([&](const ELF::Image::ProgramHeader& program_header) {
  137. if (program_header.type() == PT_TLS) {
  138. ASSERT(should_allocate_tls == ShouldAllocateTls::Yes);
  139. ASSERT(program_header.size_in_memory());
  140. if (!elf_image.is_within_image(program_header.raw_data(), program_header.size_in_image())) {
  141. dbgln("Shenanigans! ELF PT_TLS header sneaks outside of executable.");
  142. ph_load_result = KResult(-ENOEXEC);
  143. return IterationDecision::Break;
  144. }
  145. master_tls_region = allocate_region({}, program_header.size_in_memory(), String::formatted("{} (master-tls)", elf_name), PROT_READ | PROT_WRITE, AllocationStrategy::Reserve);
  146. if (!master_tls_region) {
  147. ph_load_result = KResult(-ENOMEM);
  148. return IterationDecision::Break;
  149. }
  150. master_tls_size = program_header.size_in_memory();
  151. master_tls_alignment = program_header.alignment();
  152. if (!copy_to_user(master_tls_region->vaddr().as_ptr(), program_header.raw_data(), program_header.size_in_image())) {
  153. ph_load_result = KResult(-EFAULT);
  154. return IterationDecision::Break;
  155. }
  156. return IterationDecision::Continue;
  157. }
  158. if (program_header.type() != PT_LOAD)
  159. return IterationDecision::Continue;
  160. if (program_header.is_writable()) {
  161. // Writable section: create a copy in memory.
  162. ASSERT(program_header.size_in_memory());
  163. ASSERT(program_header.alignment() == PAGE_SIZE);
  164. if (!elf_image.is_within_image(program_header.raw_data(), program_header.size_in_image())) {
  165. dbgln("Shenanigans! Writable ELF PT_LOAD header sneaks outside of executable.");
  166. ph_load_result = KResult(-ENOEXEC);
  167. return IterationDecision::Break;
  168. }
  169. int prot = 0;
  170. if (program_header.is_readable())
  171. prot |= PROT_READ;
  172. if (program_header.is_writable())
  173. prot |= PROT_WRITE;
  174. auto region_name = String::formatted("{} (data-{}{})", elf_name, program_header.is_readable() ? "r" : "", program_header.is_writable() ? "w" : "");
  175. auto* region = allocate_region(program_header.vaddr().offset(load_offset), program_header.size_in_memory(), move(region_name), prot, AllocationStrategy::Reserve);
  176. if (!region) {
  177. ph_load_result = KResult(-ENOMEM);
  178. return IterationDecision::Break;
  179. }
  180. // It's not always the case with PIE executables (and very well shouldn't be) that the
  181. // virtual address in the program header matches the one we end up giving the process.
  182. // In order to copy the data image correctly into memory, we need to copy the data starting at
  183. // the right initial page offset into the pages allocated for the elf_alloc-XX section.
  184. // FIXME: There's an opportunity to munmap, or at least mprotect, the padding space between
  185. // the .text and .data PT_LOAD sections of the executable.
  186. // Accessing it would definitely be a bug.
  187. auto page_offset = program_header.vaddr();
  188. page_offset.mask(~PAGE_MASK);
  189. if (!copy_to_user((u8*)region->vaddr().as_ptr() + page_offset.get(), program_header.raw_data(), program_header.size_in_image())) {
  190. ph_load_result = KResult(-EFAULT);
  191. return IterationDecision::Break;
  192. }
  193. return IterationDecision::Continue;
  194. }
  195. // Non-writable section: map the executable itself in memory.
  196. ASSERT(program_header.size_in_memory());
  197. ASSERT(program_header.alignment() == PAGE_SIZE);
  198. int prot = 0;
  199. if (program_header.is_readable())
  200. prot |= PROT_READ;
  201. if (program_header.is_writable())
  202. prot |= PROT_WRITE;
  203. if (program_header.is_executable())
  204. prot |= PROT_EXEC;
  205. auto* region = allocate_region_with_vmobject(program_header.vaddr().offset(load_offset), program_header.size_in_memory(), *vmobject, program_header.offset(), elf_name, prot, true);
  206. if (!region) {
  207. ph_load_result = KResult(-ENOMEM);
  208. return IterationDecision::Break;
  209. }
  210. if (program_header.offset() == 0)
  211. load_base_address = (FlatPtr)region->vaddr().as_ptr();
  212. return IterationDecision::Continue;
  213. });
  214. if (ph_load_result.is_error()) {
  215. dbgln("do_exec: Failure loading program ({})", ph_load_result.error());
  216. return ph_load_result;
  217. }
  218. if (!elf_image.entry().offset(load_offset).get()) {
  219. dbgln("do_exec: Failure loading program, entry pointer is invalid! {})", elf_image.entry().offset(load_offset));
  220. return KResult(-ENOEXEC);
  221. }
  222. auto* stack_region = allocate_region(VirtualAddress(), Thread::default_userspace_stack_size, "Stack (Main thread)", PROT_READ | PROT_WRITE, AllocationStrategy::Reserve);
  223. if (!stack_region)
  224. return KResult(-ENOMEM);
  225. stack_region->set_stack(true);
  226. return LoadResult {
  227. load_base_address,
  228. elf_image.entry().offset(load_offset).get(),
  229. executable_size,
  230. VirtualAddress(elf_image.program_header_table_offset()).offset(load_offset).get(),
  231. elf_image.program_header_count(),
  232. master_tls_region ? master_tls_region->make_weak_ptr() : nullptr,
  233. master_tls_size,
  234. master_tls_alignment,
  235. stack_region->make_weak_ptr()
  236. };
  237. }
  238. KResultOr<Process::LoadResult> Process::load(NonnullRefPtr<FileDescription> main_program_description, RefPtr<FileDescription> interpreter_description)
  239. {
  240. RefPtr<PageDirectory> old_page_directory;
  241. NonnullOwnPtrVector<Region> old_regions;
  242. {
  243. auto page_directory = PageDirectory::create_for_userspace(*this);
  244. if (!page_directory)
  245. return KResult(-ENOMEM);
  246. // Need to make sure we don't swap contexts in the middle
  247. ScopedCritical critical;
  248. old_page_directory = move(m_page_directory);
  249. old_regions = move(m_regions);
  250. m_page_directory = page_directory.release_nonnull();
  251. MM.enter_process_paging_scope(*this);
  252. }
  253. ArmedScopeGuard rollback_regions_guard([&]() {
  254. ASSERT(Process::current() == this);
  255. // Need to make sure we don't swap contexts in the middle
  256. ScopedCritical critical;
  257. // Explicitly clear m_regions *before* restoring the page directory,
  258. // otherwise we may silently corrupt memory!
  259. m_regions.clear();
  260. // Now that we freed the regions, revert to the original page directory
  261. // and restore the original regions
  262. m_page_directory = move(old_page_directory);
  263. MM.enter_process_paging_scope(*this);
  264. m_regions = move(old_regions);
  265. });
  266. if (!interpreter_description) {
  267. auto result = load_elf_object(main_program_description, FlatPtr { 0 }, ShouldAllocateTls::Yes);
  268. if (result.is_error())
  269. return result.error();
  270. rollback_regions_guard.disarm();
  271. return result;
  272. }
  273. // TODO: I'm sure this can be randomized even better. :^)
  274. FlatPtr random_offset = get_good_random<u16>() * PAGE_SIZE;
  275. FlatPtr interpreter_load_offset = 0x08000000 + random_offset;
  276. auto interpreter_load_result = load_elf_object(*interpreter_description, interpreter_load_offset, ShouldAllocateTls::No);
  277. if (interpreter_load_result.is_error())
  278. return interpreter_load_result.error();
  279. // TLS allocation will be done in userspace by the loader
  280. ASSERT(!interpreter_load_result.value().tls_region);
  281. ASSERT(!interpreter_load_result.value().tls_alignment);
  282. ASSERT(!interpreter_load_result.value().tls_size);
  283. rollback_regions_guard.disarm();
  284. return interpreter_load_result;
  285. }
  286. int Process::do_exec(NonnullRefPtr<FileDescription> main_program_description, Vector<String> arguments, Vector<String> environment, RefPtr<FileDescription> interpreter_description, Thread*& new_main_thread, u32& prev_flags)
  287. {
  288. ASSERT(is_user_process());
  289. ASSERT(!Processor::current().in_critical());
  290. auto path = main_program_description->absolute_path();
  291. #ifdef EXEC_DEBUG
  292. dbgln("do_exec({})", path);
  293. #endif
  294. // FIXME: How much stack space does process startup need?
  295. if (!validate_stack_size(arguments, environment))
  296. return -E2BIG;
  297. auto parts = path.split('/');
  298. if (parts.is_empty())
  299. return -ENOENT;
  300. // Disable profiling temporarily in case it's running on this process.
  301. bool was_profiling = is_profiling();
  302. TemporaryChange profiling_disabler(m_profiling, false);
  303. // Mark this thread as the current thread that does exec
  304. // No other thread from this process will be scheduled to run
  305. auto current_thread = Thread::current();
  306. m_exec_tid = current_thread->tid();
  307. // NOTE: We switch credentials before altering the memory layout of the process.
  308. // This ensures that ptrace access control takes the right credentials into account.
  309. // FIXME: This still feels rickety. Perhaps it would be better to simply block ptrace
  310. // clients until we're ready to be traced? Or reject them with EPERM?
  311. auto main_program_metadata = main_program_description->metadata();
  312. auto old_euid = m_euid;
  313. auto old_suid = m_suid;
  314. auto old_egid = m_egid;
  315. auto old_sgid = m_sgid;
  316. ArmedScopeGuard cred_restore_guard = [&] {
  317. m_euid = old_euid;
  318. m_suid = old_suid;
  319. m_egid = old_egid;
  320. m_sgid = old_sgid;
  321. };
  322. bool executable_is_setid = false;
  323. if (!(main_program_description->custody()->mount_flags() & MS_NOSUID)) {
  324. if (main_program_metadata.is_setuid()) {
  325. executable_is_setid = true;
  326. m_euid = m_suid = main_program_metadata.uid;
  327. }
  328. if (main_program_metadata.is_setgid()) {
  329. executable_is_setid = true;
  330. m_egid = m_sgid = main_program_metadata.gid;
  331. }
  332. }
  333. auto load_result_or_error = load(main_program_description, interpreter_description);
  334. if (load_result_or_error.is_error()) {
  335. dbgln("do_exec({}): Failed to load main program or interpreter", path);
  336. return load_result_or_error.error();
  337. }
  338. auto& load_result = load_result_or_error.value();
  339. // We can commit to the new credentials at this point.
  340. cred_restore_guard.disarm();
  341. kill_threads_except_self();
  342. #ifdef EXEC_DEBUG
  343. dbgln("Memory layout after ELF load:");
  344. dump_regions();
  345. #endif
  346. m_executable = main_program_description->custody();
  347. m_promises = m_execpromises;
  348. m_veil_state = VeilState::None;
  349. m_unveiled_paths.clear();
  350. current_thread->set_default_signal_dispositions();
  351. current_thread->clear_signals();
  352. m_futex_queues.clear();
  353. m_region_lookup_cache = {};
  354. disown_all_shared_buffers();
  355. set_dumpable(!executable_is_setid);
  356. for (size_t i = 0; i < m_fds.size(); ++i) {
  357. auto& description_and_flags = m_fds[i];
  358. if (description_and_flags.description() && description_and_flags.flags() & FD_CLOEXEC)
  359. description_and_flags = {};
  360. }
  361. int main_program_fd = -1;
  362. if (interpreter_description) {
  363. main_program_fd = alloc_fd();
  364. ASSERT(main_program_fd >= 0);
  365. main_program_description->seek(0, SEEK_SET);
  366. main_program_description->set_readable(true);
  367. m_fds[main_program_fd].set(move(main_program_description), FD_CLOEXEC);
  368. }
  369. new_main_thread = nullptr;
  370. if (&current_thread->process() == this) {
  371. new_main_thread = current_thread;
  372. } else {
  373. for_each_thread([&](auto& thread) {
  374. new_main_thread = &thread;
  375. return IterationDecision::Break;
  376. });
  377. }
  378. ASSERT(new_main_thread);
  379. auto auxv = generate_auxiliary_vector(load_result.load_base, load_result.entry_eip, m_uid, m_euid, m_gid, m_egid, path, main_program_fd);
  380. // NOTE: We create the new stack before disabling interrupts since it will zero-fault
  381. // and we don't want to deal with faults after this point.
  382. auto make_stack_result = make_userspace_stack_for_main_thread(*load_result.stack_region.unsafe_ptr(), move(arguments), move(environment), move(auxv));
  383. if (make_stack_result.is_error())
  384. return make_stack_result.error();
  385. u32 new_userspace_esp = make_stack_result.value();
  386. if (wait_for_tracer_at_next_execve())
  387. Thread::current()->send_urgent_signal_to_self(SIGSTOP);
  388. // We enter a critical section here because we don't want to get interrupted between do_exec()
  389. // and Processor::assume_context() or the next context switch.
  390. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  391. Processor::current().enter_critical(prev_flags);
  392. // NOTE: Be careful to not trigger any page faults below!
  393. m_name = parts.take_last();
  394. new_main_thread->set_name(m_name);
  395. // FIXME: PID/TID ISSUE
  396. m_pid = new_main_thread->tid().value();
  397. auto tsr_result = new_main_thread->make_thread_specific_region({});
  398. if (tsr_result.is_error())
  399. return tsr_result.error();
  400. new_main_thread->reset_fpu_state();
  401. auto& tss = new_main_thread->m_tss;
  402. tss.cs = GDT_SELECTOR_CODE3 | 3;
  403. tss.ds = GDT_SELECTOR_DATA3 | 3;
  404. tss.es = GDT_SELECTOR_DATA3 | 3;
  405. tss.ss = GDT_SELECTOR_DATA3 | 3;
  406. tss.fs = GDT_SELECTOR_DATA3 | 3;
  407. tss.gs = GDT_SELECTOR_TLS | 3;
  408. tss.eip = load_result.entry_eip;
  409. tss.esp = new_userspace_esp;
  410. tss.cr3 = m_page_directory->cr3();
  411. tss.ss2 = m_pid.value();
  412. if (was_profiling)
  413. Profiling::did_exec(path);
  414. {
  415. ScopedSpinLock lock(g_scheduler_lock);
  416. new_main_thread->set_state(Thread::State::Runnable);
  417. }
  418. u32 lock_count_to_restore;
  419. [[maybe_unused]] auto rc = big_lock().force_unlock_if_locked(lock_count_to_restore);
  420. ASSERT_INTERRUPTS_DISABLED();
  421. ASSERT(Processor::current().in_critical());
  422. return 0;
  423. }
  424. static Vector<ELF::AuxiliaryValue> generate_auxiliary_vector(FlatPtr load_base, FlatPtr entry_eip, uid_t uid, uid_t euid, gid_t gid, gid_t egid, String executable_path, int main_program_fd)
  425. {
  426. Vector<ELF::AuxiliaryValue> auxv;
  427. // PHDR/EXECFD
  428. // PH*
  429. auxv.append({ ELF::AuxiliaryValue::PageSize, PAGE_SIZE });
  430. auxv.append({ ELF::AuxiliaryValue::BaseAddress, (void*)load_base });
  431. auxv.append({ ELF::AuxiliaryValue::Entry, (void*)entry_eip });
  432. // NOTELF
  433. auxv.append({ ELF::AuxiliaryValue::Uid, (long)uid });
  434. auxv.append({ ELF::AuxiliaryValue::EUid, (long)euid });
  435. auxv.append({ ELF::AuxiliaryValue::Gid, (long)gid });
  436. auxv.append({ ELF::AuxiliaryValue::EGid, (long)egid });
  437. // FIXME: Don't hard code this? We might support other platforms later.. (e.g. x86_64)
  438. auxv.append({ ELF::AuxiliaryValue::Platform, "i386" });
  439. // FIXME: This is platform specific
  440. auxv.append({ ELF::AuxiliaryValue::HwCap, (long)CPUID(1).edx() });
  441. auxv.append({ ELF::AuxiliaryValue::ClockTick, (long)TimeManagement::the().ticks_per_second() });
  442. // FIXME: Also take into account things like extended filesystem permissions? That's what linux does...
  443. auxv.append({ ELF::AuxiliaryValue::Secure, ((uid != euid) || (gid != egid)) ? 1 : 0 });
  444. char random_bytes[16] {};
  445. get_fast_random_bytes((u8*)random_bytes, sizeof(random_bytes));
  446. auxv.append({ ELF::AuxiliaryValue::Random, String(random_bytes, sizeof(random_bytes)) });
  447. auxv.append({ ELF::AuxiliaryValue::ExecFilename, executable_path });
  448. auxv.append({ ELF::AuxiliaryValue::ExecFileDescriptor, main_program_fd });
  449. auxv.append({ ELF::AuxiliaryValue::Null, 0L });
  450. return auxv;
  451. }
  452. static KResultOr<Vector<String>> find_shebang_interpreter_for_executable(const char first_page[], int nread)
  453. {
  454. int word_start = 2;
  455. int word_length = 0;
  456. if (nread > 2 && first_page[0] == '#' && first_page[1] == '!') {
  457. Vector<String> interpreter_words;
  458. for (int i = 2; i < nread; ++i) {
  459. if (first_page[i] == '\n') {
  460. break;
  461. }
  462. if (first_page[i] != ' ') {
  463. ++word_length;
  464. }
  465. if (first_page[i] == ' ') {
  466. if (word_length > 0) {
  467. interpreter_words.append(String(&first_page[word_start], word_length));
  468. }
  469. word_length = 0;
  470. word_start = i + 1;
  471. }
  472. }
  473. if (word_length > 0)
  474. interpreter_words.append(String(&first_page[word_start], word_length));
  475. if (!interpreter_words.is_empty())
  476. return interpreter_words;
  477. }
  478. return KResult(-ENOEXEC);
  479. }
  480. KResultOr<NonnullRefPtr<FileDescription>> Process::find_elf_interpreter_for_executable(const String& path, char (&first_page)[PAGE_SIZE], int nread, size_t file_size)
  481. {
  482. if (nread < (int)sizeof(Elf32_Ehdr))
  483. return KResult(-ENOEXEC);
  484. auto elf_header = (Elf32_Ehdr*)first_page;
  485. if (!ELF::validate_elf_header(*elf_header, file_size)) {
  486. dbgln("exec({}): File has invalid ELF header", path);
  487. return KResult(-ENOEXEC);
  488. }
  489. // Not using KResultOr here because we'll want to do the same thing in userspace in the RTLD
  490. String interpreter_path;
  491. if (!ELF::validate_program_headers(*elf_header, file_size, (u8*)first_page, nread, &interpreter_path)) {
  492. dbgln("exec({}): File has invalid ELF Program headers", path);
  493. return KResult(-ENOEXEC);
  494. }
  495. if (!interpreter_path.is_empty()) {
  496. #ifdef EXEC_DEBUG
  497. dbgln("exec({}): Using program interpreter {}", path, interpreter_path);
  498. #endif
  499. auto interp_result = VFS::the().open(interpreter_path, O_EXEC, 0, current_directory());
  500. if (interp_result.is_error()) {
  501. dbgln("exec({}): Unable to open program interpreter {}", path, interpreter_path);
  502. return interp_result.error();
  503. }
  504. auto interpreter_description = interp_result.value();
  505. auto interp_metadata = interpreter_description->metadata();
  506. ASSERT(interpreter_description->inode());
  507. // Validate the program interpreter as a valid elf binary.
  508. // If your program interpreter is a #! file or something, it's time to stop playing games :)
  509. if (interp_metadata.size < (int)sizeof(Elf32_Ehdr))
  510. return KResult(-ENOEXEC);
  511. memset(first_page, 0, sizeof(first_page));
  512. auto first_page_buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)&first_page);
  513. auto nread_or_error = interpreter_description->read(first_page_buffer, sizeof(first_page));
  514. if (nread_or_error.is_error())
  515. return KResult(-ENOEXEC);
  516. nread = nread_or_error.value();
  517. if (nread < (int)sizeof(Elf32_Ehdr))
  518. return KResult(-ENOEXEC);
  519. elf_header = (Elf32_Ehdr*)first_page;
  520. if (!ELF::validate_elf_header(*elf_header, interp_metadata.size)) {
  521. dbgln("exec({}): Interpreter ({}) has invalid ELF header", path, interpreter_description->absolute_path());
  522. return KResult(-ENOEXEC);
  523. }
  524. // Not using KResultOr here because we'll want to do the same thing in userspace in the RTLD
  525. String interpreter_interpreter_path;
  526. if (!ELF::validate_program_headers(*elf_header, interp_metadata.size, (u8*)first_page, nread, &interpreter_interpreter_path)) {
  527. dbgln("exec({}): Interpreter ({}) has invalid ELF Program headers", path, interpreter_description->absolute_path());
  528. return KResult(-ENOEXEC);
  529. }
  530. if (!interpreter_interpreter_path.is_empty()) {
  531. dbgln("exec({}): Interpreter ({}) has its own interpreter ({})! No thank you!", path, interpreter_description->absolute_path(), interpreter_interpreter_path);
  532. return KResult(-ELOOP);
  533. }
  534. return interpreter_description;
  535. }
  536. if (elf_header->e_type != ET_EXEC) {
  537. // We can't exec an ET_REL, that's just an object file from the compiler
  538. // If it's ET_DYN with no PT_INTERP, then we can't load it properly either
  539. return KResult(-ENOEXEC);
  540. }
  541. // No interpreter, but, path refers to a valid elf image
  542. return KResult(KSuccess);
  543. }
  544. int Process::exec(String path, Vector<String> arguments, Vector<String> environment, int recursion_depth)
  545. {
  546. if (recursion_depth > 2) {
  547. dbgln("exec({}): SHENANIGANS! recursed too far trying to find #! interpreter", path);
  548. return -ELOOP;
  549. }
  550. // Open the file to check what kind of binary format it is
  551. // Currently supported formats:
  552. // - #! interpreted file
  553. // - ELF32
  554. // * ET_EXEC binary that just gets loaded
  555. // * ET_DYN binary that requires a program interpreter
  556. //
  557. auto result = VFS::the().open(path, O_EXEC, 0, current_directory());
  558. if (result.is_error())
  559. return result.error();
  560. auto description = result.release_value();
  561. auto metadata = description->metadata();
  562. // Always gonna need at least 3 bytes. these are for #!X
  563. if (metadata.size < 3)
  564. return -ENOEXEC;
  565. ASSERT(description->inode());
  566. // Read the first page of the program into memory so we can validate the binfmt of it
  567. char first_page[PAGE_SIZE];
  568. auto first_page_buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)&first_page);
  569. auto nread_or_error = description->read(first_page_buffer, sizeof(first_page));
  570. if (nread_or_error.is_error())
  571. return -ENOEXEC;
  572. // 1) #! interpreted file
  573. auto shebang_result = find_shebang_interpreter_for_executable(first_page, nread_or_error.value());
  574. if (!shebang_result.is_error()) {
  575. Vector<String> new_arguments(shebang_result.value());
  576. new_arguments.append(path);
  577. arguments.remove(0);
  578. new_arguments.append(move(arguments));
  579. return exec(shebang_result.value().first(), move(new_arguments), move(environment), ++recursion_depth);
  580. }
  581. // #2) ELF32 for i386
  582. auto elf_result = find_elf_interpreter_for_executable(path, first_page, nread_or_error.value(), metadata.size);
  583. RefPtr<FileDescription> interpreter_description;
  584. // We're getting either an interpreter, an error, or KSuccess (i.e. no interpreter but file checks out)
  585. if (!elf_result.is_error())
  586. interpreter_description = elf_result.value();
  587. else if (elf_result.error().is_error())
  588. return elf_result.error();
  589. // The bulk of exec() is done by do_exec(), which ensures that all locals
  590. // are cleaned up by the time we yield-teleport below.
  591. Thread* new_main_thread = nullptr;
  592. u32 prev_flags = 0;
  593. int rc = do_exec(move(description), move(arguments), move(environment), move(interpreter_description), new_main_thread, prev_flags);
  594. m_exec_tid = 0;
  595. if (rc < 0)
  596. return rc;
  597. ASSERT_INTERRUPTS_DISABLED();
  598. ASSERT(Processor::current().in_critical());
  599. auto current_thread = Thread::current();
  600. if (current_thread == new_main_thread) {
  601. // We need to enter the scheduler lock before changing the state
  602. // and it will be released after the context switch into that
  603. // thread. We should also still be in our critical section
  604. ASSERT(!g_scheduler_lock.own_lock());
  605. ASSERT(Processor::current().in_critical() == 1);
  606. g_scheduler_lock.lock();
  607. current_thread->set_state(Thread::State::Running);
  608. Processor::assume_context(*current_thread, prev_flags);
  609. ASSERT_NOT_REACHED();
  610. }
  611. Processor::current().leave_critical(prev_flags);
  612. return 0;
  613. }
  614. int Process::sys$execve(Userspace<const Syscall::SC_execve_params*> user_params)
  615. {
  616. REQUIRE_PROMISE(exec);
  617. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  618. // On success, the kernel stack will be lost.
  619. Syscall::SC_execve_params params;
  620. if (!copy_from_user(&params, user_params))
  621. return -EFAULT;
  622. if (params.arguments.length > ARG_MAX || params.environment.length > ARG_MAX)
  623. return -E2BIG;
  624. String path;
  625. {
  626. auto path_arg = get_syscall_path_argument(params.path);
  627. if (path_arg.is_error())
  628. return path_arg.error();
  629. path = path_arg.value();
  630. }
  631. auto copy_user_strings = [](const auto& list, auto& output) {
  632. if (!list.length)
  633. return true;
  634. Checked size = sizeof(list.strings);
  635. size *= list.length;
  636. if (size.has_overflow())
  637. return false;
  638. Vector<Syscall::StringArgument, 32> strings;
  639. strings.resize(list.length);
  640. if (!copy_from_user(strings.data(), list.strings, list.length * sizeof(Syscall::StringArgument)))
  641. return false;
  642. for (size_t i = 0; i < list.length; ++i) {
  643. auto string = copy_string_from_user(strings[i]);
  644. if (string.is_null())
  645. return false;
  646. output.append(move(string));
  647. }
  648. return true;
  649. };
  650. Vector<String> arguments;
  651. if (!copy_user_strings(params.arguments, arguments))
  652. return -EFAULT;
  653. Vector<String> environment;
  654. if (!copy_user_strings(params.environment, environment))
  655. return -EFAULT;
  656. int rc = exec(move(path), move(arguments), move(environment));
  657. ASSERT(rc < 0); // We should never continue after a successful exec!
  658. return rc;
  659. }
  660. }