Process.cpp 74 KB

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