Process.cpp 74 KB

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