execve.cpp 24 KB

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