Process.cpp 64 KB

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