Process.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626
  1. #include <AK/Types.h>
  2. #include "Process.h"
  3. #include "kmalloc.h"
  4. #include "StdLib.h"
  5. #include "i386.h"
  6. #include <Kernel/FileSystem/FileDescriptor.h>
  7. #include <Kernel/FileSystem/VirtualFileSystem.h>
  8. #include <Kernel/Devices/NullDevice.h>
  9. #include <Kernel/ELF/ELFLoader.h>
  10. #include <Kernel/VM/MemoryManager.h>
  11. #include "i8253.h"
  12. #include "RTC.h"
  13. #include <AK/StdLibExtras.h>
  14. #include <LibC/signal_numbers.h>
  15. #include <LibC/errno_numbers.h>
  16. #include "Syscall.h"
  17. #include "Scheduler.h"
  18. #include <Kernel/FileSystem/FIFO.h>
  19. #include "KSyms.h"
  20. #include <Kernel/Net/Socket.h>
  21. #include <Kernel/TTY/MasterPTY.h>
  22. #include <Kernel/ELF/exec_elf.h>
  23. #include <AK/StringBuilder.h>
  24. #include <AK/Time.h>
  25. #include <Kernel/SharedMemory.h>
  26. #include <Kernel/ProcessTracer.h>
  27. //#define DEBUG_IO
  28. //#define TASK_DEBUG
  29. //#define FORK_DEBUG
  30. #define SIGNAL_DEBUG
  31. //#define SHARED_BUFFER_DEBUG
  32. static pid_t next_pid;
  33. InlineLinkedList<Process>* g_processes;
  34. static String* s_hostname;
  35. static Lock* s_hostname_lock;
  36. void Process::initialize()
  37. {
  38. next_pid = 0;
  39. g_processes = new InlineLinkedList<Process>;
  40. s_hostname = new String("courage");
  41. s_hostname_lock = new Lock;
  42. }
  43. Vector<pid_t> Process::all_pids()
  44. {
  45. Vector<pid_t> pids;
  46. InterruptDisabler disabler;
  47. pids.ensure_capacity(g_processes->size_slow());
  48. for (auto* process = g_processes->head(); process; process = process->next())
  49. pids.append(process->pid());
  50. return pids;
  51. }
  52. Vector<Process*> Process::all_processes()
  53. {
  54. Vector<Process*> processes;
  55. InterruptDisabler disabler;
  56. processes.ensure_capacity(g_processes->size_slow());
  57. for (auto* process = g_processes->head(); process; process = process->next())
  58. processes.append(process);
  59. return processes;
  60. }
  61. bool Process::in_group(gid_t gid) const
  62. {
  63. return m_gids.contains(gid);
  64. }
  65. Range Process::allocate_range(LinearAddress laddr, size_t size)
  66. {
  67. laddr.mask(PAGE_MASK);
  68. size = PAGE_ROUND_UP(size);
  69. if (laddr.is_null())
  70. return m_range_allocator.allocate_anywhere(size);
  71. return m_range_allocator.allocate_specific(laddr, size);
  72. }
  73. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  74. {
  75. auto range = allocate_range(laddr, size);
  76. if (!range.is_valid())
  77. return nullptr;
  78. m_regions.append(adopt(*new Region(range, move(name), is_readable, is_writable)));
  79. MM.map_region(*this, *m_regions.last());
  80. if (commit)
  81. m_regions.last()->commit();
  82. return m_regions.last().ptr();
  83. }
  84. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Inode>&& inode, String&& name, bool is_readable, bool is_writable)
  85. {
  86. auto range = allocate_range(laddr, size);
  87. if (!range.is_valid())
  88. return nullptr;
  89. m_regions.append(adopt(*new Region(range, move(inode), move(name), is_readable, is_writable)));
  90. MM.map_region(*this, *m_regions.last());
  91. return m_regions.last().ptr();
  92. }
  93. Region* Process::allocate_region_with_vmo(LinearAddress laddr, size_t size, Retained<VMObject>&& vmo, size_t offset_in_vmo, String&& name, bool is_readable, bool is_writable)
  94. {
  95. auto range = allocate_range(laddr, size);
  96. if (!range.is_valid())
  97. return nullptr;
  98. offset_in_vmo &= PAGE_MASK;
  99. m_regions.append(adopt(*new Region(range, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  100. MM.map_region(*this, *m_regions.last());
  101. return m_regions.last().ptr();
  102. }
  103. bool Process::deallocate_region(Region& region)
  104. {
  105. InterruptDisabler disabler;
  106. for (int i = 0; i < m_regions.size(); ++i) {
  107. if (m_regions[i] == &region) {
  108. m_range_allocator.deallocate({ region.laddr(), region.size() });
  109. MM.unmap_region(region);
  110. m_regions.remove(i);
  111. return true;
  112. }
  113. }
  114. return false;
  115. }
  116. Region* Process::region_from_range(LinearAddress laddr, size_t size)
  117. {
  118. size = PAGE_ROUND_UP(size);
  119. for (auto& region : m_regions) {
  120. if (region->laddr() == laddr && region->size() == size)
  121. return region.ptr();
  122. }
  123. return nullptr;
  124. }
  125. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  126. {
  127. if (!validate_read_str(name))
  128. return -EFAULT;
  129. auto* region = region_from_range(LinearAddress((dword)addr), size);
  130. if (!region)
  131. return -EINVAL;
  132. region->set_name(String(name));
  133. return 0;
  134. }
  135. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  136. {
  137. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  138. return (void*)-EFAULT;
  139. void* addr = (void*)params->addr;
  140. size_t size = params->size;
  141. int prot = params->prot;
  142. int flags = params->flags;
  143. int fd = params->fd;
  144. off_t offset = params->offset;
  145. if (size == 0)
  146. return (void*)-EINVAL;
  147. if ((dword)addr & ~PAGE_MASK)
  148. return (void*)-EINVAL;
  149. if (flags & MAP_ANONYMOUS) {
  150. auto* region = allocate_region(LinearAddress((dword)addr), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  151. if (!region)
  152. return (void*)-ENOMEM;
  153. if (flags & MAP_SHARED)
  154. region->set_shared(true);
  155. return region->laddr().as_ptr();
  156. }
  157. if (offset & ~PAGE_MASK)
  158. return (void*)-EINVAL;
  159. auto* descriptor = file_descriptor(fd);
  160. if (!descriptor)
  161. return (void*)-EBADF;
  162. auto region_or_error = descriptor->mmap(*this, LinearAddress((dword)addr), offset, size, prot);
  163. if (region_or_error.is_error())
  164. return (void*)(int)region_or_error.error();
  165. auto region = region_or_error.value();
  166. if (flags & MAP_SHARED)
  167. region->set_shared(true);
  168. return region->laddr().as_ptr();
  169. }
  170. int Process::sys$munmap(void* addr, size_t size)
  171. {
  172. auto* region = region_from_range(LinearAddress((dword)addr), size);
  173. if (!region)
  174. return -EINVAL;
  175. if (!deallocate_region(*region))
  176. return -EINVAL;
  177. return 0;
  178. }
  179. int Process::sys$gethostname(char* buffer, ssize_t size)
  180. {
  181. if (size < 0)
  182. return -EINVAL;
  183. if (!validate_write(buffer, size))
  184. return -EFAULT;
  185. LOCKER(*s_hostname_lock);
  186. if (size < (s_hostname->length() + 1))
  187. return -ENAMETOOLONG;
  188. strcpy(buffer, s_hostname->characters());
  189. return 0;
  190. }
  191. Process* Process::fork(RegisterDump& regs)
  192. {
  193. auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copy_ref(), m_executable.copy_ref(), m_tty, this);
  194. if (!child)
  195. return nullptr;
  196. #ifdef FORK_DEBUG
  197. dbgprintf("fork: child=%p\n", child);
  198. #endif
  199. for (auto& region : m_regions) {
  200. #ifdef FORK_DEBUG
  201. dbgprintf("fork: cloning Region{%p} \"%s\" L%x\n", region.ptr(), region->name().characters(), region->laddr().get());
  202. #endif
  203. auto cloned_region = region->clone();
  204. child->m_regions.append(move(cloned_region));
  205. MM.map_region(*child, *child->m_regions.last());
  206. }
  207. for (auto gid : m_gids)
  208. child->m_gids.set(gid);
  209. auto& child_tss = child->main_thread().m_tss;
  210. child_tss.eax = 0; // fork() returns 0 in the child :^)
  211. child_tss.ebx = regs.ebx;
  212. child_tss.ecx = regs.ecx;
  213. child_tss.edx = regs.edx;
  214. child_tss.ebp = regs.ebp;
  215. child_tss.esp = regs.esp_if_crossRing;
  216. child_tss.esi = regs.esi;
  217. child_tss.edi = regs.edi;
  218. child_tss.eflags = regs.eflags;
  219. child_tss.eip = regs.eip;
  220. child_tss.cs = regs.cs;
  221. child_tss.ds = regs.ds;
  222. child_tss.es = regs.es;
  223. child_tss.fs = regs.fs;
  224. child_tss.gs = regs.gs;
  225. child_tss.ss = regs.ss_if_crossRing;
  226. #ifdef FORK_DEBUG
  227. dbgprintf("fork: child will begin executing at %w:%x with stack %w:%x, kstack %w:%x\n", child_tss.cs, child_tss.eip, child_tss.ss, child_tss.esp, child_tss.ss0, child_tss.esp0);
  228. #endif
  229. {
  230. InterruptDisabler disabler;
  231. g_processes->prepend(child);
  232. }
  233. #ifdef TASK_DEBUG
  234. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child_tss.eip);
  235. #endif
  236. child->main_thread().set_state(Thread::State::Skip1SchedulerPass);
  237. return child;
  238. }
  239. pid_t Process::sys$fork(RegisterDump& regs)
  240. {
  241. auto* child = fork(regs);
  242. ASSERT(child);
  243. return child->pid();
  244. }
  245. int Process::do_exec(String path, Vector<String> arguments, Vector<String> environment)
  246. {
  247. ASSERT(is_ring3());
  248. dbgprintf("%s(%d) do_exec(%s): thread_count() = %d\n", m_name.characters(), m_pid, path.characters(), thread_count());
  249. // FIXME(Thread): Kill any threads the moment we commit to the exec().
  250. if (thread_count() != 1) {
  251. dbgprintf("Gonna die because I have many threads! These are the threads:\n");
  252. for_each_thread([] (Thread& thread) {
  253. dbgprintf("Thread{%p}: TID=%d, PID=%d\n", &thread, thread.tid(), thread.pid());
  254. return IterationDecision::Continue;
  255. });
  256. ASSERT(thread_count() == 1);
  257. ASSERT_NOT_REACHED();
  258. }
  259. auto parts = path.split('/');
  260. if (parts.is_empty())
  261. return -ENOENT;
  262. auto result = VFS::the().open(path.view(), 0, 0, cwd_inode());
  263. if (result.is_error())
  264. return result.error();
  265. auto descriptor = result.value();
  266. if (!descriptor->metadata().may_execute(m_euid, m_gids))
  267. return -EACCES;
  268. if (!descriptor->metadata().size) {
  269. return -ENOTIMPL;
  270. }
  271. dword entry_eip = 0;
  272. // FIXME: Is there a race here?
  273. auto old_page_directory = move(m_page_directory);
  274. m_page_directory = PageDirectory::create();
  275. #ifdef MM_DEBUG
  276. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  277. #endif
  278. ProcessPagingScope paging_scope(*this);
  279. auto vmo = VMObject::create_file_backed(descriptor->inode());
  280. #if 0
  281. // FIXME: I would like to do this, but it would instantiate all the damn inodes.
  282. vmo->set_name(descriptor->absolute_path());
  283. #else
  284. vmo->set_name("ELF image");
  285. #endif
  286. RetainPtr<Region> region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copy_ref(), 0, "executable", true, false);
  287. ASSERT(region);
  288. if (this != &current->process()) {
  289. // FIXME: Don't force-load the entire executable at once, let the on-demand pager take care of it.
  290. bool success = region->page_in();
  291. ASSERT(success);
  292. }
  293. OwnPtr<ELFLoader> loader;
  294. {
  295. // Okay, here comes the sleight of hand, pay close attention..
  296. auto old_regions = move(m_regions);
  297. m_regions.append(*region);
  298. loader = make<ELFLoader>(region->laddr().as_ptr());
  299. loader->map_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, size_t offset_in_image, bool is_readable, bool is_writable, const String& name) {
  300. ASSERT(size);
  301. ASSERT(alignment == PAGE_SIZE);
  302. (void) allocate_region_with_vmo(laddr, size, vmo.copy_ref(), offset_in_image, String(name), is_readable, is_writable);
  303. return laddr.as_ptr();
  304. };
  305. loader->alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  306. ASSERT(size);
  307. ASSERT(alignment == PAGE_SIZE);
  308. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  309. return laddr.as_ptr();
  310. };
  311. bool success = loader->load();
  312. if (!success || !loader->entry().get()) {
  313. m_page_directory = move(old_page_directory);
  314. // FIXME: RAII this somehow instead.
  315. ASSERT(&current->process() == this);
  316. MM.enter_process_paging_scope(*this);
  317. m_regions = move(old_regions);
  318. kprintf("do_exec: Failure loading %s\n", path.characters());
  319. return -ENOEXEC;
  320. }
  321. entry_eip = loader->entry().get();
  322. }
  323. m_elf_loader = move(loader);
  324. current->m_kernel_stack_for_signal_handler_region = nullptr;
  325. current->m_signal_stack_user_region = nullptr;
  326. current->set_default_signal_dispositions();
  327. current->m_signal_mask = 0;
  328. current->m_pending_signals = 0;
  329. for (int i = 0; i < m_fds.size(); ++i) {
  330. auto& daf = m_fds[i];
  331. if (daf.descriptor && daf.flags & FD_CLOEXEC) {
  332. daf.descriptor->close();
  333. daf = { };
  334. }
  335. }
  336. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  337. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  338. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  339. if (&current->process() == this)
  340. cli();
  341. Scheduler::prepare_to_modify_tss(main_thread());
  342. m_name = parts.take_last();
  343. // ss0 sp!!!!!!!!!
  344. dword old_esp0 = main_thread().m_tss.esp0;
  345. memset(&main_thread().m_tss, 0, sizeof(main_thread().m_tss));
  346. main_thread().m_tss.eflags = 0x0202;
  347. main_thread().m_tss.eip = entry_eip;
  348. main_thread().m_tss.cs = 0x1b;
  349. main_thread().m_tss.ds = 0x23;
  350. main_thread().m_tss.es = 0x23;
  351. main_thread().m_tss.fs = 0x23;
  352. main_thread().m_tss.gs = 0x23;
  353. main_thread().m_tss.ss = 0x23;
  354. main_thread().m_tss.cr3 = page_directory().cr3();
  355. main_thread().make_userspace_stack_for_main_thread(move(arguments), move(environment));
  356. main_thread().m_tss.ss0 = 0x10;
  357. main_thread().m_tss.esp0 = old_esp0;
  358. main_thread().m_tss.ss2 = m_pid;
  359. m_executable = descriptor->inode();
  360. if (descriptor->metadata().is_setuid())
  361. m_euid = descriptor->metadata().uid;
  362. if (descriptor->metadata().is_setgid())
  363. m_egid = descriptor->metadata().gid;
  364. #ifdef TASK_DEBUG
  365. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), main_thread().tss().eip);
  366. #endif
  367. main_thread().set_state(Thread::State::Skip1SchedulerPass);
  368. return 0;
  369. }
  370. int Process::exec(String path, Vector<String> arguments, Vector<String> environment)
  371. {
  372. // The bulk of exec() is done by do_exec(), which ensures that all locals
  373. // are cleaned up by the time we yield-teleport below.
  374. int rc = do_exec(move(path), move(arguments), move(environment));
  375. if (rc < 0)
  376. return rc;
  377. if (&current->process() == this) {
  378. Scheduler::yield();
  379. ASSERT_NOT_REACHED();
  380. }
  381. return 0;
  382. }
  383. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  384. {
  385. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  386. // On success, the kernel stack will be lost.
  387. if (!validate_read_str(filename))
  388. return -EFAULT;
  389. if (!*filename)
  390. return -ENOENT;
  391. if (argv) {
  392. if (!validate_read_typed(argv))
  393. return -EFAULT;
  394. for (size_t i = 0; argv[i]; ++i) {
  395. if (!validate_read_str(argv[i]))
  396. return -EFAULT;
  397. }
  398. }
  399. if (envp) {
  400. if (!validate_read_typed(envp))
  401. return -EFAULT;
  402. for (size_t i = 0; envp[i]; ++i) {
  403. if (!validate_read_str(envp[i]))
  404. return -EFAULT;
  405. }
  406. }
  407. String path(filename);
  408. Vector<String> arguments;
  409. Vector<String> environment;
  410. {
  411. auto parts = path.split('/');
  412. if (argv) {
  413. for (size_t i = 0; argv[i]; ++i) {
  414. arguments.append(argv[i]);
  415. }
  416. } else {
  417. arguments.append(parts.last());
  418. }
  419. if (envp) {
  420. for (size_t i = 0; envp[i]; ++i)
  421. environment.append(envp[i]);
  422. }
  423. }
  424. int rc = exec(move(path), move(arguments), move(environment));
  425. ASSERT(rc < 0); // We should never continue after a successful exec!
  426. return rc;
  427. }
  428. Process* Process::create_user_process(const String& path, uid_t uid, gid_t gid, pid_t parent_pid, int& error, Vector<String>&& arguments, Vector<String>&& environment, TTY* tty)
  429. {
  430. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  431. auto parts = path.split('/');
  432. if (arguments.is_empty()) {
  433. arguments.append(parts.last());
  434. }
  435. RetainPtr<Inode> cwd;
  436. {
  437. InterruptDisabler disabler;
  438. if (auto* parent = Process::from_pid(parent_pid))
  439. cwd = parent->m_cwd.copy_ref();
  440. }
  441. if (!cwd)
  442. cwd = VFS::the().root_inode();
  443. auto* process = new Process(parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  444. error = process->exec(path, move(arguments), move(environment));
  445. if (error != 0) {
  446. delete process;
  447. return nullptr;
  448. }
  449. {
  450. InterruptDisabler disabler;
  451. g_processes->prepend(process);
  452. }
  453. #ifdef TASK_DEBUG
  454. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->main_thread().tss().eip);
  455. #endif
  456. error = 0;
  457. return process;
  458. }
  459. Process* Process::create_kernel_process(String&& name, void (*e)())
  460. {
  461. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  462. process->main_thread().tss().eip = (dword)e;
  463. if (process->pid() != 0) {
  464. InterruptDisabler disabler;
  465. g_processes->prepend(process);
  466. #ifdef TASK_DEBUG
  467. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->main_thread().tss().eip);
  468. #endif
  469. }
  470. process->main_thread().set_state(Thread::State::Runnable);
  471. return process;
  472. }
  473. static const dword userspace_range_base = 0x01000000;
  474. static const dword kernelspace_range_base = 0xc0000000;
  475. Process::Process(String&& name, uid_t uid, gid_t gid, pid_t ppid, RingLevel ring, RetainPtr<Inode>&& cwd, RetainPtr<Inode>&& executable, TTY* tty, Process* fork_parent)
  476. : m_name(move(name))
  477. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  478. , m_uid(uid)
  479. , m_gid(gid)
  480. , m_euid(uid)
  481. , m_egid(gid)
  482. , m_ring(ring)
  483. , m_cwd(move(cwd))
  484. , m_executable(move(executable))
  485. , m_tty(tty)
  486. , m_ppid(ppid)
  487. , m_range_allocator(LinearAddress(userspace_range_base), kernelspace_range_base - userspace_range_base)
  488. {
  489. dbgprintf("Process: New process PID=%u with name=%s\n", m_pid, m_name.characters());
  490. m_page_directory = PageDirectory::create();
  491. #ifdef MM_DEBUG
  492. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  493. #endif
  494. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the main thread in the new process.
  495. if (fork_parent)
  496. m_main_thread = current->clone(*this);
  497. else
  498. m_main_thread = new Thread(*this);
  499. m_gids.set(m_gid);
  500. if (fork_parent) {
  501. m_sid = fork_parent->m_sid;
  502. m_pgid = fork_parent->m_pgid;
  503. } else {
  504. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  505. InterruptDisabler disabler;
  506. if (auto* parent = Process::from_pid(m_ppid)) {
  507. m_sid = parent->m_sid;
  508. m_pgid = parent->m_pgid;
  509. }
  510. }
  511. if (fork_parent) {
  512. m_fds.resize(fork_parent->m_fds.size());
  513. for (int i = 0; i < fork_parent->m_fds.size(); ++i) {
  514. if (!fork_parent->m_fds[i].descriptor)
  515. continue;
  516. #ifdef FORK_DEBUG
  517. dbgprintf("fork: cloning fd %u... (%p) istty? %u\n", i, fork_parent->m_fds[i].descriptor.ptr(), fork_parent->m_fds[i].descriptor->is_tty());
  518. #endif
  519. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  520. m_fds[i].flags = fork_parent->m_fds[i].flags;
  521. }
  522. } else {
  523. m_fds.resize(m_max_open_file_descriptors);
  524. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  525. m_fds[0].set(*device_to_use_as_tty.open(O_RDONLY).value());
  526. m_fds[1].set(*device_to_use_as_tty.open(O_WRONLY).value());
  527. m_fds[2].set(*device_to_use_as_tty.open(O_WRONLY).value());
  528. }
  529. if (fork_parent) {
  530. m_sid = fork_parent->m_sid;
  531. m_pgid = fork_parent->m_pgid;
  532. m_umask = fork_parent->m_umask;
  533. }
  534. }
  535. Process::~Process()
  536. {
  537. dbgprintf("~Process{%p} name=%s pid=%d, m_fds=%d\n", this, m_name.characters(), pid(), m_fds.size());
  538. delete m_main_thread;
  539. m_main_thread = nullptr;
  540. Vector<Thread*, 16> my_threads;
  541. for_each_thread([&my_threads] (auto& thread) {
  542. my_threads.append(&thread);
  543. return IterationDecision::Continue;
  544. });
  545. for (auto* thread : my_threads)
  546. delete thread;
  547. }
  548. void Process::dump_regions()
  549. {
  550. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  551. kprintf("BEGIN END SIZE NAME\n");
  552. for (auto& region : m_regions) {
  553. kprintf("%x -- %x %x %s\n",
  554. region->laddr().get(),
  555. region->laddr().offset(region->size() - 1).get(),
  556. region->size(),
  557. region->name().characters());
  558. }
  559. }
  560. void Process::sys$exit(int status)
  561. {
  562. cli();
  563. #ifdef TASK_DEBUG
  564. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  565. #endif
  566. dump_backtrace();
  567. m_termination_status = status;
  568. m_termination_signal = 0;
  569. die();
  570. ASSERT_NOT_REACHED();
  571. }
  572. void Process::create_signal_trampolines_if_needed()
  573. {
  574. if (!m_return_to_ring3_from_signal_trampoline.is_null())
  575. return;
  576. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  577. // FIXME: Remap as read-only after setup.
  578. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "Signal trampolines", true, true);
  579. m_return_to_ring3_from_signal_trampoline = region->laddr();
  580. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.as_ptr();
  581. *code_ptr++ = 0x58; // pop eax (Argument to signal handler (ignored here))
  582. *code_ptr++ = 0x5a; // pop edx (Original signal mask to restore)
  583. *code_ptr++ = 0xb8; // mov eax, <dword>
  584. *(dword*)code_ptr = Syscall::SC_restore_signal_mask;
  585. code_ptr += sizeof(dword);
  586. *code_ptr++ = 0xcd; // int 0x82
  587. *code_ptr++ = 0x82;
  588. *code_ptr++ = 0x83; // add esp, (stack alignment padding)
  589. *code_ptr++ = 0xc4;
  590. *code_ptr++ = sizeof(dword) * 3;
  591. *code_ptr++ = 0x61; // popa
  592. *code_ptr++ = 0x9d; // popf
  593. *code_ptr++ = 0xc3; // ret
  594. *code_ptr++ = 0x0f; // ud2
  595. *code_ptr++ = 0x0b;
  596. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  597. *code_ptr++ = 0x58; // pop eax (Argument to signal handler (ignored here))
  598. *code_ptr++ = 0x5a; // pop edx (Original signal mask to restore)
  599. *code_ptr++ = 0xb8; // mov eax, <dword>
  600. *(dword*)code_ptr = Syscall::SC_restore_signal_mask;
  601. code_ptr += sizeof(dword);
  602. *code_ptr++ = 0xcd; // int 0x82
  603. // NOTE: Stack alignment padding doesn't matter when returning to ring0.
  604. // Nothing matters really, as we're returning by replacing the entire TSS.
  605. *code_ptr++ = 0x82;
  606. *code_ptr++ = 0xb8; // mov eax, <dword>
  607. *(dword*)code_ptr = Syscall::SC_sigreturn;
  608. code_ptr += sizeof(dword);
  609. *code_ptr++ = 0xcd; // int 0x82
  610. *code_ptr++ = 0x82;
  611. *code_ptr++ = 0x0f; // ud2
  612. *code_ptr++ = 0x0b;
  613. }
  614. int Process::sys$restore_signal_mask(dword mask)
  615. {
  616. current->m_signal_mask = mask;
  617. return 0;
  618. }
  619. void Process::sys$sigreturn()
  620. {
  621. InterruptDisabler disabler;
  622. Scheduler::prepare_to_modify_tss(*current);
  623. current->m_tss = *current->m_tss_to_resume_kernel;
  624. current->m_tss_to_resume_kernel.clear();
  625. #ifdef SIGNAL_DEBUG
  626. kprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  627. auto& tss = current->tss();
  628. kprintf(" -> resuming execution at %w:%x stack %w:%x flags %x cr3 %x\n", tss.cs, tss.eip, tss.ss, tss.esp, tss.eflags, tss.cr3);
  629. #endif
  630. current->set_state(Thread::State::Skip1SchedulerPass);
  631. Scheduler::yield();
  632. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  633. ASSERT_NOT_REACHED();
  634. }
  635. void Process::crash()
  636. {
  637. ASSERT_INTERRUPTS_DISABLED();
  638. ASSERT(!is_dead());
  639. dump_backtrace();
  640. m_termination_signal = SIGSEGV;
  641. dump_regions();
  642. ASSERT(is_ring3());
  643. die();
  644. ASSERT_NOT_REACHED();
  645. }
  646. Process* Process::from_pid(pid_t pid)
  647. {
  648. ASSERT_INTERRUPTS_DISABLED();
  649. for (auto* process = g_processes->head(); process; process = process->next()) {
  650. if (process->pid() == pid)
  651. return process;
  652. }
  653. return nullptr;
  654. }
  655. FileDescriptor* Process::file_descriptor(int fd)
  656. {
  657. if (fd < 0)
  658. return nullptr;
  659. if (fd < m_fds.size())
  660. return m_fds[fd].descriptor.ptr();
  661. return nullptr;
  662. }
  663. const FileDescriptor* Process::file_descriptor(int fd) const
  664. {
  665. if (fd < 0)
  666. return nullptr;
  667. if (fd < m_fds.size())
  668. return m_fds[fd].descriptor.ptr();
  669. return nullptr;
  670. }
  671. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, ssize_t size)
  672. {
  673. if (size < 0)
  674. return -EINVAL;
  675. if (!validate_write(buffer, size))
  676. return -EFAULT;
  677. auto* descriptor = file_descriptor(fd);
  678. if (!descriptor)
  679. return -EBADF;
  680. return descriptor->get_dir_entries((byte*)buffer, size);
  681. }
  682. int Process::sys$lseek(int fd, off_t offset, int whence)
  683. {
  684. auto* descriptor = file_descriptor(fd);
  685. if (!descriptor)
  686. return -EBADF;
  687. return descriptor->seek(offset, whence);
  688. }
  689. int Process::sys$ttyname_r(int fd, char* buffer, ssize_t size)
  690. {
  691. if (size < 0)
  692. return -EINVAL;
  693. if (!validate_write(buffer, size))
  694. return -EFAULT;
  695. auto* descriptor = file_descriptor(fd);
  696. if (!descriptor)
  697. return -EBADF;
  698. if (!descriptor->is_tty())
  699. return -ENOTTY;
  700. auto tty_name = descriptor->tty()->tty_name();
  701. if (size < tty_name.length() + 1)
  702. return -ERANGE;
  703. strcpy(buffer, tty_name.characters());
  704. return 0;
  705. }
  706. int Process::sys$ptsname_r(int fd, char* buffer, ssize_t size)
  707. {
  708. if (size < 0)
  709. return -EINVAL;
  710. if (!validate_write(buffer, size))
  711. return -EFAULT;
  712. auto* descriptor = file_descriptor(fd);
  713. if (!descriptor)
  714. return -EBADF;
  715. auto* master_pty = descriptor->master_pty();
  716. if (!master_pty)
  717. return -ENOTTY;
  718. auto pts_name = master_pty->pts_name();
  719. if (size < pts_name.length() + 1)
  720. return -ERANGE;
  721. strcpy(buffer, pts_name.characters());
  722. return 0;
  723. }
  724. ssize_t Process::sys$writev(int fd, const struct iovec* iov, int iov_count)
  725. {
  726. if (iov_count < 0)
  727. return -EINVAL;
  728. if (!validate_read_typed(iov, iov_count))
  729. return -EFAULT;
  730. // FIXME: Return EINVAL if sum of iovecs is greater than INT_MAX
  731. auto* descriptor = file_descriptor(fd);
  732. if (!descriptor)
  733. return -EBADF;
  734. int nwritten = 0;
  735. for (int i = 0; i < iov_count; ++i) {
  736. int rc = do_write(*descriptor, (const byte*)iov[i].iov_base, iov[i].iov_len);
  737. if (rc < 0) {
  738. if (nwritten == 0)
  739. return rc;
  740. return nwritten;
  741. }
  742. nwritten += rc;
  743. }
  744. if (current->has_unmasked_pending_signals()) {
  745. current->block(Thread::State::BlockedSignal);
  746. if (nwritten == 0)
  747. return -EINTR;
  748. }
  749. return nwritten;
  750. }
  751. ssize_t Process::do_write(FileDescriptor& descriptor, const byte* data, int data_size)
  752. {
  753. ssize_t nwritten = 0;
  754. if (!descriptor.is_blocking())
  755. return descriptor.write(data, data_size);
  756. while (nwritten < data_size) {
  757. #ifdef IO_DEBUG
  758. dbgprintf("while %u < %u\n", nwritten, size);
  759. #endif
  760. if (!descriptor.can_write()) {
  761. #ifdef IO_DEBUG
  762. dbgprintf("block write on %d\n", fd);
  763. #endif
  764. current->block(Thread::State::BlockedWrite, descriptor);
  765. }
  766. ssize_t rc = descriptor.write(data + nwritten, data_size - nwritten);
  767. #ifdef IO_DEBUG
  768. dbgprintf(" -> write returned %d\n", rc);
  769. #endif
  770. if (rc < 0) {
  771. // FIXME: Support returning partial nwritten with errno.
  772. ASSERT(nwritten == 0);
  773. return rc;
  774. }
  775. if (rc == 0)
  776. break;
  777. if (current->has_unmasked_pending_signals()) {
  778. current->block(Thread::State::BlockedSignal);
  779. if (nwritten == 0)
  780. return -EINTR;
  781. }
  782. nwritten += rc;
  783. }
  784. return nwritten;
  785. }
  786. ssize_t Process::sys$write(int fd, const byte* data, ssize_t size)
  787. {
  788. if (size < 0)
  789. return -EINVAL;
  790. if (size == 0)
  791. return 0;
  792. if (!validate_read(data, size))
  793. return -EFAULT;
  794. #ifdef DEBUG_IO
  795. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  796. #endif
  797. auto* descriptor = file_descriptor(fd);
  798. if (!descriptor)
  799. return -EBADF;
  800. auto nwritten = do_write(*descriptor, data, size);
  801. if (current->has_unmasked_pending_signals()) {
  802. current->block(Thread::State::BlockedSignal);
  803. if (nwritten == 0)
  804. return -EINTR;
  805. }
  806. return nwritten;
  807. }
  808. ssize_t Process::sys$read(int fd, byte* buffer, ssize_t size)
  809. {
  810. if (size < 0)
  811. return -EINVAL;
  812. if (size == 0)
  813. return 0;
  814. if (!validate_write(buffer, size))
  815. return -EFAULT;
  816. #ifdef DEBUG_IO
  817. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, buffer, size);
  818. #endif
  819. auto* descriptor = file_descriptor(fd);
  820. if (!descriptor)
  821. return -EBADF;
  822. if (descriptor->is_blocking()) {
  823. if (!descriptor->can_read()) {
  824. current->block(Thread::State::BlockedRead, *descriptor);
  825. if (current->m_was_interrupted_while_blocked)
  826. return -EINTR;
  827. }
  828. }
  829. return descriptor->read(buffer, size);
  830. }
  831. int Process::sys$close(int fd)
  832. {
  833. auto* descriptor = file_descriptor(fd);
  834. if (!descriptor)
  835. return -EBADF;
  836. int rc = descriptor->close();
  837. m_fds[fd] = { };
  838. return rc;
  839. }
  840. int Process::sys$utime(const char* pathname, const utimbuf* buf)
  841. {
  842. if (!validate_read_str(pathname))
  843. return -EFAULT;
  844. if (buf && !validate_read_typed(buf))
  845. return -EFAULT;
  846. time_t atime;
  847. time_t mtime;
  848. if (buf) {
  849. atime = buf->actime;
  850. mtime = buf->modtime;
  851. } else {
  852. struct timeval now;
  853. kgettimeofday(now);
  854. mtime = now.tv_sec;
  855. atime = now.tv_sec;
  856. }
  857. return VFS::the().utime(StringView(pathname), cwd_inode(), atime, mtime);
  858. }
  859. int Process::sys$access(const char* pathname, int mode)
  860. {
  861. if (!validate_read_str(pathname))
  862. return -EFAULT;
  863. return VFS::the().access(StringView(pathname), mode, cwd_inode());
  864. }
  865. int Process::sys$fcntl(int fd, int cmd, dword arg)
  866. {
  867. (void) cmd;
  868. (void) arg;
  869. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  870. auto* descriptor = file_descriptor(fd);
  871. if (!descriptor)
  872. return -EBADF;
  873. // NOTE: The FD flags are not shared between FileDescriptor objects.
  874. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  875. switch (cmd) {
  876. case F_DUPFD: {
  877. int arg_fd = (int)arg;
  878. if (arg_fd < 0)
  879. return -EINVAL;
  880. int new_fd = alloc_fd(arg_fd);
  881. if (new_fd < 0)
  882. return new_fd;
  883. m_fds[new_fd].set(*descriptor);
  884. break;
  885. }
  886. case F_GETFD:
  887. return m_fds[fd].flags;
  888. case F_SETFD:
  889. m_fds[fd].flags = arg;
  890. break;
  891. case F_GETFL:
  892. return descriptor->file_flags();
  893. case F_SETFL:
  894. // FIXME: Support changing O_NONBLOCK
  895. descriptor->set_file_flags(arg);
  896. break;
  897. default:
  898. ASSERT_NOT_REACHED();
  899. }
  900. return 0;
  901. }
  902. int Process::sys$fstat(int fd, stat* statbuf)
  903. {
  904. if (!validate_write_typed(statbuf))
  905. return -EFAULT;
  906. auto* descriptor = file_descriptor(fd);
  907. if (!descriptor)
  908. return -EBADF;
  909. return descriptor->fstat(*statbuf);
  910. }
  911. int Process::sys$lstat(const char* path, stat* statbuf)
  912. {
  913. if (!validate_write_typed(statbuf))
  914. return -EFAULT;
  915. return VFS::the().stat(StringView(path), O_NOFOLLOW_NOERROR, cwd_inode(), *statbuf);
  916. }
  917. int Process::sys$stat(const char* path, stat* statbuf)
  918. {
  919. if (!validate_write_typed(statbuf))
  920. return -EFAULT;
  921. return VFS::the().stat(StringView(path), O_NOFOLLOW_NOERROR, cwd_inode(), *statbuf);
  922. }
  923. int Process::sys$readlink(const char* path, char* buffer, ssize_t size)
  924. {
  925. if (size < 0)
  926. return -EINVAL;
  927. if (!validate_read_str(path))
  928. return -EFAULT;
  929. if (!validate_write(buffer, size))
  930. return -EFAULT;
  931. auto result = VFS::the().open(path, O_RDONLY | O_NOFOLLOW_NOERROR, 0, cwd_inode());
  932. if (result.is_error())
  933. return result.error();
  934. auto descriptor = result.value();
  935. if (!descriptor->metadata().is_symlink())
  936. return -EINVAL;
  937. auto contents = descriptor->read_entire_file();
  938. if (!contents)
  939. return -EIO; // FIXME: Get a more detailed error from VFS.
  940. memcpy(buffer, contents.pointer(), min(size, (ssize_t)contents.size()));
  941. if (contents.size() + 1 < size)
  942. buffer[contents.size()] = '\0';
  943. return 0;
  944. }
  945. int Process::sys$chdir(const char* path)
  946. {
  947. if (!validate_read_str(path))
  948. return -EFAULT;
  949. auto directory_or_error = VFS::the().open_directory(StringView(path), cwd_inode());
  950. if (directory_or_error.is_error())
  951. return directory_or_error.error();
  952. m_cwd = *directory_or_error.value();
  953. return 0;
  954. }
  955. int Process::sys$getcwd(char* buffer, ssize_t size)
  956. {
  957. if (size < 0)
  958. return -EINVAL;
  959. if (!validate_write(buffer, size))
  960. return -EFAULT;
  961. auto path_or_error = VFS::the().absolute_path(cwd_inode());
  962. if (path_or_error.is_error())
  963. return path_or_error.error();
  964. auto path = path_or_error.value();
  965. if (size < path.length() + 1)
  966. return -ERANGE;
  967. strcpy(buffer, path.characters());
  968. return 0;
  969. }
  970. int Process::number_of_open_file_descriptors() const
  971. {
  972. int count = 0;
  973. for (auto& descriptor : m_fds) {
  974. if (descriptor)
  975. ++count;
  976. }
  977. return count;
  978. }
  979. int Process::sys$open(const char* path, int options, mode_t mode)
  980. {
  981. #ifdef DEBUG_IO
  982. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  983. #endif
  984. if (!validate_read_str(path))
  985. return -EFAULT;
  986. int fd = alloc_fd();
  987. if (fd < 0)
  988. return fd;
  989. auto result = VFS::the().open(path, options, mode & ~umask(), cwd_inode());
  990. if (result.is_error())
  991. return result.error();
  992. auto descriptor = result.value();
  993. if (options & O_DIRECTORY && !descriptor->is_directory())
  994. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  995. if (options & O_NONBLOCK)
  996. descriptor->set_blocking(false);
  997. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  998. m_fds[fd].set(move(descriptor), flags);
  999. return fd;
  1000. }
  1001. int Process::alloc_fd(int first_candidate_fd)
  1002. {
  1003. int fd = -EMFILE;
  1004. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1005. if (!m_fds[i]) {
  1006. fd = i;
  1007. break;
  1008. }
  1009. }
  1010. return fd;
  1011. }
  1012. int Process::sys$pipe(int pipefd[2])
  1013. {
  1014. if (!validate_write_typed(pipefd))
  1015. return -EFAULT;
  1016. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1017. return -EMFILE;
  1018. auto fifo = FIFO::create(m_uid);
  1019. int reader_fd = alloc_fd();
  1020. m_fds[reader_fd].set(fifo->open_direction(FIFO::Reader));
  1021. pipefd[0] = reader_fd;
  1022. int writer_fd = alloc_fd();
  1023. m_fds[writer_fd].set(fifo->open_direction(FIFO::Writer));
  1024. pipefd[1] = writer_fd;
  1025. return 0;
  1026. }
  1027. int Process::sys$killpg(int pgrp, int signum)
  1028. {
  1029. if (signum < 1 || signum >= 32)
  1030. return -EINVAL;
  1031. (void) pgrp;
  1032. ASSERT_NOT_REACHED();
  1033. }
  1034. int Process::sys$setuid(uid_t uid)
  1035. {
  1036. if (uid != m_uid && !is_superuser())
  1037. return -EPERM;
  1038. m_uid = uid;
  1039. m_euid = uid;
  1040. return 0;
  1041. }
  1042. int Process::sys$setgid(gid_t gid)
  1043. {
  1044. if (gid != m_gid && !is_superuser())
  1045. return -EPERM;
  1046. m_gid = gid;
  1047. m_egid = gid;
  1048. return 0;
  1049. }
  1050. unsigned Process::sys$alarm(unsigned seconds)
  1051. {
  1052. (void) seconds;
  1053. ASSERT_NOT_REACHED();
  1054. }
  1055. int Process::sys$uname(utsname* buf)
  1056. {
  1057. if (!validate_write_typed(buf))
  1058. return -EFAULT;
  1059. strcpy(buf->sysname, "Serenity");
  1060. strcpy(buf->release, "1.0-dev");
  1061. strcpy(buf->version, "FIXME");
  1062. strcpy(buf->machine, "i386");
  1063. LOCKER(*s_hostname_lock);
  1064. strncpy(buf->nodename, s_hostname->characters(), sizeof(utsname::nodename));
  1065. return 0;
  1066. }
  1067. int Process::sys$isatty(int fd)
  1068. {
  1069. auto* descriptor = file_descriptor(fd);
  1070. if (!descriptor)
  1071. return -EBADF;
  1072. if (!descriptor->is_tty())
  1073. return -ENOTTY;
  1074. return 1;
  1075. }
  1076. int Process::sys$kill(pid_t pid, int signal)
  1077. {
  1078. if (signal < 0 || signal >= 32)
  1079. return -EINVAL;
  1080. if (pid == 0) {
  1081. // FIXME: Send to same-group processes.
  1082. ASSERT(pid != 0);
  1083. }
  1084. if (pid == -1) {
  1085. // FIXME: Send to all processes.
  1086. ASSERT(pid != -1);
  1087. }
  1088. if (pid == m_pid) {
  1089. current->send_signal(signal, this);
  1090. Scheduler::yield();
  1091. return 0;
  1092. }
  1093. InterruptDisabler disabler;
  1094. auto* peer = Process::from_pid(pid);
  1095. if (!peer)
  1096. return -ESRCH;
  1097. // FIXME: Allow sending SIGCONT to everyone in the process group.
  1098. // FIXME: Should setuid processes have some special treatment here?
  1099. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  1100. return -EPERM;
  1101. if (peer->is_ring0() && signal == SIGKILL) {
  1102. kprintf("%s(%u) attempted to send SIGKILL to ring 0 process %s(%u)\n", name().characters(), m_pid, peer->name().characters(), peer->pid());
  1103. return -EPERM;
  1104. }
  1105. peer->send_signal(signal, this);
  1106. return 0;
  1107. }
  1108. int Process::sys$usleep(useconds_t usec)
  1109. {
  1110. if (!usec)
  1111. return 0;
  1112. current->sleep(usec / 1000);
  1113. if (current->m_wakeup_time > g_uptime) {
  1114. ASSERT(current->m_was_interrupted_while_blocked);
  1115. dword ticks_left_until_original_wakeup_time = current->m_wakeup_time - g_uptime;
  1116. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1117. }
  1118. return 0;
  1119. }
  1120. int Process::sys$sleep(unsigned seconds)
  1121. {
  1122. if (!seconds)
  1123. return 0;
  1124. current->sleep(seconds * TICKS_PER_SECOND);
  1125. if (current->m_wakeup_time > g_uptime) {
  1126. ASSERT(current->m_was_interrupted_while_blocked);
  1127. dword ticks_left_until_original_wakeup_time = current->m_wakeup_time - g_uptime;
  1128. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1129. }
  1130. return 0;
  1131. }
  1132. void kgettimeofday(timeval& tv)
  1133. {
  1134. tv.tv_sec = RTC::boot_time() + PIT::seconds_since_boot();
  1135. tv.tv_usec = PIT::ticks_this_second() * 1000;
  1136. }
  1137. int Process::sys$gettimeofday(timeval* tv)
  1138. {
  1139. if (!validate_write_typed(tv))
  1140. return -EFAULT;
  1141. kgettimeofday(*tv);
  1142. return 0;
  1143. }
  1144. uid_t Process::sys$getuid()
  1145. {
  1146. return m_uid;
  1147. }
  1148. gid_t Process::sys$getgid()
  1149. {
  1150. return m_gid;
  1151. }
  1152. uid_t Process::sys$geteuid()
  1153. {
  1154. return m_euid;
  1155. }
  1156. gid_t Process::sys$getegid()
  1157. {
  1158. return m_egid;
  1159. }
  1160. pid_t Process::sys$getpid()
  1161. {
  1162. return m_pid;
  1163. }
  1164. pid_t Process::sys$getppid()
  1165. {
  1166. return m_ppid;
  1167. }
  1168. mode_t Process::sys$umask(mode_t mask)
  1169. {
  1170. auto old_mask = m_umask;
  1171. m_umask = mask & 0777;
  1172. return old_mask;
  1173. }
  1174. int Process::reap(Process& process)
  1175. {
  1176. int exit_status;
  1177. {
  1178. InterruptDisabler disabler;
  1179. exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1180. if (process.ppid()) {
  1181. auto* parent = Process::from_pid(process.ppid());
  1182. if (parent) {
  1183. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1184. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1185. }
  1186. }
  1187. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), to_string(process.state()));
  1188. ASSERT(process.is_dead());
  1189. g_processes->remove(&process);
  1190. }
  1191. delete &process;
  1192. return exit_status;
  1193. }
  1194. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1195. {
  1196. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1197. // FIXME: Respect options
  1198. (void) options;
  1199. if (wstatus)
  1200. if (!validate_write_typed(wstatus))
  1201. return -EFAULT;
  1202. int dummy_wstatus;
  1203. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1204. {
  1205. InterruptDisabler disabler;
  1206. if (waitee != -1 && !Process::from_pid(waitee))
  1207. return -ECHILD;
  1208. }
  1209. if (options & WNOHANG) {
  1210. if (waitee == -1) {
  1211. pid_t reaped_pid = 0;
  1212. InterruptDisabler disabler;
  1213. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1214. if (process.is_dead()) {
  1215. reaped_pid = process.pid();
  1216. exit_status = reap(process);
  1217. }
  1218. return true;
  1219. });
  1220. return reaped_pid;
  1221. } else {
  1222. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1223. InterruptDisabler disabler;
  1224. auto* waitee_process = Process::from_pid(waitee);
  1225. if (!waitee_process)
  1226. return -ECHILD;
  1227. if (waitee_process->is_dead()) {
  1228. exit_status = reap(*waitee_process);
  1229. return waitee;
  1230. }
  1231. return 0;
  1232. }
  1233. }
  1234. current->m_waitee_pid = waitee;
  1235. current->block(Thread::State::BlockedWait);
  1236. if (current->m_was_interrupted_while_blocked)
  1237. return -EINTR;
  1238. Process* waitee_process;
  1239. {
  1240. InterruptDisabler disabler;
  1241. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1242. waitee_process = Process::from_pid(current->m_waitee_pid);
  1243. }
  1244. ASSERT(waitee_process);
  1245. exit_status = reap(*waitee_process);
  1246. return current->m_waitee_pid;
  1247. }
  1248. enum class KernelMemoryCheckResult {
  1249. NotInsideKernelMemory,
  1250. AccessGranted,
  1251. AccessDenied
  1252. };
  1253. // FIXME: Nothing about this is really super...
  1254. // This structure is only present at offset 28 in the main multiboot info struct
  1255. // if bit 5 of offset 0 (flags) is set. We're just assuming that the flag is set.
  1256. //
  1257. // Also, there's almost certainly a better way to get that information here than
  1258. // a global set by boot.S
  1259. //
  1260. // Also I'm not 100% sure any of this is correct...
  1261. struct mb_elf {
  1262. uint32_t num;
  1263. uint32_t size;
  1264. uint32_t addr;
  1265. uint32_t shndx;
  1266. };
  1267. extern "C" {
  1268. void* multiboot_ptr;
  1269. }
  1270. static KernelMemoryCheckResult check_kernel_memory_access(LinearAddress laddr, bool is_write)
  1271. {
  1272. // FIXME: It would be better to have a proper structure for this...
  1273. auto* sections = (const mb_elf*)((const byte*)multiboot_ptr + 28);
  1274. auto* kernel_program_headers = (Elf32_Phdr*)(sections->addr);
  1275. for (unsigned i = 0; i < sections->num; ++i) {
  1276. auto& segment = kernel_program_headers[i];
  1277. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1278. continue;
  1279. if (laddr.get() < segment.p_vaddr || laddr.get() > (segment.p_vaddr + segment.p_memsz))
  1280. continue;
  1281. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1282. return KernelMemoryCheckResult::AccessDenied;
  1283. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1284. return KernelMemoryCheckResult::AccessDenied;
  1285. return KernelMemoryCheckResult::AccessGranted;
  1286. }
  1287. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1288. }
  1289. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1290. {
  1291. if (laddr.is_null())
  1292. return false;
  1293. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1294. // This code allows access outside of the known used address ranges to get caught.
  1295. auto kmc_result = check_kernel_memory_access(laddr, false);
  1296. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1297. return true;
  1298. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1299. return false;
  1300. if (is_kmalloc_address(laddr.as_ptr()))
  1301. return true;
  1302. return validate_read(laddr.as_ptr(), 1);
  1303. }
  1304. bool Process::validate_read_str(const char* str)
  1305. {
  1306. if (!validate_read(str, 1))
  1307. return false;
  1308. return validate_read(str, strlen(str) + 1);
  1309. }
  1310. bool Process::validate_read(const void* address, ssize_t size) const
  1311. {
  1312. ASSERT(size >= 0);
  1313. LinearAddress first_address((dword)address);
  1314. LinearAddress last_address = first_address.offset(size - 1);
  1315. if (is_ring0()) {
  1316. auto kmc_result = check_kernel_memory_access(first_address, false);
  1317. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1318. return true;
  1319. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1320. return false;
  1321. if (is_kmalloc_address(address))
  1322. return true;
  1323. }
  1324. ASSERT(size);
  1325. if (!size)
  1326. return false;
  1327. if (first_address.page_base() != last_address.page_base()) {
  1328. if (!MM.validate_user_read(*this, last_address))
  1329. return false;
  1330. }
  1331. return MM.validate_user_read(*this, first_address);
  1332. }
  1333. bool Process::validate_write(void* address, ssize_t size) const
  1334. {
  1335. ASSERT(size >= 0);
  1336. LinearAddress first_address((dword)address);
  1337. LinearAddress last_address = first_address.offset(size - 1);
  1338. if (is_ring0()) {
  1339. if (is_kmalloc_address(address))
  1340. return true;
  1341. auto kmc_result = check_kernel_memory_access(first_address, true);
  1342. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1343. return true;
  1344. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1345. return false;
  1346. }
  1347. if (!size)
  1348. return false;
  1349. if (first_address.page_base() != last_address.page_base()) {
  1350. if (!MM.validate_user_write(*this, last_address))
  1351. return false;
  1352. }
  1353. return MM.validate_user_write(*this, last_address);
  1354. }
  1355. pid_t Process::sys$getsid(pid_t pid)
  1356. {
  1357. if (pid == 0)
  1358. return m_sid;
  1359. InterruptDisabler disabler;
  1360. auto* process = Process::from_pid(pid);
  1361. if (!process)
  1362. return -ESRCH;
  1363. if (m_sid != process->m_sid)
  1364. return -EPERM;
  1365. return process->m_sid;
  1366. }
  1367. pid_t Process::sys$setsid()
  1368. {
  1369. InterruptDisabler disabler;
  1370. bool found_process_with_same_pgid_as_my_pid = false;
  1371. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1372. found_process_with_same_pgid_as_my_pid = true;
  1373. return false;
  1374. });
  1375. if (found_process_with_same_pgid_as_my_pid)
  1376. return -EPERM;
  1377. m_sid = m_pid;
  1378. m_pgid = m_pid;
  1379. return m_sid;
  1380. }
  1381. pid_t Process::sys$getpgid(pid_t pid)
  1382. {
  1383. if (pid == 0)
  1384. return m_pgid;
  1385. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1386. auto* process = Process::from_pid(pid);
  1387. if (!process)
  1388. return -ESRCH;
  1389. return process->m_pgid;
  1390. }
  1391. pid_t Process::sys$getpgrp()
  1392. {
  1393. return m_pgid;
  1394. }
  1395. static pid_t get_sid_from_pgid(pid_t pgid)
  1396. {
  1397. InterruptDisabler disabler;
  1398. auto* group_leader = Process::from_pid(pgid);
  1399. if (!group_leader)
  1400. return -1;
  1401. return group_leader->sid();
  1402. }
  1403. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1404. {
  1405. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1406. pid_t pid = specified_pid ? specified_pid : m_pid;
  1407. if (specified_pgid < 0)
  1408. return -EINVAL;
  1409. auto* process = Process::from_pid(pid);
  1410. if (!process)
  1411. return -ESRCH;
  1412. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1413. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1414. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1415. if (current_sid != new_sid) {
  1416. // Can't move a process between sessions.
  1417. return -EPERM;
  1418. }
  1419. // FIXME: There are more EPERM conditions to check for here..
  1420. process->m_pgid = new_pgid;
  1421. return 0;
  1422. }
  1423. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1424. {
  1425. auto* descriptor = file_descriptor(fd);
  1426. if (!descriptor)
  1427. return -EBADF;
  1428. if (!descriptor->is_file())
  1429. return -ENOTTY;
  1430. return descriptor->file()->ioctl(*descriptor, request, arg);
  1431. }
  1432. int Process::sys$getdtablesize()
  1433. {
  1434. return m_max_open_file_descriptors;
  1435. }
  1436. int Process::sys$dup(int old_fd)
  1437. {
  1438. auto* descriptor = file_descriptor(old_fd);
  1439. if (!descriptor)
  1440. return -EBADF;
  1441. int new_fd = alloc_fd(0);
  1442. if (new_fd < 0)
  1443. return new_fd;
  1444. m_fds[new_fd].set(*descriptor);
  1445. return new_fd;
  1446. }
  1447. int Process::sys$dup2(int old_fd, int new_fd)
  1448. {
  1449. auto* descriptor = file_descriptor(old_fd);
  1450. if (!descriptor)
  1451. return -EBADF;
  1452. if (new_fd < 0 || new_fd >= m_max_open_file_descriptors)
  1453. return -EINVAL;
  1454. m_fds[new_fd].set(*descriptor);
  1455. return new_fd;
  1456. }
  1457. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1458. {
  1459. if (old_set) {
  1460. if (!validate_write_typed(old_set))
  1461. return -EFAULT;
  1462. *old_set = current->m_signal_mask;
  1463. }
  1464. if (set) {
  1465. if (!validate_read_typed(set))
  1466. return -EFAULT;
  1467. switch (how) {
  1468. case SIG_BLOCK:
  1469. current->m_signal_mask &= ~(*set);
  1470. break;
  1471. case SIG_UNBLOCK:
  1472. current->m_signal_mask |= *set;
  1473. break;
  1474. case SIG_SETMASK:
  1475. current->m_signal_mask = *set;
  1476. break;
  1477. default:
  1478. return -EINVAL;
  1479. }
  1480. }
  1481. return 0;
  1482. }
  1483. int Process::sys$sigpending(sigset_t* set)
  1484. {
  1485. if (!validate_write_typed(set))
  1486. return -EFAULT;
  1487. *set = current->m_pending_signals;
  1488. return 0;
  1489. }
  1490. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1491. {
  1492. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1493. return -EINVAL;
  1494. if (!validate_read_typed(act))
  1495. return -EFAULT;
  1496. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1497. auto& action = current->m_signal_action_data[signum];
  1498. if (old_act) {
  1499. if (!validate_write_typed(old_act))
  1500. return -EFAULT;
  1501. old_act->sa_flags = action.flags;
  1502. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1503. }
  1504. action.flags = act->sa_flags;
  1505. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1506. return 0;
  1507. }
  1508. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  1509. {
  1510. if (count < 0)
  1511. return -EINVAL;
  1512. if (!count)
  1513. return m_gids.size();
  1514. if (count != (int)m_gids.size())
  1515. return -EINVAL;
  1516. if (!validate_write_typed(gids, m_gids.size()))
  1517. return -EFAULT;
  1518. size_t i = 0;
  1519. for (auto gid : m_gids)
  1520. gids[i++] = gid;
  1521. return 0;
  1522. }
  1523. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  1524. {
  1525. if (count < 0)
  1526. return -EINVAL;
  1527. if (!is_superuser())
  1528. return -EPERM;
  1529. if (!validate_read(gids, count))
  1530. return -EFAULT;
  1531. m_gids.clear();
  1532. m_gids.set(m_gid);
  1533. for (int i = 0; i < count; ++i)
  1534. m_gids.set(gids[i]);
  1535. return 0;
  1536. }
  1537. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1538. {
  1539. if (!validate_read_str(pathname))
  1540. return -EFAULT;
  1541. size_t pathname_length = strlen(pathname);
  1542. if (pathname_length == 0)
  1543. return -EINVAL;
  1544. if (pathname_length >= 255)
  1545. return -ENAMETOOLONG;
  1546. return VFS::the().mkdir(StringView(pathname, pathname_length), mode & ~umask(), cwd_inode());
  1547. }
  1548. clock_t Process::sys$times(tms* times)
  1549. {
  1550. if (!validate_write_typed(times))
  1551. return -EFAULT;
  1552. times->tms_utime = m_ticks_in_user;
  1553. times->tms_stime = m_ticks_in_kernel;
  1554. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1555. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1556. return g_uptime & 0x7fffffff;
  1557. }
  1558. int Process::sys$select(const Syscall::SC_select_params* params)
  1559. {
  1560. if (!validate_read_typed(params))
  1561. return -EFAULT;
  1562. if (params->writefds && !validate_read_typed(params->writefds))
  1563. return -EFAULT;
  1564. if (params->readfds && !validate_read_typed(params->readfds))
  1565. return -EFAULT;
  1566. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1567. return -EFAULT;
  1568. if (params->timeout && !validate_read_typed(params->timeout))
  1569. return -EFAULT;
  1570. int nfds = params->nfds;
  1571. fd_set* writefds = params->writefds;
  1572. fd_set* readfds = params->readfds;
  1573. fd_set* exceptfds = params->exceptfds;
  1574. auto* timeout = params->timeout;
  1575. // FIXME: Implement exceptfds support.
  1576. (void)exceptfds;
  1577. if (timeout) {
  1578. struct timeval now;
  1579. kgettimeofday(now);
  1580. AK::timeval_add(&now, timeout, &current->m_select_timeout);
  1581. current->m_select_has_timeout = true;
  1582. } else {
  1583. current->m_select_has_timeout = false;
  1584. }
  1585. if (nfds < 0)
  1586. return -EINVAL;
  1587. // FIXME: Return -EINTR if a signal is caught.
  1588. // FIXME: Return -EINVAL if timeout is invalid.
  1589. auto transfer_fds = [this, nfds] (fd_set* set, auto& vector) -> int {
  1590. vector.clear_with_capacity();
  1591. if (!set)
  1592. return 0;
  1593. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1594. for (int i = 0; i < nfds; ++i) {
  1595. if (bitmap.get(i)) {
  1596. if (!file_descriptor(i))
  1597. return -EBADF;
  1598. vector.append(i);
  1599. }
  1600. }
  1601. return 0;
  1602. };
  1603. int error = 0;
  1604. error = transfer_fds(writefds, current->m_select_write_fds);
  1605. if (error)
  1606. return error;
  1607. error = transfer_fds(readfds, current->m_select_read_fds);
  1608. if (error)
  1609. return error;
  1610. error = transfer_fds(exceptfds, current->m_select_exceptional_fds);
  1611. if (error)
  1612. return error;
  1613. #ifdef DEBUG_IO
  1614. dbgprintf("%s<%u> selecting on (read:%u, write:%u), timeout=%p\n", name().characters(), pid(), current->m_select_read_fds.size(), current->m_select_write_fds.size(), timeout);
  1615. #endif
  1616. if (!timeout || (timeout->tv_sec || timeout->tv_usec))
  1617. current->block(Thread::State::BlockedSelect);
  1618. int markedfds = 0;
  1619. if (readfds) {
  1620. memset(readfds, 0, sizeof(fd_set));
  1621. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1622. for (int fd : current->m_select_read_fds) {
  1623. auto* descriptor = file_descriptor(fd);
  1624. if (!descriptor)
  1625. continue;
  1626. if (descriptor->can_read()) {
  1627. bitmap.set(fd, true);
  1628. ++markedfds;
  1629. }
  1630. }
  1631. }
  1632. if (writefds) {
  1633. memset(writefds, 0, sizeof(fd_set));
  1634. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1635. for (int fd : current->m_select_write_fds) {
  1636. auto* descriptor = file_descriptor(fd);
  1637. if (!descriptor)
  1638. continue;
  1639. if (descriptor->can_write()) {
  1640. bitmap.set(fd, true);
  1641. ++markedfds;
  1642. }
  1643. }
  1644. }
  1645. // FIXME: Check for exceptional conditions.
  1646. return markedfds;
  1647. }
  1648. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1649. {
  1650. if (!validate_read_typed(fds))
  1651. return -EFAULT;
  1652. current->m_select_write_fds.clear_with_capacity();
  1653. current->m_select_read_fds.clear_with_capacity();
  1654. for (int i = 0; i < nfds; ++i) {
  1655. if (fds[i].events & POLLIN)
  1656. current->m_select_read_fds.append(fds[i].fd);
  1657. if (fds[i].events & POLLOUT)
  1658. current->m_select_write_fds.append(fds[i].fd);
  1659. }
  1660. // FIXME: this should set m_select_timeout, right?
  1661. if (timeout < 0)
  1662. current->block(Thread::State::BlockedSelect);
  1663. int fds_with_revents = 0;
  1664. for (int i = 0; i < nfds; ++i) {
  1665. auto* descriptor = file_descriptor(fds[i].fd);
  1666. if (!descriptor) {
  1667. fds[i].revents = POLLNVAL;
  1668. continue;
  1669. }
  1670. fds[i].revents = 0;
  1671. if (fds[i].events & POLLIN && descriptor->can_read())
  1672. fds[i].revents |= POLLIN;
  1673. if (fds[i].events & POLLOUT && descriptor->can_write())
  1674. fds[i].revents |= POLLOUT;
  1675. if (fds[i].revents)
  1676. ++fds_with_revents;
  1677. }
  1678. return fds_with_revents;
  1679. }
  1680. Inode& Process::cwd_inode()
  1681. {
  1682. // FIXME: This is retarded factoring.
  1683. if (!m_cwd)
  1684. m_cwd = VFS::the().root_inode();
  1685. return *m_cwd;
  1686. }
  1687. int Process::sys$link(const char* old_path, const char* new_path)
  1688. {
  1689. if (!validate_read_str(old_path))
  1690. return -EFAULT;
  1691. if (!validate_read_str(new_path))
  1692. return -EFAULT;
  1693. return VFS::the().link(StringView(old_path), StringView(new_path), cwd_inode());
  1694. }
  1695. int Process::sys$unlink(const char* pathname)
  1696. {
  1697. if (!validate_read_str(pathname))
  1698. return -EFAULT;
  1699. return VFS::the().unlink(StringView(pathname), cwd_inode());
  1700. }
  1701. int Process::sys$symlink(const char* target, const char* linkpath)
  1702. {
  1703. if (!validate_read_str(target))
  1704. return -EFAULT;
  1705. if (!validate_read_str(linkpath))
  1706. return -EFAULT;
  1707. return VFS::the().symlink(StringView(target), StringView(linkpath), cwd_inode());
  1708. }
  1709. int Process::sys$rmdir(const char* pathname)
  1710. {
  1711. if (!validate_read_str(pathname))
  1712. return -EFAULT;
  1713. return VFS::the().rmdir(StringView(pathname), cwd_inode());
  1714. }
  1715. int Process::sys$read_tsc(dword* lsw, dword* msw)
  1716. {
  1717. if (!validate_write_typed(lsw))
  1718. return -EFAULT;
  1719. if (!validate_write_typed(msw))
  1720. return -EFAULT;
  1721. read_tsc(*lsw, *msw);
  1722. return 0;
  1723. }
  1724. int Process::sys$chmod(const char* pathname, mode_t mode)
  1725. {
  1726. if (!validate_read_str(pathname))
  1727. return -EFAULT;
  1728. return VFS::the().chmod(StringView(pathname), mode, cwd_inode());
  1729. }
  1730. int Process::sys$fchmod(int fd, mode_t mode)
  1731. {
  1732. auto* descriptor = file_descriptor(fd);
  1733. if (!descriptor)
  1734. return -EBADF;
  1735. return descriptor->fchmod(mode);
  1736. }
  1737. int Process::sys$chown(const char* pathname, uid_t uid, gid_t gid)
  1738. {
  1739. if (!validate_read_str(pathname))
  1740. return -EFAULT;
  1741. return VFS::the().chown(StringView(pathname), uid, gid, cwd_inode());
  1742. }
  1743. void Process::finalize()
  1744. {
  1745. ASSERT(current == g_finalizer);
  1746. dbgprintf("Finalizing Process %s(%u)\n", m_name.characters(), m_pid);
  1747. m_fds.clear();
  1748. m_tty = nullptr;
  1749. disown_all_shared_buffers();
  1750. {
  1751. InterruptDisabler disabler;
  1752. if (auto* parent_process = Process::from_pid(m_ppid)) {
  1753. // FIXME(Thread): What should we do here? Should we look at all threads' signal actions?
  1754. if (parent_process->main_thread().m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  1755. // NOTE: If the parent doesn't care about this process, let it go.
  1756. m_ppid = 0;
  1757. } else {
  1758. parent_process->send_signal(SIGCHLD, this);
  1759. }
  1760. }
  1761. }
  1762. m_dead = true;
  1763. }
  1764. void Process::die()
  1765. {
  1766. if (m_tracer)
  1767. m_tracer->set_dead();
  1768. {
  1769. InterruptDisabler disabler;
  1770. for_each_thread([] (Thread& thread) {
  1771. if (thread.state() != Thread::State::Dead)
  1772. thread.set_state(Thread::State::Dying);
  1773. return IterationDecision::Continue;
  1774. });
  1775. }
  1776. if (!Scheduler::is_active())
  1777. Scheduler::pick_next_and_switch_now();
  1778. }
  1779. size_t Process::amount_virtual() const
  1780. {
  1781. size_t amount = 0;
  1782. for (auto& region : m_regions) {
  1783. amount += region->size();
  1784. }
  1785. return amount;
  1786. }
  1787. size_t Process::amount_resident() const
  1788. {
  1789. // FIXME: This will double count if multiple regions use the same physical page.
  1790. size_t amount = 0;
  1791. for (auto& region : m_regions) {
  1792. amount += region->amount_resident();
  1793. }
  1794. return amount;
  1795. }
  1796. size_t Process::amount_shared() const
  1797. {
  1798. // FIXME: This will double count if multiple regions use the same physical page.
  1799. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage retain counts,
  1800. // and each PhysicalPage is only retained by its VMObject. This needs to be refactored
  1801. // so that every Region contributes +1 retain to each of its PhysicalPages.
  1802. size_t amount = 0;
  1803. for (auto& region : m_regions) {
  1804. amount += region->amount_shared();
  1805. }
  1806. return amount;
  1807. }
  1808. int Process::sys$socket(int domain, int type, int protocol)
  1809. {
  1810. int fd = alloc_fd();
  1811. if (fd < 0)
  1812. return fd;
  1813. auto result = Socket::create(domain, type, protocol);
  1814. if (result.is_error())
  1815. return result.error();
  1816. auto descriptor = FileDescriptor::create(*result.value());
  1817. unsigned flags = 0;
  1818. if (type & SOCK_CLOEXEC)
  1819. flags |= FD_CLOEXEC;
  1820. if (type & SOCK_NONBLOCK)
  1821. descriptor->set_blocking(false);
  1822. m_fds[fd].set(move(descriptor), flags);
  1823. return fd;
  1824. }
  1825. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  1826. {
  1827. if (!validate_read(address, address_length))
  1828. return -EFAULT;
  1829. auto* descriptor = file_descriptor(sockfd);
  1830. if (!descriptor)
  1831. return -EBADF;
  1832. if (!descriptor->is_socket())
  1833. return -ENOTSOCK;
  1834. auto& socket = *descriptor->socket();
  1835. return socket.bind(address, address_length);
  1836. }
  1837. int Process::sys$listen(int sockfd, int backlog)
  1838. {
  1839. auto* descriptor = file_descriptor(sockfd);
  1840. if (!descriptor)
  1841. return -EBADF;
  1842. if (!descriptor->is_socket())
  1843. return -ENOTSOCK;
  1844. auto& socket = *descriptor->socket();
  1845. auto result = socket.listen(backlog);
  1846. if (result.is_error())
  1847. return result;
  1848. descriptor->set_socket_role(SocketRole::Listener);
  1849. return 0;
  1850. }
  1851. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  1852. {
  1853. if (!validate_write_typed(address_size))
  1854. return -EFAULT;
  1855. if (!validate_write(address, *address_size))
  1856. return -EFAULT;
  1857. int accepted_socket_fd = alloc_fd();
  1858. if (accepted_socket_fd < 0)
  1859. return accepted_socket_fd;
  1860. auto* accepting_socket_descriptor = file_descriptor(accepting_socket_fd);
  1861. if (!accepting_socket_descriptor)
  1862. return -EBADF;
  1863. if (!accepting_socket_descriptor->is_socket())
  1864. return -ENOTSOCK;
  1865. auto& socket = *accepting_socket_descriptor->socket();
  1866. if (!socket.can_accept()) {
  1867. ASSERT(!accepting_socket_descriptor->is_blocking());
  1868. return -EAGAIN;
  1869. }
  1870. auto accepted_socket = socket.accept();
  1871. ASSERT(accepted_socket);
  1872. bool success = accepted_socket->get_address(address, address_size);
  1873. ASSERT(success);
  1874. auto accepted_socket_descriptor = FileDescriptor::create(move(accepted_socket), SocketRole::Accepted);
  1875. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  1876. // I'm not sure if this matches other systems but it makes sense to me.
  1877. accepted_socket_descriptor->set_blocking(accepting_socket_descriptor->is_blocking());
  1878. m_fds[accepted_socket_fd].set(move(accepted_socket_descriptor), m_fds[accepting_socket_fd].flags);
  1879. return accepted_socket_fd;
  1880. }
  1881. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  1882. {
  1883. if (!validate_read(address, address_size))
  1884. return -EFAULT;
  1885. int fd = alloc_fd();
  1886. if (fd < 0)
  1887. return fd;
  1888. auto* descriptor = file_descriptor(sockfd);
  1889. if (!descriptor)
  1890. return -EBADF;
  1891. if (!descriptor->is_socket())
  1892. return -ENOTSOCK;
  1893. if (descriptor->socket_role() == SocketRole::Connected)
  1894. return -EISCONN;
  1895. auto& socket = *descriptor->socket();
  1896. descriptor->set_socket_role(SocketRole::Connecting);
  1897. auto result = socket.connect(*descriptor, address, address_size, descriptor->is_blocking() ? ShouldBlock::Yes : ShouldBlock::No);
  1898. if (result.is_error()) {
  1899. descriptor->set_socket_role(SocketRole::None);
  1900. return result;
  1901. }
  1902. descriptor->set_socket_role(SocketRole::Connected);
  1903. return 0;
  1904. }
  1905. ssize_t Process::sys$sendto(const Syscall::SC_sendto_params* params)
  1906. {
  1907. if (!validate_read_typed(params))
  1908. return -EFAULT;
  1909. int sockfd = params->sockfd;
  1910. const void* data = params->data;
  1911. size_t data_length = params->data_length;
  1912. int flags = params->flags;
  1913. auto* addr = (const sockaddr*)params->addr;
  1914. auto addr_length = (socklen_t)params->addr_length;
  1915. if (!validate_read(data, data_length))
  1916. return -EFAULT;
  1917. if (addr && !validate_read(addr, addr_length))
  1918. return -EFAULT;
  1919. auto* descriptor = file_descriptor(sockfd);
  1920. if (!descriptor)
  1921. return -EBADF;
  1922. if (!descriptor->is_socket())
  1923. return -ENOTSOCK;
  1924. auto& socket = *descriptor->socket();
  1925. kprintf("sendto %p (%u), flags=%u, addr: %p (%u)\n", data, data_length, flags, addr, addr_length);
  1926. return socket.sendto(*descriptor, data, data_length, flags, addr, addr_length);
  1927. }
  1928. ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* params)
  1929. {
  1930. if (!validate_read_typed(params))
  1931. return -EFAULT;
  1932. int sockfd = params->sockfd;
  1933. void* buffer = params->buffer;
  1934. size_t buffer_length = params->buffer_length;
  1935. int flags = params->flags;
  1936. auto* addr = (sockaddr*)params->addr;
  1937. auto* addr_length = (socklen_t*)params->addr_length;
  1938. if (!validate_write(buffer, buffer_length))
  1939. return -EFAULT;
  1940. if (addr_length) {
  1941. if (!validate_write_typed(addr_length))
  1942. return -EFAULT;
  1943. if (!validate_write(addr, *addr_length))
  1944. return -EFAULT;
  1945. } else if (addr) {
  1946. return -EINVAL;
  1947. }
  1948. auto* descriptor = file_descriptor(sockfd);
  1949. if (!descriptor)
  1950. return -EBADF;
  1951. if (!descriptor->is_socket())
  1952. return -ENOTSOCK;
  1953. auto& socket = *descriptor->socket();
  1954. kprintf("recvfrom %p (%u), flags=%u, addr: %p (%p)\n", buffer, buffer_length, flags, addr, addr_length);
  1955. return socket.recvfrom(*descriptor, buffer, buffer_length, flags, addr, addr_length);
  1956. }
  1957. int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params)
  1958. {
  1959. if (!validate_read_typed(params))
  1960. return -EFAULT;
  1961. int sockfd = params->sockfd;
  1962. int level = params->level;
  1963. int option = params->option;
  1964. auto* value = params->value;
  1965. auto* value_size = (socklen_t*)params->value_size;
  1966. if (!validate_write_typed(value_size))
  1967. return -EFAULT;
  1968. if (!validate_write(value, *value_size))
  1969. return -EFAULT;
  1970. auto* descriptor = file_descriptor(sockfd);
  1971. if (!descriptor)
  1972. return -EBADF;
  1973. if (!descriptor->is_socket())
  1974. return -ENOTSOCK;
  1975. auto& socket = *descriptor->socket();
  1976. return socket.getsockopt(level, option, value, value_size);
  1977. }
  1978. int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params)
  1979. {
  1980. if (!validate_read_typed(params))
  1981. return -EFAULT;
  1982. int sockfd = params->sockfd;
  1983. int level = params->level;
  1984. int option = params->option;
  1985. auto* value = params->value;
  1986. auto value_size = (socklen_t)params->value_size;
  1987. if (!validate_read(value, value_size))
  1988. return -EFAULT;
  1989. auto* descriptor = file_descriptor(sockfd);
  1990. if (!descriptor)
  1991. return -EBADF;
  1992. if (!descriptor->is_socket())
  1993. return -ENOTSOCK;
  1994. auto& socket = *descriptor->socket();
  1995. return socket.setsockopt(level, option, value, value_size);
  1996. }
  1997. struct SharedBuffer {
  1998. SharedBuffer(pid_t pid1, pid_t pid2, int size)
  1999. : m_pid1(pid1)
  2000. , m_pid2(pid2)
  2001. , m_vmo(VMObject::create_anonymous(size))
  2002. {
  2003. ASSERT(pid1 != pid2);
  2004. }
  2005. void* retain(Process& process)
  2006. {
  2007. if (m_pid1 == process.pid()) {
  2008. ++m_pid1_retain_count;
  2009. if (!m_pid1_region) {
  2010. m_pid1_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, m_pid1_writable);
  2011. m_pid1_region->set_shared(true);
  2012. }
  2013. return m_pid1_region->laddr().as_ptr();
  2014. } else if (m_pid2 == process.pid()) {
  2015. ++m_pid2_retain_count;
  2016. if (!m_pid2_region) {
  2017. m_pid2_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, m_pid2_writable);
  2018. m_pid2_region->set_shared(true);
  2019. }
  2020. return m_pid2_region->laddr().as_ptr();
  2021. }
  2022. return nullptr;
  2023. }
  2024. void release(Process& process)
  2025. {
  2026. if (m_pid1 == process.pid()) {
  2027. ASSERT(m_pid1_retain_count);
  2028. --m_pid1_retain_count;
  2029. if (!m_pid1_retain_count) {
  2030. if (m_pid1_region)
  2031. process.deallocate_region(*m_pid1_region);
  2032. m_pid1_region = nullptr;
  2033. }
  2034. destroy_if_unused();
  2035. } else if (m_pid2 == process.pid()) {
  2036. ASSERT(m_pid2_retain_count);
  2037. --m_pid2_retain_count;
  2038. if (!m_pid2_retain_count) {
  2039. if (m_pid2_region)
  2040. process.deallocate_region(*m_pid2_region);
  2041. m_pid2_region = nullptr;
  2042. }
  2043. destroy_if_unused();
  2044. }
  2045. }
  2046. void disown(pid_t pid)
  2047. {
  2048. if (m_pid1 == pid) {
  2049. m_pid1 = 0;
  2050. m_pid1_retain_count = 0;
  2051. destroy_if_unused();
  2052. } else if (m_pid2 == pid) {
  2053. m_pid2 = 0;
  2054. m_pid2_retain_count = 0;
  2055. destroy_if_unused();
  2056. }
  2057. }
  2058. pid_t pid1() const { return m_pid1; }
  2059. pid_t pid2() const { return m_pid2; }
  2060. unsigned pid1_retain_count() const { return m_pid1_retain_count; }
  2061. unsigned pid2_retain_count() const { return m_pid2_retain_count; }
  2062. size_t size() const { return m_vmo->size(); }
  2063. void destroy_if_unused();
  2064. void seal()
  2065. {
  2066. m_pid1_writable = false;
  2067. m_pid2_writable = false;
  2068. if (m_pid1_region) {
  2069. m_pid1_region->set_writable(false);
  2070. MM.remap_region(*m_pid1_region->page_directory(), *m_pid1_region);
  2071. }
  2072. if (m_pid2_region) {
  2073. m_pid2_region->set_writable(false);
  2074. MM.remap_region(*m_pid2_region->page_directory(), *m_pid2_region);
  2075. }
  2076. }
  2077. int m_shared_buffer_id { -1 };
  2078. pid_t m_pid1;
  2079. pid_t m_pid2;
  2080. unsigned m_pid1_retain_count { 1 };
  2081. unsigned m_pid2_retain_count { 0 };
  2082. Region* m_pid1_region { nullptr };
  2083. Region* m_pid2_region { nullptr };
  2084. bool m_pid1_writable { false };
  2085. bool m_pid2_writable { false };
  2086. Retained<VMObject> m_vmo;
  2087. };
  2088. static int s_next_shared_buffer_id;
  2089. Lockable<HashMap<int, OwnPtr<SharedBuffer>>>& shared_buffers()
  2090. {
  2091. static Lockable<HashMap<int, OwnPtr<SharedBuffer>>>* map;
  2092. if (!map)
  2093. map = new Lockable<HashMap<int, OwnPtr<SharedBuffer>>>;
  2094. return *map;
  2095. }
  2096. void SharedBuffer::destroy_if_unused()
  2097. {
  2098. if (!m_pid1_retain_count && !m_pid2_retain_count) {
  2099. LOCKER(shared_buffers().lock());
  2100. #ifdef SHARED_BUFFER_DEBUG
  2101. kprintf("Destroying unused SharedBuffer{%p} id: %d (pid1: %d, pid2: %d)\n", this, m_shared_buffer_id, m_pid1, m_pid2);
  2102. #endif
  2103. auto count_before = shared_buffers().resource().size();
  2104. shared_buffers().resource().remove(m_shared_buffer_id);
  2105. ASSERT(count_before != shared_buffers().resource().size());
  2106. }
  2107. }
  2108. void Process::disown_all_shared_buffers()
  2109. {
  2110. LOCKER(shared_buffers().lock());
  2111. Vector<SharedBuffer*, 32> buffers_to_disown;
  2112. for (auto& it : shared_buffers().resource())
  2113. buffers_to_disown.append(it.value.ptr());
  2114. for (auto* shared_buffer : buffers_to_disown)
  2115. shared_buffer->disown(m_pid);
  2116. }
  2117. int Process::sys$create_shared_buffer(pid_t peer_pid, int size, void** buffer)
  2118. {
  2119. if (!size || size < 0)
  2120. return -EINVAL;
  2121. size = PAGE_ROUND_UP(size);
  2122. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2123. return -EINVAL;
  2124. if (!validate_write_typed(buffer))
  2125. return -EFAULT;
  2126. {
  2127. InterruptDisabler disabler;
  2128. auto* peer = Process::from_pid(peer_pid);
  2129. if (!peer)
  2130. return -ESRCH;
  2131. }
  2132. LOCKER(shared_buffers().lock());
  2133. int shared_buffer_id = ++s_next_shared_buffer_id;
  2134. auto shared_buffer = make<SharedBuffer>(m_pid, peer_pid, size);
  2135. shared_buffer->m_shared_buffer_id = shared_buffer_id;
  2136. ASSERT(shared_buffer->size() >= size);
  2137. shared_buffer->m_pid1_region = allocate_region_with_vmo(LinearAddress(), shared_buffer->size(), shared_buffer->m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2138. shared_buffer->m_pid1_region->set_shared(true);
  2139. *buffer = shared_buffer->m_pid1_region->laddr().as_ptr();
  2140. #ifdef SHARED_BUFFER_DEBUG
  2141. kprintf("%s(%u): Created shared buffer %d (%u bytes, vmo is %u) for sharing with %d\n", name().characters(), pid(),shared_buffer_id, size, shared_buffer->size(), peer_pid);
  2142. #endif
  2143. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2144. return shared_buffer_id;
  2145. }
  2146. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2147. {
  2148. LOCKER(shared_buffers().lock());
  2149. auto it = shared_buffers().resource().find(shared_buffer_id);
  2150. if (it == shared_buffers().resource().end())
  2151. return -EINVAL;
  2152. auto& shared_buffer = *(*it).value;
  2153. #ifdef SHARED_BUFFER_DEBUG
  2154. kprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2155. #endif
  2156. shared_buffer.release(*this);
  2157. return 0;
  2158. }
  2159. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2160. {
  2161. LOCKER(shared_buffers().lock());
  2162. auto it = shared_buffers().resource().find(shared_buffer_id);
  2163. if (it == shared_buffers().resource().end())
  2164. return (void*)-EINVAL;
  2165. auto& shared_buffer = *(*it).value;
  2166. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2167. return (void*)-EINVAL;
  2168. #ifdef SHARED_BUFFER_DEBUG
  2169. kprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2170. #endif
  2171. return shared_buffer.retain(*this);
  2172. }
  2173. int Process::sys$seal_shared_buffer(int shared_buffer_id)
  2174. {
  2175. LOCKER(shared_buffers().lock());
  2176. auto it = shared_buffers().resource().find(shared_buffer_id);
  2177. if (it == shared_buffers().resource().end())
  2178. return -EINVAL;
  2179. auto& shared_buffer = *(*it).value;
  2180. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2181. return -EINVAL;
  2182. #ifdef SHARED_BUFFER_DEBUG
  2183. kprintf("%s(%u): Sealing shared buffer %d\n", name().characters(), pid(), shared_buffer_id);
  2184. #endif
  2185. shared_buffer.seal();
  2186. return 0;
  2187. }
  2188. int Process::sys$get_shared_buffer_size(int shared_buffer_id)
  2189. {
  2190. LOCKER(shared_buffers().lock());
  2191. auto it = shared_buffers().resource().find(shared_buffer_id);
  2192. if (it == shared_buffers().resource().end())
  2193. return -EINVAL;
  2194. auto& shared_buffer = *(*it).value;
  2195. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2196. return -EINVAL;
  2197. #ifdef SHARED_BUFFER_DEBUG
  2198. kprintf("%s(%u): Get shared buffer %d size: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2199. #endif
  2200. return shared_buffer.size();
  2201. }
  2202. const char* to_string(Process::Priority priority)
  2203. {
  2204. switch (priority) {
  2205. case Process::IdlePriority: return "Idle";
  2206. case Process::LowPriority: return "Low";
  2207. case Process::NormalPriority: return "Normal";
  2208. case Process::HighPriority: return "High";
  2209. }
  2210. kprintf("to_string(Process::Priority): Invalid priority: %u\n", priority);
  2211. ASSERT_NOT_REACHED();
  2212. return nullptr;
  2213. }
  2214. void Process::terminate_due_to_signal(byte signal)
  2215. {
  2216. ASSERT_INTERRUPTS_DISABLED();
  2217. ASSERT(signal < 32);
  2218. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  2219. m_termination_status = 0;
  2220. m_termination_signal = signal;
  2221. die();
  2222. }
  2223. void Process::send_signal(byte signal, Process* sender)
  2224. {
  2225. // FIXME(Thread): Find the appropriate thread to deliver the signal to.
  2226. main_thread().send_signal(signal, sender);
  2227. }
  2228. int Process::thread_count() const
  2229. {
  2230. int count = 0;
  2231. for_each_thread([&count] (auto&) {
  2232. ++count;
  2233. return IterationDecision::Continue;
  2234. });
  2235. return count;
  2236. }
  2237. int Process::sys$create_thread(int(*entry)(void*), void* argument)
  2238. {
  2239. if (!validate_read((const void*)entry, sizeof(void*)))
  2240. return -EFAULT;
  2241. auto* thread = new Thread(*this);
  2242. auto& tss = thread->tss();
  2243. tss.eip = (dword)entry;
  2244. tss.eflags = 0x0202;
  2245. tss.cr3 = page_directory().cr3();
  2246. thread->make_userspace_stack_for_secondary_thread(argument);
  2247. thread->set_state(Thread::State::Runnable);
  2248. return 0;
  2249. }
  2250. void Process::sys$exit_thread(int code)
  2251. {
  2252. cli();
  2253. if (&current->process().main_thread() == current) {
  2254. sys$exit(code);
  2255. return;
  2256. }
  2257. current->set_state(Thread::State::Dying);
  2258. big_lock().unlock_if_locked();
  2259. Scheduler::pick_next_and_switch_now();
  2260. ASSERT_NOT_REACHED();
  2261. }
  2262. int Process::sys$gettid()
  2263. {
  2264. return current->tid();
  2265. }
  2266. int Process::sys$donate(int tid)
  2267. {
  2268. if (tid < 0)
  2269. return -EINVAL;
  2270. InterruptDisabler disabler;
  2271. Thread* beneficiary = nullptr;
  2272. for_each_thread([&] (Thread& thread) {
  2273. if (thread.tid() == tid) {
  2274. beneficiary = &thread;
  2275. return IterationDecision::Abort;
  2276. }
  2277. return IterationDecision::Continue;
  2278. });
  2279. if (!beneficiary)
  2280. return -ENOTHREAD;
  2281. Scheduler::donate_to(beneficiary, "sys$donate");
  2282. return 0;
  2283. }
  2284. int Process::sys$rename(const char* oldpath, const char* newpath)
  2285. {
  2286. if (!validate_read_str(oldpath))
  2287. return -EFAULT;
  2288. if (!validate_read_str(newpath))
  2289. return -EFAULT;
  2290. return VFS::the().rename(StringView(oldpath), StringView(newpath), cwd_inode());
  2291. }
  2292. int Process::sys$shm_open(const char* name, int flags, mode_t mode)
  2293. {
  2294. if (!validate_read_str(name))
  2295. return -EFAULT;
  2296. int fd = alloc_fd();
  2297. if (fd < 0)
  2298. return fd;
  2299. auto shm_or_error = SharedMemory::open(String(name), flags, mode);
  2300. if (shm_or_error.is_error())
  2301. return shm_or_error.error();
  2302. auto descriptor = FileDescriptor::create(shm_or_error.value().ptr());
  2303. m_fds[fd].set(move(descriptor), FD_CLOEXEC);
  2304. return fd;
  2305. }
  2306. int Process::sys$shm_unlink(const char* name)
  2307. {
  2308. if (!validate_read_str(name))
  2309. return -EFAULT;
  2310. return SharedMemory::unlink(String(name));
  2311. }
  2312. int Process::sys$ftruncate(int fd, off_t length)
  2313. {
  2314. auto* descriptor = file_descriptor(fd);
  2315. if (!descriptor)
  2316. return -EBADF;
  2317. // FIXME: Check that fd is writable, otherwise EINVAL.
  2318. if (!descriptor->is_file() && !descriptor->is_shared_memory())
  2319. return -EINVAL;
  2320. return descriptor->truncate(length);
  2321. }
  2322. int Process::sys$systrace(pid_t pid)
  2323. {
  2324. InterruptDisabler disabler;
  2325. auto* peer = Process::from_pid(pid);
  2326. if (!peer)
  2327. return -ESRCH;
  2328. if (peer->uid() != m_euid)
  2329. return -EACCES;
  2330. int fd = alloc_fd();
  2331. if (fd < 0)
  2332. return fd;
  2333. auto descriptor = FileDescriptor::create(peer->ensure_tracer());
  2334. m_fds[fd].set(move(descriptor), 0);
  2335. return fd;
  2336. }
  2337. ProcessTracer& Process::ensure_tracer()
  2338. {
  2339. if (!m_tracer)
  2340. m_tracer = ProcessTracer::create(m_pid);
  2341. return *m_tracer;
  2342. }
  2343. void Process::FileDescriptorAndFlags::clear()
  2344. {
  2345. descriptor = nullptr;
  2346. flags = 0;
  2347. }
  2348. void Process::FileDescriptorAndFlags::set(Retained<FileDescriptor>&& d, dword f)
  2349. {
  2350. descriptor = move(d);
  2351. flags = f;
  2352. }
  2353. int Process::sys$mknod(const char* pathname, mode_t mode, dev_t dev)
  2354. {
  2355. if (!validate_read_str(pathname))
  2356. return -EFAULT;
  2357. return VFS::the().mknod(StringView(pathname), mode, dev, cwd_inode());
  2358. }