Process.cpp 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647
  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/Arch/i386/PIT.h>
  9. #include <Kernel/Devices/NullDevice.h>
  10. #include <Kernel/FileSystem/Custody.h>
  11. #include <Kernel/FileSystem/FIFO.h>
  12. #include <Kernel/FileSystem/FileDescription.h>
  13. #include <Kernel/FileSystem/SharedMemory.h>
  14. #include <Kernel/FileSystem/VirtualFileSystem.h>
  15. #include <Kernel/KSyms.h>
  16. #include <Kernel/Multiboot.h>
  17. #include <Kernel/Net/Socket.h>
  18. #include <Kernel/Process.h>
  19. #include <Kernel/ProcessTracer.h>
  20. #include <Kernel/RTC.h>
  21. #include <Kernel/Scheduler.h>
  22. #include <Kernel/StdLib.h>
  23. #include <Kernel/SharedBuffer.h>
  24. #include <Kernel/Syscall.h>
  25. #include <Kernel/TTY/MasterPTY.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, m_executable, 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, 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, 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;
  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. if (!options) {
  1249. // FIXME: This can't be right.. can it? Figure out how this should actually work.
  1250. options = WEXITED;
  1251. }
  1252. if (wstatus)
  1253. if (!validate_write_typed(wstatus))
  1254. return -EFAULT;
  1255. int dummy_wstatus;
  1256. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1257. {
  1258. InterruptDisabler disabler;
  1259. if (waitee != -1 && !Process::from_pid(waitee))
  1260. return -ECHILD;
  1261. }
  1262. if (options & WNOHANG) {
  1263. // FIXME: Figure out what WNOHANG should do with stopped children.
  1264. if (waitee == -1) {
  1265. pid_t reaped_pid = 0;
  1266. InterruptDisabler disabler;
  1267. for_each_child([&reaped_pid, &exit_status](Process& process) {
  1268. if (process.is_dead()) {
  1269. reaped_pid = process.pid();
  1270. exit_status = reap(process);
  1271. }
  1272. return IterationDecision::Continue;
  1273. });
  1274. return reaped_pid;
  1275. } else {
  1276. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1277. InterruptDisabler disabler;
  1278. auto* waitee_process = Process::from_pid(waitee);
  1279. if (!waitee_process)
  1280. return -ECHILD;
  1281. if (waitee_process->is_dead()) {
  1282. exit_status = reap(*waitee_process);
  1283. return waitee;
  1284. }
  1285. return 0;
  1286. }
  1287. }
  1288. current->m_waitee_pid = waitee;
  1289. current->m_wait_options = options;
  1290. current->block(Thread::State::BlockedWait);
  1291. if (current->m_was_interrupted_while_blocked)
  1292. return -EINTR;
  1293. InterruptDisabler disabler;
  1294. // NOTE: If waitee was -1, m_waitee_pid will have been filled in by the scheduler.
  1295. Process* waitee_process = Process::from_pid(current->m_waitee_pid);
  1296. ASSERT(waitee_process);
  1297. if (waitee_process->is_dead()) {
  1298. exit_status = reap(*waitee_process);
  1299. } else {
  1300. ASSERT(waitee_process->main_thread().state() == Thread::State::Stopped);
  1301. exit_status = 0x7f;
  1302. }
  1303. return current->m_waitee_pid;
  1304. }
  1305. enum class KernelMemoryCheckResult {
  1306. NotInsideKernelMemory,
  1307. AccessGranted,
  1308. AccessDenied
  1309. };
  1310. static KernelMemoryCheckResult check_kernel_memory_access(VirtualAddress vaddr, bool is_write)
  1311. {
  1312. auto& sections = multiboot_info_ptr->u.elf_sec;
  1313. auto* kernel_program_headers = (Elf32_Phdr*)(sections.addr);
  1314. for (unsigned i = 0; i < sections.num; ++i) {
  1315. auto& segment = kernel_program_headers[i];
  1316. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1317. continue;
  1318. if (vaddr.get() < segment.p_vaddr || vaddr.get() > (segment.p_vaddr + segment.p_memsz))
  1319. continue;
  1320. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1321. return KernelMemoryCheckResult::AccessDenied;
  1322. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1323. return KernelMemoryCheckResult::AccessDenied;
  1324. return KernelMemoryCheckResult::AccessGranted;
  1325. }
  1326. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1327. }
  1328. bool Process::validate_read_from_kernel(VirtualAddress vaddr) const
  1329. {
  1330. if (vaddr.is_null())
  1331. return false;
  1332. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1333. // This code allows access outside of the known used address ranges to get caught.
  1334. auto kmc_result = check_kernel_memory_access(vaddr, false);
  1335. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1336. return true;
  1337. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1338. return false;
  1339. if (is_kmalloc_address(vaddr.as_ptr()))
  1340. return true;
  1341. return validate_read(vaddr.as_ptr(), 1);
  1342. }
  1343. bool Process::validate_read_str(const char* str)
  1344. {
  1345. if (!validate_read(str, 1))
  1346. return false;
  1347. return validate_read(str, strlen(str) + 1);
  1348. }
  1349. bool Process::validate_read(const void* address, ssize_t size) const
  1350. {
  1351. ASSERT(size >= 0);
  1352. VirtualAddress first_address((u32)address);
  1353. VirtualAddress last_address = first_address.offset(size - 1);
  1354. if (is_ring0()) {
  1355. auto kmc_result = check_kernel_memory_access(first_address, false);
  1356. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1357. return true;
  1358. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1359. return false;
  1360. if (is_kmalloc_address(address))
  1361. return true;
  1362. }
  1363. ASSERT(size);
  1364. if (!size)
  1365. return false;
  1366. if (first_address.page_base() != last_address.page_base()) {
  1367. if (!MM.validate_user_read(*this, last_address))
  1368. return false;
  1369. }
  1370. return MM.validate_user_read(*this, first_address);
  1371. }
  1372. bool Process::validate_write(void* address, ssize_t size) const
  1373. {
  1374. ASSERT(size >= 0);
  1375. VirtualAddress first_address((u32)address);
  1376. VirtualAddress last_address = first_address.offset(size - 1);
  1377. if (is_ring0()) {
  1378. if (is_kmalloc_address(address))
  1379. return true;
  1380. auto kmc_result = check_kernel_memory_access(first_address, true);
  1381. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1382. return true;
  1383. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1384. return false;
  1385. }
  1386. if (!size)
  1387. return false;
  1388. if (first_address.page_base() != last_address.page_base()) {
  1389. if (!MM.validate_user_write(*this, last_address))
  1390. return false;
  1391. }
  1392. return MM.validate_user_write(*this, last_address);
  1393. }
  1394. pid_t Process::sys$getsid(pid_t pid)
  1395. {
  1396. if (pid == 0)
  1397. return m_sid;
  1398. InterruptDisabler disabler;
  1399. auto* process = Process::from_pid(pid);
  1400. if (!process)
  1401. return -ESRCH;
  1402. if (m_sid != process->m_sid)
  1403. return -EPERM;
  1404. return process->m_sid;
  1405. }
  1406. pid_t Process::sys$setsid()
  1407. {
  1408. InterruptDisabler disabler;
  1409. bool found_process_with_same_pgid_as_my_pid = false;
  1410. Process::for_each_in_pgrp(pid(), [&](auto&) {
  1411. found_process_with_same_pgid_as_my_pid = true;
  1412. return false;
  1413. });
  1414. if (found_process_with_same_pgid_as_my_pid)
  1415. return -EPERM;
  1416. m_sid = m_pid;
  1417. m_pgid = m_pid;
  1418. return m_sid;
  1419. }
  1420. pid_t Process::sys$getpgid(pid_t pid)
  1421. {
  1422. if (pid == 0)
  1423. return m_pgid;
  1424. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1425. auto* process = Process::from_pid(pid);
  1426. if (!process)
  1427. return -ESRCH;
  1428. return process->m_pgid;
  1429. }
  1430. pid_t Process::sys$getpgrp()
  1431. {
  1432. return m_pgid;
  1433. }
  1434. static pid_t get_sid_from_pgid(pid_t pgid)
  1435. {
  1436. InterruptDisabler disabler;
  1437. auto* group_leader = Process::from_pid(pgid);
  1438. if (!group_leader)
  1439. return -1;
  1440. return group_leader->sid();
  1441. }
  1442. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1443. {
  1444. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1445. pid_t pid = specified_pid ? specified_pid : m_pid;
  1446. if (specified_pgid < 0)
  1447. return -EINVAL;
  1448. auto* process = Process::from_pid(pid);
  1449. if (!process)
  1450. return -ESRCH;
  1451. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1452. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1453. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1454. if (current_sid != new_sid) {
  1455. // Can't move a process between sessions.
  1456. return -EPERM;
  1457. }
  1458. // FIXME: There are more EPERM conditions to check for here..
  1459. process->m_pgid = new_pgid;
  1460. return 0;
  1461. }
  1462. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1463. {
  1464. auto* description = file_description(fd);
  1465. if (!description)
  1466. return -EBADF;
  1467. return description->file().ioctl(*description, request, arg);
  1468. }
  1469. int Process::sys$getdtablesize()
  1470. {
  1471. return m_max_open_file_descriptors;
  1472. }
  1473. int Process::sys$dup(int old_fd)
  1474. {
  1475. auto* description = file_description(old_fd);
  1476. if (!description)
  1477. return -EBADF;
  1478. int new_fd = alloc_fd(0);
  1479. if (new_fd < 0)
  1480. return new_fd;
  1481. m_fds[new_fd].set(*description);
  1482. return new_fd;
  1483. }
  1484. int Process::sys$dup2(int old_fd, int new_fd)
  1485. {
  1486. auto* description = file_description(old_fd);
  1487. if (!description)
  1488. return -EBADF;
  1489. if (new_fd < 0 || new_fd >= m_max_open_file_descriptors)
  1490. return -EINVAL;
  1491. m_fds[new_fd].set(*description);
  1492. return new_fd;
  1493. }
  1494. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1495. {
  1496. if (old_set) {
  1497. if (!validate_write_typed(old_set))
  1498. return -EFAULT;
  1499. *old_set = current->m_signal_mask;
  1500. }
  1501. if (set) {
  1502. if (!validate_read_typed(set))
  1503. return -EFAULT;
  1504. switch (how) {
  1505. case SIG_BLOCK:
  1506. current->m_signal_mask &= ~(*set);
  1507. break;
  1508. case SIG_UNBLOCK:
  1509. current->m_signal_mask |= *set;
  1510. break;
  1511. case SIG_SETMASK:
  1512. current->m_signal_mask = *set;
  1513. break;
  1514. default:
  1515. return -EINVAL;
  1516. }
  1517. }
  1518. return 0;
  1519. }
  1520. int Process::sys$sigpending(sigset_t* set)
  1521. {
  1522. if (!validate_write_typed(set))
  1523. return -EFAULT;
  1524. *set = current->m_pending_signals;
  1525. return 0;
  1526. }
  1527. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1528. {
  1529. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1530. return -EINVAL;
  1531. if (!validate_read_typed(act))
  1532. return -EFAULT;
  1533. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1534. auto& action = current->m_signal_action_data[signum];
  1535. if (old_act) {
  1536. if (!validate_write_typed(old_act))
  1537. return -EFAULT;
  1538. old_act->sa_flags = action.flags;
  1539. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1540. }
  1541. action.flags = act->sa_flags;
  1542. action.handler_or_sigaction = VirtualAddress((u32)act->sa_sigaction);
  1543. return 0;
  1544. }
  1545. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  1546. {
  1547. if (count < 0)
  1548. return -EINVAL;
  1549. if (!count)
  1550. return m_gids.size();
  1551. if (count != (int)m_gids.size())
  1552. return -EINVAL;
  1553. if (!validate_write_typed(gids, m_gids.size()))
  1554. return -EFAULT;
  1555. size_t i = 0;
  1556. for (auto gid : m_gids)
  1557. gids[i++] = gid;
  1558. return 0;
  1559. }
  1560. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  1561. {
  1562. if (count < 0)
  1563. return -EINVAL;
  1564. if (!is_superuser())
  1565. return -EPERM;
  1566. if (!validate_read(gids, count))
  1567. return -EFAULT;
  1568. m_gids.clear();
  1569. m_gids.set(m_gid);
  1570. for (int i = 0; i < count; ++i)
  1571. m_gids.set(gids[i]);
  1572. return 0;
  1573. }
  1574. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1575. {
  1576. if (!validate_read_str(pathname))
  1577. return -EFAULT;
  1578. size_t pathname_length = strlen(pathname);
  1579. if (pathname_length == 0)
  1580. return -EINVAL;
  1581. if (pathname_length >= 255)
  1582. return -ENAMETOOLONG;
  1583. return VFS::the().mkdir(StringView(pathname, pathname_length), mode & ~umask(), current_directory());
  1584. }
  1585. clock_t Process::sys$times(tms* times)
  1586. {
  1587. if (!validate_write_typed(times))
  1588. return -EFAULT;
  1589. times->tms_utime = m_ticks_in_user;
  1590. times->tms_stime = m_ticks_in_kernel;
  1591. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1592. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1593. return g_uptime & 0x7fffffff;
  1594. }
  1595. int Process::sys$select(const Syscall::SC_select_params* params)
  1596. {
  1597. // FIXME: Return -EINTR if a signal is caught.
  1598. // FIXME: Return -EINVAL if timeout is invalid.
  1599. if (!validate_read_typed(params))
  1600. return -EFAULT;
  1601. if (params->writefds && !validate_write_typed(params->writefds))
  1602. return -EFAULT;
  1603. if (params->readfds && !validate_write_typed(params->readfds))
  1604. return -EFAULT;
  1605. if (params->exceptfds && !validate_write_typed(params->exceptfds))
  1606. return -EFAULT;
  1607. if (params->timeout && !validate_read_typed(params->timeout))
  1608. return -EFAULT;
  1609. if (params->nfds < 0)
  1610. return -EINVAL;
  1611. if (params->timeout && (params->timeout->tv_sec || params->timeout->tv_usec)) {
  1612. timeval_add(kgettimeofday(), *params->timeout, current->m_select_timeout);
  1613. current->m_select_has_timeout = true;
  1614. } else {
  1615. current->m_select_has_timeout = false;
  1616. }
  1617. auto transfer_fds = [&](auto* fds, auto& vector) -> int {
  1618. vector.clear_with_capacity();
  1619. if (!fds)
  1620. return 0;
  1621. for (int fd = 0; fd < params->nfds; ++fd) {
  1622. if (FD_ISSET(fd, fds)) {
  1623. if (!file_description(fd))
  1624. return -EBADF;
  1625. vector.append(fd);
  1626. }
  1627. }
  1628. return 0;
  1629. };
  1630. if (int error = transfer_fds(params->writefds, current->m_select_write_fds))
  1631. return error;
  1632. if (int error = transfer_fds(params->readfds, current->m_select_read_fds))
  1633. return error;
  1634. if (int error = transfer_fds(params->exceptfds, current->m_select_exceptional_fds))
  1635. return error;
  1636. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  1637. 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);
  1638. #endif
  1639. if (!params->timeout || current->m_select_has_timeout)
  1640. current->block(Thread::State::BlockedSelect);
  1641. int marked_fd_count = 0;
  1642. auto mark_fds = [&](auto* fds, auto& vector, auto should_mark) {
  1643. if (!fds)
  1644. return;
  1645. FD_ZERO(fds);
  1646. for (int fd : vector) {
  1647. if (auto* description = file_description(fd); description && should_mark(*description)) {
  1648. FD_SET(fd, fds);
  1649. ++marked_fd_count;
  1650. }
  1651. }
  1652. };
  1653. mark_fds(params->readfds, current->m_select_read_fds, [](auto& description) { return description.can_read(); });
  1654. mark_fds(params->writefds, current->m_select_write_fds, [](auto& description) { return description.can_write(); });
  1655. // FIXME: We should also mark params->exceptfds as appropriate.
  1656. return marked_fd_count;
  1657. }
  1658. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1659. {
  1660. if (!validate_read_typed(fds))
  1661. return -EFAULT;
  1662. current->m_select_write_fds.clear_with_capacity();
  1663. current->m_select_read_fds.clear_with_capacity();
  1664. for (int i = 0; i < nfds; ++i) {
  1665. if (fds[i].events & POLLIN)
  1666. current->m_select_read_fds.append(fds[i].fd);
  1667. if (fds[i].events & POLLOUT)
  1668. current->m_select_write_fds.append(fds[i].fd);
  1669. }
  1670. if (timeout >= 0) {
  1671. // poll is in ms, we want s/us.
  1672. struct timeval tvtimeout;
  1673. tvtimeout.tv_sec = 0;
  1674. while (timeout >= 1000) {
  1675. tvtimeout.tv_sec += 1;
  1676. timeout -= 1000;
  1677. }
  1678. tvtimeout.tv_usec = timeout * 1000;
  1679. timeval_add(kgettimeofday(), tvtimeout, current->m_select_timeout);
  1680. current->m_select_has_timeout = true;
  1681. } else {
  1682. current->m_select_has_timeout = false;
  1683. }
  1684. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  1685. 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);
  1686. #endif
  1687. if (current->m_select_has_timeout || timeout < 0) {
  1688. current->block(Thread::State::BlockedSelect);
  1689. }
  1690. int fds_with_revents = 0;
  1691. for (int i = 0; i < nfds; ++i) {
  1692. auto* description = file_description(fds[i].fd);
  1693. if (!description) {
  1694. fds[i].revents = POLLNVAL;
  1695. continue;
  1696. }
  1697. fds[i].revents = 0;
  1698. if (fds[i].events & POLLIN && description->can_read())
  1699. fds[i].revents |= POLLIN;
  1700. if (fds[i].events & POLLOUT && description->can_write())
  1701. fds[i].revents |= POLLOUT;
  1702. if (fds[i].revents)
  1703. ++fds_with_revents;
  1704. }
  1705. return fds_with_revents;
  1706. }
  1707. Custody& Process::current_directory()
  1708. {
  1709. if (!m_cwd)
  1710. m_cwd = VFS::the().root_custody();
  1711. return *m_cwd;
  1712. }
  1713. int Process::sys$link(const char* old_path, const char* new_path)
  1714. {
  1715. if (!validate_read_str(old_path))
  1716. return -EFAULT;
  1717. if (!validate_read_str(new_path))
  1718. return -EFAULT;
  1719. return VFS::the().link(StringView(old_path), StringView(new_path), current_directory());
  1720. }
  1721. int Process::sys$unlink(const char* pathname)
  1722. {
  1723. if (!validate_read_str(pathname))
  1724. return -EFAULT;
  1725. return VFS::the().unlink(StringView(pathname), current_directory());
  1726. }
  1727. int Process::sys$symlink(const char* target, const char* linkpath)
  1728. {
  1729. if (!validate_read_str(target))
  1730. return -EFAULT;
  1731. if (!validate_read_str(linkpath))
  1732. return -EFAULT;
  1733. return VFS::the().symlink(StringView(target), StringView(linkpath), current_directory());
  1734. }
  1735. int Process::sys$rmdir(const char* pathname)
  1736. {
  1737. if (!validate_read_str(pathname))
  1738. return -EFAULT;
  1739. return VFS::the().rmdir(StringView(pathname), current_directory());
  1740. }
  1741. int Process::sys$read_tsc(u32* lsw, u32* msw)
  1742. {
  1743. if (!validate_write_typed(lsw))
  1744. return -EFAULT;
  1745. if (!validate_write_typed(msw))
  1746. return -EFAULT;
  1747. read_tsc(*lsw, *msw);
  1748. return 0;
  1749. }
  1750. int Process::sys$chmod(const char* pathname, mode_t mode)
  1751. {
  1752. if (!validate_read_str(pathname))
  1753. return -EFAULT;
  1754. return VFS::the().chmod(StringView(pathname), mode, current_directory());
  1755. }
  1756. int Process::sys$fchmod(int fd, mode_t mode)
  1757. {
  1758. auto* description = file_description(fd);
  1759. if (!description)
  1760. return -EBADF;
  1761. return description->fchmod(mode);
  1762. }
  1763. int Process::sys$fchown(int fd, uid_t uid, gid_t gid)
  1764. {
  1765. auto* description = file_description(fd);
  1766. if (!description)
  1767. return -EBADF;
  1768. return description->chown(uid, gid);
  1769. }
  1770. int Process::sys$chown(const char* pathname, uid_t uid, gid_t gid)
  1771. {
  1772. if (!validate_read_str(pathname))
  1773. return -EFAULT;
  1774. return VFS::the().chown(StringView(pathname), uid, gid, current_directory());
  1775. }
  1776. void Process::finalize()
  1777. {
  1778. ASSERT(current == g_finalizer);
  1779. dbgprintf("Finalizing Process %s(%u)\n", m_name.characters(), m_pid);
  1780. m_fds.clear();
  1781. m_tty = nullptr;
  1782. m_executable = nullptr;
  1783. m_cwd = nullptr;
  1784. m_elf_loader = nullptr;
  1785. disown_all_shared_buffers();
  1786. {
  1787. InterruptDisabler disabler;
  1788. if (auto* parent_process = Process::from_pid(m_ppid)) {
  1789. // FIXME(Thread): What should we do here? Should we look at all threads' signal actions?
  1790. if (parent_process->main_thread().m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  1791. // NOTE: If the parent doesn't care about this process, let it go.
  1792. m_ppid = 0;
  1793. } else {
  1794. parent_process->send_signal(SIGCHLD, this);
  1795. }
  1796. }
  1797. }
  1798. m_dead = true;
  1799. }
  1800. void Process::die()
  1801. {
  1802. if (m_tracer)
  1803. m_tracer->set_dead();
  1804. {
  1805. InterruptDisabler disabler;
  1806. for_each_thread([](Thread& thread) {
  1807. if (thread.state() != Thread::State::Dead)
  1808. thread.set_state(Thread::State::Dying);
  1809. return IterationDecision::Continue;
  1810. });
  1811. }
  1812. if (!Scheduler::is_active())
  1813. Scheduler::pick_next_and_switch_now();
  1814. }
  1815. size_t Process::amount_virtual() const
  1816. {
  1817. size_t amount = 0;
  1818. for (auto& region : m_regions) {
  1819. amount += region.size();
  1820. }
  1821. return amount;
  1822. }
  1823. size_t Process::amount_resident() const
  1824. {
  1825. // FIXME: This will double count if multiple regions use the same physical page.
  1826. size_t amount = 0;
  1827. for (auto& region : m_regions) {
  1828. amount += region.amount_resident();
  1829. }
  1830. return amount;
  1831. }
  1832. size_t Process::amount_shared() const
  1833. {
  1834. // FIXME: This will double count if multiple regions use the same physical page.
  1835. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage ref counts,
  1836. // and each PhysicalPage is only reffed by its VMObject. This needs to be refactored
  1837. // so that every Region contributes +1 ref to each of its PhysicalPages.
  1838. size_t amount = 0;
  1839. for (auto& region : m_regions) {
  1840. amount += region.amount_shared();
  1841. }
  1842. return amount;
  1843. }
  1844. int Process::sys$socket(int domain, int type, int protocol)
  1845. {
  1846. int fd = alloc_fd();
  1847. if (fd < 0)
  1848. return fd;
  1849. auto result = Socket::create(domain, type, protocol);
  1850. if (result.is_error())
  1851. return result.error();
  1852. auto description = FileDescription::create(*result.value());
  1853. unsigned flags = 0;
  1854. if (type & SOCK_CLOEXEC)
  1855. flags |= FD_CLOEXEC;
  1856. if (type & SOCK_NONBLOCK)
  1857. description->set_blocking(false);
  1858. m_fds[fd].set(move(description), flags);
  1859. return fd;
  1860. }
  1861. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  1862. {
  1863. if (!validate_read(address, address_length))
  1864. return -EFAULT;
  1865. auto* description = file_description(sockfd);
  1866. if (!description)
  1867. return -EBADF;
  1868. if (!description->is_socket())
  1869. return -ENOTSOCK;
  1870. auto& socket = *description->socket();
  1871. return socket.bind(address, address_length);
  1872. }
  1873. int Process::sys$listen(int sockfd, int backlog)
  1874. {
  1875. auto* description = file_description(sockfd);
  1876. if (!description)
  1877. return -EBADF;
  1878. if (!description->is_socket())
  1879. return -ENOTSOCK;
  1880. auto& socket = *description->socket();
  1881. auto result = socket.listen(backlog);
  1882. if (result.is_error())
  1883. return result;
  1884. description->set_socket_role(SocketRole::Listener);
  1885. return 0;
  1886. }
  1887. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  1888. {
  1889. if (!validate_write_typed(address_size))
  1890. return -EFAULT;
  1891. if (!validate_write(address, *address_size))
  1892. return -EFAULT;
  1893. int accepted_socket_fd = alloc_fd();
  1894. if (accepted_socket_fd < 0)
  1895. return accepted_socket_fd;
  1896. auto* accepting_socket_description = file_description(accepting_socket_fd);
  1897. if (!accepting_socket_description)
  1898. return -EBADF;
  1899. if (!accepting_socket_description->is_socket())
  1900. return -ENOTSOCK;
  1901. auto& socket = *accepting_socket_description->socket();
  1902. if (!socket.can_accept()) {
  1903. ASSERT(!accepting_socket_description->is_blocking());
  1904. return -EAGAIN;
  1905. }
  1906. auto accepted_socket = socket.accept();
  1907. ASSERT(accepted_socket);
  1908. bool success = accepted_socket->get_local_address(address, address_size);
  1909. ASSERT(success);
  1910. auto accepted_socket_description = FileDescription::create(move(accepted_socket), SocketRole::Accepted);
  1911. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  1912. // I'm not sure if this matches other systems but it makes sense to me.
  1913. accepted_socket_description->set_blocking(accepting_socket_description->is_blocking());
  1914. m_fds[accepted_socket_fd].set(move(accepted_socket_description), m_fds[accepting_socket_fd].flags);
  1915. return accepted_socket_fd;
  1916. }
  1917. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  1918. {
  1919. if (!validate_read(address, address_size))
  1920. return -EFAULT;
  1921. int fd = alloc_fd();
  1922. if (fd < 0)
  1923. return fd;
  1924. auto* description = file_description(sockfd);
  1925. if (!description)
  1926. return -EBADF;
  1927. if (!description->is_socket())
  1928. return -ENOTSOCK;
  1929. if (description->socket_role() == SocketRole::Connected)
  1930. return -EISCONN;
  1931. auto& socket = *description->socket();
  1932. description->set_socket_role(SocketRole::Connecting);
  1933. auto result = socket.connect(*description, address, address_size, description->is_blocking() ? ShouldBlock::Yes : ShouldBlock::No);
  1934. if (result.is_error()) {
  1935. description->set_socket_role(SocketRole::None);
  1936. return result;
  1937. }
  1938. description->set_socket_role(SocketRole::Connected);
  1939. return 0;
  1940. }
  1941. ssize_t Process::sys$sendto(const Syscall::SC_sendto_params* params)
  1942. {
  1943. if (!validate_read_typed(params))
  1944. return -EFAULT;
  1945. int sockfd = params->sockfd;
  1946. const void* data = params->data;
  1947. size_t data_length = params->data_length;
  1948. int flags = params->flags;
  1949. auto* addr = (const sockaddr*)params->addr;
  1950. auto addr_length = (socklen_t)params->addr_length;
  1951. if (!validate_read(data, data_length))
  1952. return -EFAULT;
  1953. if (addr && !validate_read(addr, addr_length))
  1954. return -EFAULT;
  1955. auto* description = file_description(sockfd);
  1956. if (!description)
  1957. return -EBADF;
  1958. if (!description->is_socket())
  1959. return -ENOTSOCK;
  1960. auto& socket = *description->socket();
  1961. kprintf("sendto %p (%u), flags=%u, addr: %p (%u)\n", data, data_length, flags, addr, addr_length);
  1962. return socket.sendto(*description, data, data_length, flags, addr, addr_length);
  1963. }
  1964. ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* params)
  1965. {
  1966. if (!validate_read_typed(params))
  1967. return -EFAULT;
  1968. int sockfd = params->sockfd;
  1969. void* buffer = params->buffer;
  1970. size_t buffer_length = params->buffer_length;
  1971. int flags = params->flags;
  1972. auto* addr = (sockaddr*)params->addr;
  1973. auto* addr_length = (socklen_t*)params->addr_length;
  1974. if (!validate_write(buffer, buffer_length))
  1975. return -EFAULT;
  1976. if (addr_length) {
  1977. if (!validate_write_typed(addr_length))
  1978. return -EFAULT;
  1979. if (!validate_write(addr, *addr_length))
  1980. return -EFAULT;
  1981. } else if (addr) {
  1982. return -EINVAL;
  1983. }
  1984. auto* description = file_description(sockfd);
  1985. if (!description)
  1986. return -EBADF;
  1987. if (!description->is_socket())
  1988. return -ENOTSOCK;
  1989. auto& socket = *description->socket();
  1990. bool original_blocking = description->is_blocking();
  1991. if (flags & MSG_DONTWAIT)
  1992. description->set_blocking(false);
  1993. auto nrecv = socket.recvfrom(*description, buffer, buffer_length, flags, addr, addr_length);
  1994. if (flags & MSG_DONTWAIT)
  1995. description->set_blocking(original_blocking);
  1996. return nrecv;
  1997. }
  1998. int Process::sys$getsockname(int sockfd, sockaddr* addr, socklen_t* addrlen)
  1999. {
  2000. if (!validate_read_typed(addrlen))
  2001. return -EFAULT;
  2002. if (*addrlen <= 0)
  2003. return -EINVAL;
  2004. if (!validate_write(addr, *addrlen))
  2005. return -EFAULT;
  2006. auto* description = file_description(sockfd);
  2007. if (!description)
  2008. return -EBADF;
  2009. if (!description->is_socket())
  2010. return -ENOTSOCK;
  2011. auto& socket = *description->socket();
  2012. if (!socket.get_local_address(addr, addrlen))
  2013. return -EINVAL; // FIXME: Should this be another error? I'm not sure.
  2014. return 0;
  2015. }
  2016. int Process::sys$getpeername(int sockfd, sockaddr* addr, socklen_t* addrlen)
  2017. {
  2018. if (!validate_read_typed(addrlen))
  2019. return -EFAULT;
  2020. if (*addrlen <= 0)
  2021. return -EINVAL;
  2022. if (!validate_write(addr, *addrlen))
  2023. return -EFAULT;
  2024. auto* description = file_description(sockfd);
  2025. if (!description)
  2026. return -EBADF;
  2027. if (!description->is_socket())
  2028. return -ENOTSOCK;
  2029. auto& socket = *description->socket();
  2030. if (!socket.is_connected())
  2031. return -ENOTCONN;
  2032. if (!socket.get_peer_address(addr, addrlen))
  2033. return -EINVAL; // FIXME: Should this be another error? I'm not sure.
  2034. return 0;
  2035. }
  2036. int Process::sys$sched_setparam(pid_t pid, const struct sched_param* param)
  2037. {
  2038. if (!validate_read_typed(param))
  2039. return -EFAULT;
  2040. InterruptDisabler disabler;
  2041. auto* peer = this;
  2042. if (pid != 0)
  2043. peer = Process::from_pid(pid);
  2044. if (!peer)
  2045. return -ESRCH;
  2046. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  2047. return -EPERM;
  2048. if (param->sched_priority < Process::FirstPriority || param->sched_priority > Process::LastPriority)
  2049. return -EINVAL;
  2050. peer->set_priority(Priority(param->sched_priority));
  2051. return 0;
  2052. }
  2053. int Process::sys$sched_getparam(pid_t pid, struct sched_param* param)
  2054. {
  2055. if (!validate_read_typed(param))
  2056. return -EFAULT;
  2057. InterruptDisabler disabler;
  2058. auto* peer = this;
  2059. if (pid != 0)
  2060. peer = Process::from_pid(pid);
  2061. if (!peer)
  2062. return -ESRCH;
  2063. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  2064. return -EPERM;
  2065. param->sched_priority = peer->priority();
  2066. return 0;
  2067. }
  2068. int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params)
  2069. {
  2070. if (!validate_read_typed(params))
  2071. return -EFAULT;
  2072. int sockfd = params->sockfd;
  2073. int level = params->level;
  2074. int option = params->option;
  2075. auto* value = params->value;
  2076. auto* value_size = (socklen_t*)params->value_size;
  2077. if (!validate_write_typed(value_size))
  2078. return -EFAULT;
  2079. if (!validate_write(value, *value_size))
  2080. return -EFAULT;
  2081. auto* description = file_description(sockfd);
  2082. if (!description)
  2083. return -EBADF;
  2084. if (!description->is_socket())
  2085. return -ENOTSOCK;
  2086. auto& socket = *description->socket();
  2087. return socket.getsockopt(level, option, value, value_size);
  2088. }
  2089. int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params)
  2090. {
  2091. if (!validate_read_typed(params))
  2092. return -EFAULT;
  2093. int sockfd = params->sockfd;
  2094. int level = params->level;
  2095. int option = params->option;
  2096. auto* value = params->value;
  2097. auto value_size = (socklen_t)params->value_size;
  2098. if (!validate_read(value, value_size))
  2099. return -EFAULT;
  2100. auto* description = file_description(sockfd);
  2101. if (!description)
  2102. return -EBADF;
  2103. if (!description->is_socket())
  2104. return -ENOTSOCK;
  2105. auto& socket = *description->socket();
  2106. return socket.setsockopt(level, option, value, value_size);
  2107. }
  2108. void Process::disown_all_shared_buffers()
  2109. {
  2110. LOCKER(shared_buffers().lock());
  2111. Vector<SharedBuffer*, 32> buffers_to_disown;
  2112. for (auto& it : shared_buffers().resource())
  2113. buffers_to_disown.append(it.value.ptr());
  2114. for (auto* shared_buffer : buffers_to_disown)
  2115. shared_buffer->disown(m_pid);
  2116. }
  2117. int Process::sys$create_shared_buffer(pid_t peer_pid, int size, void** buffer)
  2118. {
  2119. if (!size || size < 0)
  2120. return -EINVAL;
  2121. size = PAGE_ROUND_UP(size);
  2122. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2123. return -EINVAL;
  2124. if (!validate_write_typed(buffer))
  2125. return -EFAULT;
  2126. {
  2127. InterruptDisabler disabler;
  2128. auto* peer = Process::from_pid(peer_pid);
  2129. if (!peer)
  2130. return -ESRCH;
  2131. }
  2132. LOCKER(shared_buffers().lock());
  2133. static int s_next_shared_buffer_id;
  2134. int shared_buffer_id = ++s_next_shared_buffer_id;
  2135. auto shared_buffer = make<SharedBuffer>(shared_buffer_id, size);
  2136. shared_buffer->share_with(m_pid);
  2137. shared_buffer->share_with(peer_pid);
  2138. *buffer = shared_buffer->get_address(*this);
  2139. ASSERT((int)shared_buffer->size() >= size);
  2140. #ifdef SHARED_BUFFER_DEBUG
  2141. kprintf("%s(%u): Created shared buffer %d @ %p (%u bytes, vmo is %u)\n", name().characters(), pid(), shared_buffer_id, *buffer, size, shared_buffer->size());
  2142. #endif
  2143. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2144. return shared_buffer_id;
  2145. }
  2146. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2147. {
  2148. LOCKER(shared_buffers().lock());
  2149. auto it = shared_buffers().resource().find(shared_buffer_id);
  2150. if (it == shared_buffers().resource().end())
  2151. return -EINVAL;
  2152. auto& shared_buffer = *(*it).value;
  2153. #ifdef SHARED_BUFFER_DEBUG
  2154. kprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2155. #endif
  2156. shared_buffer.release(*this);
  2157. return 0;
  2158. }
  2159. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2160. {
  2161. LOCKER(shared_buffers().lock());
  2162. auto it = shared_buffers().resource().find(shared_buffer_id);
  2163. if (it == shared_buffers().resource().end())
  2164. return (void*)-EINVAL;
  2165. auto& shared_buffer = *(*it).value;
  2166. if (!shared_buffer.is_shared_with(m_pid))
  2167. return (void*)-EINVAL;
  2168. #ifdef SHARED_BUFFER_DEBUG
  2169. kprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2170. #endif
  2171. return shared_buffer.get_address(*this);
  2172. }
  2173. int Process::sys$seal_shared_buffer(int shared_buffer_id)
  2174. {
  2175. LOCKER(shared_buffers().lock());
  2176. auto it = shared_buffers().resource().find(shared_buffer_id);
  2177. if (it == shared_buffers().resource().end())
  2178. return -EINVAL;
  2179. auto& shared_buffer = *(*it).value;
  2180. if (!shared_buffer.is_shared_with(m_pid))
  2181. return -EINVAL;
  2182. #ifdef SHARED_BUFFER_DEBUG
  2183. kprintf("%s(%u): Sealing shared buffer %d\n", name().characters(), pid(), shared_buffer_id);
  2184. #endif
  2185. shared_buffer.seal();
  2186. return 0;
  2187. }
  2188. int Process::sys$get_shared_buffer_size(int shared_buffer_id)
  2189. {
  2190. LOCKER(shared_buffers().lock());
  2191. auto it = shared_buffers().resource().find(shared_buffer_id);
  2192. if (it == shared_buffers().resource().end())
  2193. return -EINVAL;
  2194. auto& shared_buffer = *(*it).value;
  2195. if (!shared_buffer.is_shared_with(m_pid))
  2196. return -EINVAL;
  2197. #ifdef SHARED_BUFFER_DEBUG
  2198. kprintf("%s(%u): Get shared buffer %d size: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2199. #endif
  2200. return shared_buffer.size();
  2201. }
  2202. const char* to_string(Process::Priority priority)
  2203. {
  2204. switch (priority) {
  2205. case Process::IdlePriority:
  2206. return "Idle";
  2207. case Process::LowPriority:
  2208. return "Low";
  2209. case Process::NormalPriority:
  2210. return "Normal";
  2211. case Process::HighPriority:
  2212. return "High";
  2213. }
  2214. kprintf("to_string(Process::Priority): Invalid priority: %u\n", priority);
  2215. ASSERT_NOT_REACHED();
  2216. return nullptr;
  2217. }
  2218. void Process::terminate_due_to_signal(u8 signal)
  2219. {
  2220. ASSERT_INTERRUPTS_DISABLED();
  2221. ASSERT(signal < 32);
  2222. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  2223. m_termination_status = 0;
  2224. m_termination_signal = signal;
  2225. die();
  2226. }
  2227. void Process::send_signal(u8 signal, Process* sender)
  2228. {
  2229. // FIXME(Thread): Find the appropriate thread to deliver the signal to.
  2230. main_thread().send_signal(signal, sender);
  2231. }
  2232. int Process::thread_count() const
  2233. {
  2234. int count = 0;
  2235. for_each_thread([&count](auto&) {
  2236. ++count;
  2237. return IterationDecision::Continue;
  2238. });
  2239. return count;
  2240. }
  2241. int Process::sys$create_thread(int (*entry)(void*), void* argument)
  2242. {
  2243. if (!validate_read((const void*)entry, sizeof(void*)))
  2244. return -EFAULT;
  2245. auto* thread = new Thread(*this);
  2246. auto& tss = thread->tss();
  2247. tss.eip = (u32)entry;
  2248. tss.eflags = 0x0202;
  2249. tss.cr3 = page_directory().cr3();
  2250. thread->make_userspace_stack_for_secondary_thread(argument);
  2251. thread->set_state(Thread::State::Runnable);
  2252. return thread->tid();
  2253. }
  2254. void Process::sys$exit_thread(int code)
  2255. {
  2256. cli();
  2257. if (&current->process().main_thread() == current) {
  2258. sys$exit(code);
  2259. return;
  2260. }
  2261. current->set_state(Thread::State::Dying);
  2262. big_lock().unlock_if_locked();
  2263. Scheduler::pick_next_and_switch_now();
  2264. ASSERT_NOT_REACHED();
  2265. }
  2266. int Process::sys$gettid()
  2267. {
  2268. return current->tid();
  2269. }
  2270. int Process::sys$donate(int tid)
  2271. {
  2272. if (tid < 0)
  2273. return -EINVAL;
  2274. InterruptDisabler disabler;
  2275. Thread* beneficiary = nullptr;
  2276. for_each_thread([&](Thread& thread) {
  2277. if (thread.tid() == tid) {
  2278. beneficiary = &thread;
  2279. return IterationDecision::Break;
  2280. }
  2281. return IterationDecision::Continue;
  2282. });
  2283. if (!beneficiary)
  2284. return -ENOTHREAD;
  2285. Scheduler::donate_to(beneficiary, "sys$donate");
  2286. return 0;
  2287. }
  2288. int Process::sys$rename(const char* oldpath, const char* newpath)
  2289. {
  2290. if (!validate_read_str(oldpath))
  2291. return -EFAULT;
  2292. if (!validate_read_str(newpath))
  2293. return -EFAULT;
  2294. return VFS::the().rename(StringView(oldpath), StringView(newpath), current_directory());
  2295. }
  2296. int Process::sys$shm_open(const char* name, int flags, mode_t mode)
  2297. {
  2298. if (!validate_read_str(name))
  2299. return -EFAULT;
  2300. int fd = alloc_fd();
  2301. if (fd < 0)
  2302. return fd;
  2303. auto shm_or_error = SharedMemory::open(String(name), flags, mode);
  2304. if (shm_or_error.is_error())
  2305. return shm_or_error.error();
  2306. auto description = FileDescription::create(shm_or_error.value().ptr());
  2307. m_fds[fd].set(move(description), FD_CLOEXEC);
  2308. return fd;
  2309. }
  2310. int Process::sys$shm_unlink(const char* name)
  2311. {
  2312. if (!validate_read_str(name))
  2313. return -EFAULT;
  2314. return SharedMemory::unlink(String(name));
  2315. }
  2316. int Process::sys$ftruncate(int fd, off_t length)
  2317. {
  2318. auto* description = file_description(fd);
  2319. if (!description)
  2320. return -EBADF;
  2321. // FIXME: Check that fd is writable, otherwise EINVAL.
  2322. return description->truncate(length);
  2323. }
  2324. int Process::sys$systrace(pid_t pid)
  2325. {
  2326. InterruptDisabler disabler;
  2327. auto* peer = Process::from_pid(pid);
  2328. if (!peer)
  2329. return -ESRCH;
  2330. if (peer->uid() != m_euid)
  2331. return -EACCES;
  2332. int fd = alloc_fd();
  2333. if (fd < 0)
  2334. return fd;
  2335. auto description = FileDescription::create(peer->ensure_tracer());
  2336. m_fds[fd].set(move(description), 0);
  2337. return fd;
  2338. }
  2339. ProcessTracer& Process::ensure_tracer()
  2340. {
  2341. if (!m_tracer)
  2342. m_tracer = ProcessTracer::create(m_pid);
  2343. return *m_tracer;
  2344. }
  2345. void Process::FileDescriptionAndFlags::clear()
  2346. {
  2347. description = nullptr;
  2348. flags = 0;
  2349. }
  2350. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& d, u32 f)
  2351. {
  2352. description = move(d);
  2353. flags = f;
  2354. }
  2355. int Process::sys$mknod(const char* pathname, mode_t mode, dev_t dev)
  2356. {
  2357. if (!validate_read_str(pathname))
  2358. return -EFAULT;
  2359. return VFS::the().mknod(StringView(pathname), mode, dev, current_directory());
  2360. }