Process.cpp 63 KB

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