Process.cpp 80 KB

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