Process.cpp 77 KB

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