Process.cpp 63 KB

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