Process.cpp 80 KB

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