execve.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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/MemoryManager.h>
  36. #include <Kernel/VM/PageDirectory.h>
  37. #include <Kernel/VM/Region.h>
  38. #include <Kernel/VM/SharedInodeVMObject.h>
  39. #include <LibC/limits.h>
  40. #include <LibELF/Loader.h>
  41. #include <LibELF/Validation.h>
  42. //#define EXEC_DEBUG
  43. //#define MM_DEBUG
  44. namespace Kernel {
  45. static bool validate_stack_size(const Vector<String>& arguments, const Vector<String>& environment)
  46. {
  47. size_t total_blob_size = 0;
  48. for (auto& a : arguments)
  49. total_blob_size += a.length() + 1;
  50. for (auto& e : environment)
  51. total_blob_size += e.length() + 1;
  52. size_t total_meta_size = sizeof(char*) * (arguments.size() + 1) + sizeof(char*) * (environment.size() + 1);
  53. // FIXME: This doesn't account for the size of the auxiliary vector
  54. return (total_blob_size + total_meta_size) < Thread::default_userspace_stack_size;
  55. }
  56. KResultOr<Process::LoadResult> Process::load_elf_object(FileDescription& object_description, FlatPtr load_offset, ShouldAllocateTls should_allocate_tls)
  57. {
  58. auto& inode = *(object_description.inode());
  59. auto vmobject = SharedInodeVMObject::create_with_inode(inode);
  60. if (static_cast<const SharedInodeVMObject&>(*vmobject).writable_mappings()) {
  61. dbg() << "Refusing to execute a write-mapped program";
  62. return KResult(-ETXTBSY);
  63. }
  64. InodeMetadata loader_metadata = object_description.metadata();
  65. auto region = MM.allocate_kernel_region_with_vmobject(*vmobject, PAGE_ROUND_UP(loader_metadata.size), "ELF loading", Region::Access::Read);
  66. if (!region) {
  67. dbg() << "Could not allocate memory for ELF loading";
  68. return KResult(-ENOMEM);
  69. }
  70. Region* master_tls_region { nullptr };
  71. size_t master_tls_size = 0;
  72. size_t master_tls_alignment = 0;
  73. m_entry_eip = 0;
  74. FlatPtr load_base_address = 0;
  75. MM.enter_process_paging_scope(*this);
  76. String object_name = LexicalPath(object_description.absolute_path()).basename();
  77. RefPtr<ELF::Loader> loader = ELF::Loader::create(region->vaddr().as_ptr(), loader_metadata.size, move(object_name));
  78. loader->map_section_hook = [&](VirtualAddress vaddr, size_t size, size_t alignment, size_t offset_in_image, bool is_readable, bool is_writable, bool is_executable, const String& name) -> u8* {
  79. ASSERT(size);
  80. ASSERT(alignment == PAGE_SIZE);
  81. int prot = 0;
  82. if (is_readable)
  83. prot |= PROT_READ;
  84. if (is_writable)
  85. prot |= PROT_WRITE;
  86. if (is_executable)
  87. prot |= PROT_EXEC;
  88. if (auto* region = allocate_region_with_vmobject(vaddr.offset(load_offset), size, *vmobject, offset_in_image, String(name), prot)) {
  89. region->set_shared(true);
  90. if (offset_in_image == 0)
  91. load_base_address = (FlatPtr)region->vaddr().as_ptr();
  92. return region->vaddr().as_ptr();
  93. }
  94. return nullptr;
  95. };
  96. loader->alloc_section_hook = [&](VirtualAddress vaddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) -> u8* {
  97. ASSERT(size);
  98. ASSERT(alignment == PAGE_SIZE);
  99. int prot = 0;
  100. if (is_readable)
  101. prot |= PROT_READ;
  102. if (is_writable)
  103. prot |= PROT_WRITE;
  104. if (auto* region = allocate_region(vaddr.offset(load_offset), size, String(name), prot))
  105. return region->vaddr().as_ptr();
  106. return nullptr;
  107. };
  108. if (should_allocate_tls == ShouldAllocateTls::Yes) {
  109. loader->tls_section_hook = [&](size_t size, size_t alignment) {
  110. ASSERT(size);
  111. master_tls_region = allocate_region({}, size, String(), PROT_READ | PROT_WRITE);
  112. master_tls_size = size;
  113. master_tls_alignment = alignment;
  114. return master_tls_region->vaddr().as_ptr();
  115. };
  116. }
  117. ASSERT(!Processor::current().in_critical());
  118. bool success = loader->load();
  119. if (!success) {
  120. klog() << "do_exec: Failure loading program";
  121. return KResult(-ENOEXEC);
  122. }
  123. if (!loader->entry().offset(load_offset).get()) {
  124. klog() << "do_exec: Failure loading program, entry pointer is invalid! (" << loader->entry().offset(load_offset) << ")";
  125. return KResult(-ENOEXEC);
  126. }
  127. // NOTE: At this point, we've committed to the new executable.
  128. return LoadResult {
  129. load_base_address,
  130. loader->entry().offset(load_offset).get(),
  131. (size_t)loader_metadata.size,
  132. VirtualAddress(loader->image().program_header_table_offset()).offset(load_offset).get(),
  133. loader->image().program_header_count(),
  134. master_tls_region ? master_tls_region->make_weak_ptr() : nullptr,
  135. master_tls_size,
  136. master_tls_alignment
  137. };
  138. }
  139. int Process::load(NonnullRefPtr<FileDescription> main_program_description, RefPtr<FileDescription> interpreter_description)
  140. {
  141. RefPtr<PageDirectory> old_page_directory;
  142. NonnullOwnPtrVector<Region> old_regions;
  143. {
  144. // Need to make sure we don't swap contexts in the middle
  145. ScopedCritical critical;
  146. old_page_directory = move(m_page_directory);
  147. old_regions = move(m_regions);
  148. m_page_directory = PageDirectory::create_for_userspace(*this);
  149. }
  150. ArmedScopeGuard rollback_regions_guard([&]() {
  151. ASSERT(Process::current() == this);
  152. // Need to make sure we don't swap contexts in the middle
  153. ScopedCritical critical;
  154. m_page_directory = move(old_page_directory);
  155. m_regions = move(old_regions);
  156. MM.enter_process_paging_scope(*this);
  157. });
  158. if (!interpreter_description) {
  159. auto result = load_elf_object(main_program_description, FlatPtr { 0 }, ShouldAllocateTls::Yes);
  160. if (result.is_error())
  161. return result.error();
  162. m_load_base = result.value().load_base;
  163. m_entry_eip = result.value().entry_eip;
  164. m_master_tls_region = result.value().tls_region;
  165. m_master_tls_size = result.value().tls_size;
  166. m_master_tls_alignment = result.value().tls_alignment;
  167. rollback_regions_guard.disarm();
  168. return 0;
  169. }
  170. // TODO: This should be randomized for ASLR
  171. constexpr FlatPtr interpreter_load_offset = 0x08000000;
  172. auto interpreter_load_result = load_elf_object(*interpreter_description, interpreter_load_offset, ShouldAllocateTls::No);
  173. if (interpreter_load_result.is_error())
  174. return interpreter_load_result.error();
  175. m_load_base = interpreter_load_result.value().load_base;
  176. m_entry_eip = interpreter_load_result.value().entry_eip;
  177. // TLS allocation will be done in userspace by the loader
  178. m_master_tls_region = nullptr;
  179. m_master_tls_size = 0;
  180. m_master_tls_alignment = 0;
  181. rollback_regions_guard.disarm();
  182. return 0;
  183. }
  184. 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)
  185. {
  186. ASSERT(is_user_process());
  187. ASSERT(!Processor::current().in_critical());
  188. auto path = main_program_description->absolute_path();
  189. #ifdef EXEC_DEBUG
  190. dbg() << "do_exec(" << path << ")";
  191. #endif
  192. // FIXME: How much stack space does process startup need?
  193. if (!validate_stack_size(arguments, environment))
  194. return -E2BIG;
  195. auto parts = path.split('/');
  196. if (parts.is_empty())
  197. return -ENOENT;
  198. // Disable profiling temporarily in case it's running on this process.
  199. bool was_profiling = is_profiling();
  200. TemporaryChange profiling_disabler(m_profiling, false);
  201. // Mark this thread as the current thread that does exec
  202. // No other thread from this process will be scheduled to run
  203. auto current_thread = Thread::current();
  204. m_exec_tid = current_thread->tid();
  205. #ifdef MM_DEBUG
  206. dbg() << "Process " << pid().value() << " exec: PD=" << m_page_directory.ptr() << " created";
  207. #endif
  208. int load_rc = load(main_program_description, interpreter_description);
  209. if (load_rc) {
  210. klog() << "do_exec: Failed to load main program or interpreter";
  211. return load_rc;
  212. }
  213. kill_threads_except_self();
  214. #ifdef EXEC_DEBUG
  215. klog() << "Memory layout after ELF load:";
  216. dump_regions();
  217. #endif
  218. m_executable = main_program_description->custody();
  219. m_promises = m_execpromises;
  220. m_veil_state = VeilState::None;
  221. m_unveiled_paths.clear();
  222. auto main_program_metadata = main_program_description->metadata();
  223. if (!(main_program_description->custody()->mount_flags() & MS_NOSUID)) {
  224. if (main_program_metadata.is_setuid())
  225. m_euid = m_suid = main_program_metadata.uid;
  226. if (main_program_metadata.is_setgid())
  227. m_egid = m_sgid = main_program_metadata.gid;
  228. }
  229. current_thread->set_default_signal_dispositions();
  230. current_thread->clear_signals();
  231. m_futex_queues.clear();
  232. m_region_lookup_cache = {};
  233. disown_all_shared_buffers();
  234. for (size_t i = 0; i < m_fds.size(); ++i) {
  235. auto& description_and_flags = m_fds[i];
  236. if (description_and_flags.description() && description_and_flags.flags() & FD_CLOEXEC)
  237. description_and_flags = {};
  238. }
  239. if (interpreter_description) {
  240. m_main_program_fd = alloc_fd();
  241. ASSERT(m_main_program_fd >= 0);
  242. main_program_description->seek(0, SEEK_SET);
  243. main_program_description->set_readable(true);
  244. m_fds[m_main_program_fd].set(move(main_program_description), FD_CLOEXEC);
  245. }
  246. new_main_thread = nullptr;
  247. if (&current_thread->process() == this) {
  248. new_main_thread = current_thread;
  249. } else {
  250. for_each_thread([&](auto& thread) {
  251. new_main_thread = &thread;
  252. return IterationDecision::Break;
  253. });
  254. }
  255. ASSERT(new_main_thread);
  256. auto auxv = generate_auxiliary_vector();
  257. // NOTE: We create the new stack before disabling interrupts since it will zero-fault
  258. // and we don't want to deal with faults after this point.
  259. auto make_stack_result = new_main_thread->make_userspace_stack_for_main_thread(move(arguments), move(environment), move(auxv));
  260. if (make_stack_result.is_error())
  261. return make_stack_result.error();
  262. u32 new_userspace_esp = make_stack_result.value();
  263. if (wait_for_tracer_at_next_execve())
  264. Thread::current()->send_urgent_signal_to_self(SIGSTOP);
  265. // We enter a critical section here because we don't want to get interrupted between do_exec()
  266. // and Processor::assume_context() or the next context switch.
  267. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  268. Processor::current().enter_critical(prev_flags);
  269. // NOTE: Be careful to not trigger any page faults below!
  270. m_name = parts.take_last();
  271. new_main_thread->set_name(m_name);
  272. // FIXME: PID/TID ISSUE
  273. m_pid = new_main_thread->tid().value();
  274. auto tsr_result = new_main_thread->make_thread_specific_region({});
  275. if (tsr_result.is_error())
  276. return tsr_result.error();
  277. new_main_thread->reset_fpu_state();
  278. auto& tss = new_main_thread->m_tss;
  279. tss.cs = GDT_SELECTOR_CODE3 | 3;
  280. tss.ds = GDT_SELECTOR_DATA3 | 3;
  281. tss.es = GDT_SELECTOR_DATA3 | 3;
  282. tss.ss = GDT_SELECTOR_DATA3 | 3;
  283. tss.fs = GDT_SELECTOR_DATA3 | 3;
  284. tss.gs = GDT_SELECTOR_TLS | 3;
  285. tss.eip = m_entry_eip;
  286. tss.esp = new_userspace_esp;
  287. tss.cr3 = m_page_directory->cr3();
  288. tss.ss2 = m_pid.value();
  289. if (was_profiling)
  290. Profiling::did_exec(path);
  291. {
  292. ScopedSpinLock lock(g_scheduler_lock);
  293. new_main_thread->set_state(Thread::State::Runnable);
  294. }
  295. u32 lock_count_to_restore;
  296. (void)big_lock().force_unlock_if_locked(lock_count_to_restore);
  297. ASSERT_INTERRUPTS_DISABLED();
  298. ASSERT(Processor::current().in_critical());
  299. return 0;
  300. }
  301. Vector<AuxiliaryValue> Process::generate_auxiliary_vector() const
  302. {
  303. Vector<AuxiliaryValue> auxv;
  304. // PHDR/EXECFD
  305. // PH*
  306. auxv.append({ AuxiliaryValue::PageSize, PAGE_SIZE });
  307. auxv.append({ AuxiliaryValue::BaseAddress, (void*)m_load_base });
  308. auxv.append({ AuxiliaryValue::Entry, (void*)m_entry_eip });
  309. // NOTELF
  310. auxv.append({ AuxiliaryValue::Uid, (long)m_uid });
  311. auxv.append({ AuxiliaryValue::EUid, (long)m_euid });
  312. auxv.append({ AuxiliaryValue::Gid, (long)m_gid });
  313. auxv.append({ AuxiliaryValue::EGid, (long)m_egid });
  314. // FIXME: Don't hard code this? We might support other platforms later.. (e.g. x86_64)
  315. auxv.append({ AuxiliaryValue::Platform, "i386" });
  316. // FIXME: This is platform specific
  317. auxv.append({ AuxiliaryValue::HwCap, (long)CPUID(1).edx() });
  318. auxv.append({ AuxiliaryValue::ClockTick, (long)TimeManagement::the().ticks_per_second() });
  319. // FIXME: Also take into account things like extended filesystem permissions? That's what linux does...
  320. auxv.append({ AuxiliaryValue::Secure, ((m_uid != m_euid) || (m_gid != m_egid)) ? 1 : 0 });
  321. char random_bytes[16] {};
  322. get_fast_random_bytes((u8*)random_bytes, sizeof(random_bytes));
  323. auxv.append({ AuxiliaryValue::Random, String(random_bytes, sizeof(random_bytes)) });
  324. auxv.append({ AuxiliaryValue::ExecFilename, m_executable->absolute_path() });
  325. auxv.append({ AuxiliaryValue::ExecFileDescriptor, m_main_program_fd });
  326. auxv.append({ AuxiliaryValue::Null, 0L });
  327. return auxv;
  328. }
  329. static KResultOr<Vector<String>> find_shebang_interpreter_for_executable(const char first_page[], int nread)
  330. {
  331. int word_start = 2;
  332. int word_length = 0;
  333. if (nread > 2 && first_page[0] == '#' && first_page[1] == '!') {
  334. Vector<String> interpreter_words;
  335. for (int i = 2; i < nread; ++i) {
  336. if (first_page[i] == '\n') {
  337. break;
  338. }
  339. if (first_page[i] != ' ') {
  340. ++word_length;
  341. }
  342. if (first_page[i] == ' ') {
  343. if (word_length > 0) {
  344. interpreter_words.append(String(&first_page[word_start], word_length));
  345. }
  346. word_length = 0;
  347. word_start = i + 1;
  348. }
  349. }
  350. if (word_length > 0)
  351. interpreter_words.append(String(&first_page[word_start], word_length));
  352. if (!interpreter_words.is_empty())
  353. return interpreter_words;
  354. }
  355. return KResult(-ENOEXEC);
  356. }
  357. KResultOr<NonnullRefPtr<FileDescription>> Process::find_elf_interpreter_for_executable(const String& path, char (&first_page)[PAGE_SIZE], int nread, size_t file_size)
  358. {
  359. if (nread < (int)sizeof(Elf32_Ehdr))
  360. return KResult(-ENOEXEC);
  361. auto elf_header = (Elf32_Ehdr*)first_page;
  362. if (!ELF::validate_elf_header(*elf_header, file_size)) {
  363. dbg() << "exec(" << path << "): File has invalid ELF header";
  364. return KResult(-ENOEXEC);
  365. }
  366. // Not using KResultOr here because we'll want to do the same thing in userspace in the RTLD
  367. String interpreter_path;
  368. if (!ELF::validate_program_headers(*elf_header, file_size, (u8*)first_page, nread, &interpreter_path)) {
  369. dbg() << "exec(" << path << "): File has invalid ELF Program headers";
  370. return KResult(-ENOEXEC);
  371. }
  372. if (!interpreter_path.is_empty()) {
  373. // Programs with an interpreter better be relocatable executables or we don't know what to do...
  374. if (elf_header->e_type != ET_DYN)
  375. return KResult(-ENOEXEC);
  376. dbg() << "exec(" << path << "): Using program interpreter " << interpreter_path;
  377. auto interp_result = VFS::the().open(interpreter_path, O_EXEC, 0, current_directory());
  378. if (interp_result.is_error()) {
  379. dbg() << "exec(" << path << "): Unable to open program interpreter " << interpreter_path;
  380. return interp_result.error();
  381. }
  382. auto interpreter_description = interp_result.value();
  383. auto interp_metadata = interpreter_description->metadata();
  384. ASSERT(interpreter_description->inode());
  385. // Validate the program interpreter as a valid elf binary.
  386. // If your program interpreter is a #! file or something, it's time to stop playing games :)
  387. if (interp_metadata.size < (int)sizeof(Elf32_Ehdr))
  388. return KResult(-ENOEXEC);
  389. memset(first_page, 0, sizeof(first_page));
  390. auto first_page_buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)&first_page);
  391. auto nread_or_error = interpreter_description->read(first_page_buffer, sizeof(first_page));
  392. if (nread_or_error.is_error())
  393. return KResult(-ENOEXEC);
  394. nread = nread_or_error.value();
  395. if (nread < (int)sizeof(Elf32_Ehdr))
  396. return KResult(-ENOEXEC);
  397. elf_header = (Elf32_Ehdr*)first_page;
  398. if (!ELF::validate_elf_header(*elf_header, interp_metadata.size)) {
  399. dbg() << "exec(" << path << "): Interpreter (" << interpreter_description->absolute_path() << ") has invalid ELF header";
  400. return KResult(-ENOEXEC);
  401. }
  402. // Not using KResultOr here because we'll want to do the same thing in userspace in the RTLD
  403. String interpreter_interpreter_path;
  404. if (!ELF::validate_program_headers(*elf_header, interp_metadata.size, (u8*)first_page, nread, &interpreter_interpreter_path)) {
  405. dbg() << "exec(" << path << "): Interpreter (" << interpreter_description->absolute_path() << ") has invalid ELF Program headers";
  406. return KResult(-ENOEXEC);
  407. }
  408. // FIXME: Uncomment this
  409. // How do we get gcc to not insert an interpreter section to /usr/lib/Loader.so itself?
  410. // if (!interpreter_interpreter_path.is_empty()) {
  411. // dbg() << "exec(" << path << "): Interpreter (" << interpreter_description->absolute_path() << ") has its own interpreter (" << interpreter_interpreter_path << ")! No thank you!";
  412. // return KResult(-ELOOP);
  413. // }
  414. return interpreter_description;
  415. }
  416. if (elf_header->e_type != ET_EXEC) {
  417. // We can't exec an ET_REL, that's just an object file from the compiler
  418. // If it's ET_DYN with no PT_INTERP, then we can't load it properly either
  419. return KResult(-ENOEXEC);
  420. }
  421. // No interpreter, but, path refers to a valid elf image
  422. return KResult(KSuccess);
  423. }
  424. int Process::exec(String path, Vector<String> arguments, Vector<String> environment, int recursion_depth)
  425. {
  426. if (recursion_depth > 2) {
  427. dbg() << "exec(" << path << "): SHENANIGANS! recursed too far trying to find #! interpreter";
  428. return -ELOOP;
  429. }
  430. // Open the file to check what kind of binary format it is
  431. // Currently supported formats:
  432. // - #! interpreted file
  433. // - ELF32
  434. // * ET_EXEC binary that just gets loaded
  435. // * ET_DYN binary that requires a program interpreter
  436. //
  437. auto result = VFS::the().open(path, O_EXEC, 0, current_directory());
  438. if (result.is_error())
  439. return result.error();
  440. auto description = result.release_value();
  441. auto metadata = description->metadata();
  442. // Always gonna need at least 3 bytes. these are for #!X
  443. if (metadata.size < 3)
  444. return -ENOEXEC;
  445. ASSERT(description->inode());
  446. // Read the first page of the program into memory so we can validate the binfmt of it
  447. char first_page[PAGE_SIZE];
  448. auto first_page_buffer = UserOrKernelBuffer::for_kernel_buffer((u8*)&first_page);
  449. auto nread_or_error = description->read(first_page_buffer, sizeof(first_page));
  450. if (nread_or_error.is_error())
  451. return -ENOEXEC;
  452. // 1) #! interpreted file
  453. auto shebang_result = find_shebang_interpreter_for_executable(first_page, nread_or_error.value());
  454. if (!shebang_result.is_error()) {
  455. Vector<String> new_arguments(shebang_result.value());
  456. new_arguments.append(path);
  457. arguments.remove(0);
  458. new_arguments.append(move(arguments));
  459. return exec(shebang_result.value().first(), move(new_arguments), move(environment), ++recursion_depth);
  460. }
  461. // #2) ELF32 for i386
  462. auto elf_result = find_elf_interpreter_for_executable(path, first_page, nread_or_error.value(), metadata.size);
  463. RefPtr<FileDescription> interpreter_description;
  464. // We're getting either an interpreter, an error, or KSuccess (i.e. no interpreter but file checks out)
  465. if (!elf_result.is_error())
  466. interpreter_description = elf_result.value();
  467. else if (elf_result.error().is_error())
  468. return elf_result.error();
  469. // The bulk of exec() is done by do_exec(), which ensures that all locals
  470. // are cleaned up by the time we yield-teleport below.
  471. Thread* new_main_thread = nullptr;
  472. u32 prev_flags = 0;
  473. int rc = do_exec(move(description), move(arguments), move(environment), move(interpreter_description), new_main_thread, prev_flags);
  474. m_exec_tid = 0;
  475. if (rc < 0)
  476. return rc;
  477. ASSERT_INTERRUPTS_DISABLED();
  478. ASSERT(Processor::current().in_critical());
  479. auto current_thread = Thread::current();
  480. if (current_thread == new_main_thread) {
  481. // We need to enter the scheduler lock before changing the state
  482. // and it will be released after the context switch into that
  483. // thread. We should also still be in our critical section
  484. ASSERT(!g_scheduler_lock.own_lock());
  485. ASSERT(Processor::current().in_critical() == 1);
  486. g_scheduler_lock.lock();
  487. current_thread->set_state(Thread::State::Running);
  488. Processor::assume_context(*current_thread, prev_flags);
  489. ASSERT_NOT_REACHED();
  490. }
  491. Processor::current().leave_critical(prev_flags);
  492. return 0;
  493. }
  494. int Process::sys$execve(Userspace<const Syscall::SC_execve_params*> user_params)
  495. {
  496. REQUIRE_PROMISE(exec);
  497. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  498. // On success, the kernel stack will be lost.
  499. Syscall::SC_execve_params params;
  500. if (!copy_from_user(&params, user_params))
  501. return -EFAULT;
  502. if (params.arguments.length > ARG_MAX || params.environment.length > ARG_MAX)
  503. return -E2BIG;
  504. String path;
  505. {
  506. auto path_arg = get_syscall_path_argument(params.path);
  507. if (path_arg.is_error())
  508. return path_arg.error();
  509. path = path_arg.value();
  510. }
  511. auto copy_user_strings = [](const auto& list, auto& output) {
  512. if (!list.length)
  513. return true;
  514. Checked size = sizeof(list.length);
  515. size *= list.length;
  516. if (size.has_overflow())
  517. return false;
  518. Vector<Syscall::StringArgument, 32> strings;
  519. strings.resize(list.length);
  520. if (!copy_from_user(strings.data(), list.strings, list.length * sizeof(Syscall::StringArgument)))
  521. return false;
  522. for (size_t i = 0; i < list.length; ++i) {
  523. auto string = copy_string_from_user(strings[i]);
  524. if (string.is_null())
  525. return false;
  526. output.append(move(string));
  527. }
  528. return true;
  529. };
  530. Vector<String> arguments;
  531. if (!copy_user_strings(params.arguments, arguments))
  532. return -EFAULT;
  533. Vector<String> environment;
  534. if (!copy_user_strings(params.environment, environment))
  535. return -EFAULT;
  536. int rc = exec(move(path), move(arguments), move(environment));
  537. ASSERT(rc < 0); // We should never continue after a successful exec!
  538. return rc;
  539. }
  540. }