Process.cpp 77 KB

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