Process.cpp 63 KB

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