Process.cpp 82 KB

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