execve.cpp 24 KB

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