Process.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  1. #include "types.h"
  2. #include "Process.h"
  3. #include "kmalloc.h"
  4. #include "VGA.h"
  5. #include "StdLib.h"
  6. #include "i386.h"
  7. #include "system.h"
  8. #include <VirtualFileSystem/FileHandle.h>
  9. #include <VirtualFileSystem/VirtualFileSystem.h>
  10. #include <ELFLoader/ELFLoader.h>
  11. #include "MemoryManager.h"
  12. #include "errno.h"
  13. #include "i8253.h"
  14. #include "RTC.h"
  15. #include "ProcFileSystem.h"
  16. #include <AK/StdLib.h>
  17. //#define DEBUG_IO
  18. //#define TASK_DEBUG
  19. //#define FORK_DEBUG
  20. //#define SCHEDULER_DEBUG
  21. #define COOL_GLOBALS
  22. #ifdef COOL_GLOBALS
  23. struct CoolGlobals {
  24. dword current_pid;
  25. };
  26. CoolGlobals* g_cool_globals;
  27. #endif
  28. // FIXME: Only do a single validation for accesses that don't span multiple pages.
  29. // FIXME: Some places pass strlen(arg1) as arg2. This doesn't seem entirely perfect..
  30. #define VALIDATE_USER_READ(b, s) \
  31. do { \
  32. LinearAddress laddr((dword)(b)); \
  33. if (!validate_user_read(laddr) || !validate_user_read(laddr.offset((s) - 1))) \
  34. return -EFAULT; \
  35. } while(0)
  36. #define VALIDATE_USER_WRITE(b, s) \
  37. do { \
  38. LinearAddress laddr((dword)(b)); \
  39. if (!validate_user_write(laddr) || !validate_user_write(laddr.offset((s) - 1))) \
  40. return -EFAULT; \
  41. } while(0)
  42. static const DWORD defaultStackSize = 16384;
  43. Process* current;
  44. Process* s_kernelProcess;
  45. static pid_t next_pid;
  46. static InlineLinkedList<Process>* s_processes;
  47. static InlineLinkedList<Process>* s_deadProcesses;
  48. static String* s_hostname;
  49. static String& hostnameStorage(InterruptDisabler&)
  50. {
  51. ASSERT(s_hostname);
  52. return *s_hostname;
  53. }
  54. static String getHostname()
  55. {
  56. InterruptDisabler disabler;
  57. return hostnameStorage(disabler).isolatedCopy();
  58. }
  59. static bool contextSwitch(Process*);
  60. static void redoKernelProcessTSS()
  61. {
  62. if (!s_kernelProcess->selector())
  63. s_kernelProcess->setSelector(gdt_alloc_entry());
  64. auto& tssDescriptor = getGDTEntry(s_kernelProcess->selector());
  65. tssDescriptor.setBase(&s_kernelProcess->tss());
  66. tssDescriptor.setLimit(0xffff);
  67. tssDescriptor.dpl = 0;
  68. tssDescriptor.segment_present = 1;
  69. tssDescriptor.granularity = 1;
  70. tssDescriptor.zero = 0;
  71. tssDescriptor.operation_size = 1;
  72. tssDescriptor.descriptor_type = 0;
  73. tssDescriptor.type = 9;
  74. flushGDT();
  75. }
  76. void Process::prepForIRETToNewProcess()
  77. {
  78. redoKernelProcessTSS();
  79. s_kernelProcess->tss().backlink = current->selector();
  80. loadTaskRegister(s_kernelProcess->selector());
  81. }
  82. static void hlt_loop()
  83. {
  84. for (;;) {
  85. asm volatile("hlt");
  86. }
  87. }
  88. void Process::initialize()
  89. {
  90. #ifdef COOL_GLOBALS
  91. g_cool_globals = (CoolGlobals*)0x1000;
  92. #endif
  93. current = nullptr;
  94. next_pid = 0;
  95. s_processes = new InlineLinkedList<Process>;
  96. s_deadProcesses = new InlineLinkedList<Process>;
  97. s_kernelProcess = Process::createKernelProcess(hlt_loop, "colonel");
  98. s_hostname = new String("birx");
  99. redoKernelProcessTSS();
  100. loadTaskRegister(s_kernelProcess->selector());
  101. }
  102. template<typename Callback>
  103. static void forEachProcess(Callback callback)
  104. {
  105. ASSERT_INTERRUPTS_DISABLED();
  106. for (auto* process = s_processes->head(); process; process = process->next()) {
  107. if (!callback(*process))
  108. break;
  109. }
  110. }
  111. void Process::for_each_in_pgrp(pid_t pgid, Function<void(Process&)> callback)
  112. {
  113. ASSERT_INTERRUPTS_DISABLED();
  114. for (auto* process = s_processes->head(); process; process = process->next()) {
  115. if (process->pgid() == pgid)
  116. callback(*process);
  117. }
  118. }
  119. Vector<Process*> Process::allProcesses()
  120. {
  121. InterruptDisabler disabler;
  122. Vector<Process*> processes;
  123. processes.ensureCapacity(s_processes->sizeSlow());
  124. for (auto* process = s_processes->head(); process; process = process->next())
  125. processes.append(process);
  126. return processes;
  127. }
  128. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable)
  129. {
  130. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  131. if (laddr.is_null()) {
  132. laddr = m_nextRegion;
  133. m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
  134. }
  135. laddr.mask(0xfffff000);
  136. unsigned page_count = ceilDiv(size, PAGE_SIZE);
  137. auto physical_pages = MM.allocate_physical_pages(page_count);
  138. ASSERT(physical_pages.size() == page_count);
  139. m_regions.append(adopt(*new Region(laddr, size, move(physical_pages), move(name), is_readable, is_writable)));
  140. MM.mapRegion(*this, *m_regions.last());
  141. return m_regions.last().ptr();
  142. }
  143. bool Process::deallocate_region(Region& region)
  144. {
  145. InterruptDisabler disabler;
  146. for (size_t i = 0; i < m_regions.size(); ++i) {
  147. if (m_regions[i].ptr() == &region) {
  148. MM.unmapRegion(*this, region);
  149. m_regions.remove(i);
  150. return true;
  151. }
  152. }
  153. return false;
  154. }
  155. Region* Process::regionFromRange(LinearAddress laddr, size_t size)
  156. {
  157. for (auto& region : m_regions) {
  158. if (region->linearAddress == laddr && region->size == size)
  159. return region.ptr();
  160. }
  161. return nullptr;
  162. }
  163. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  164. {
  165. VALIDATE_USER_READ(name, strlen(name));
  166. auto* region = regionFromRange(LinearAddress((dword)addr), size);
  167. if (!region)
  168. return -EINVAL;
  169. region->name = name;
  170. return 0;
  171. }
  172. void* Process::sys$mmap(void* addr, size_t size)
  173. {
  174. InterruptDisabler disabler;
  175. // FIXME: Implement mapping at a client-preferred address.
  176. ASSERT(addr == nullptr);
  177. auto* region = allocate_region(LinearAddress(), size, "mmap");
  178. if (!region)
  179. return (void*)-1;
  180. MM.mapRegion(*this, *region);
  181. return (void*)region->linearAddress.get();
  182. }
  183. int Process::sys$munmap(void* addr, size_t size)
  184. {
  185. InterruptDisabler disabler;
  186. auto* region = regionFromRange(LinearAddress((dword)addr), size);
  187. if (!region)
  188. return -1;
  189. if (!deallocate_region(*region))
  190. return -1;
  191. return 0;
  192. }
  193. int Process::sys$gethostname(char* buffer, size_t size)
  194. {
  195. VALIDATE_USER_WRITE(buffer, size);
  196. auto hostname = getHostname();
  197. if (size < (hostname.length() + 1))
  198. return -ENAMETOOLONG;
  199. memcpy(buffer, hostname.characters(), size);
  200. return 0;
  201. }
  202. Process* Process::fork(RegisterDump& regs)
  203. {
  204. auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copyRef(), m_executable.copyRef(), m_tty, this);
  205. #ifdef FORK_DEBUG
  206. dbgprintf("fork: child=%p\n", child);
  207. #endif
  208. #if 0
  209. // FIXME: An honest fork() would copy these. Needs a Vector copy ctor.
  210. child->m_arguments = m_arguments;
  211. child->m_initialEnvironment = m_initialEnvironment;
  212. #endif
  213. for (auto& region : m_regions) {
  214. #ifdef FORK_DEBUG
  215. dbgprintf("fork: cloning Region{%p}\n", region.ptr());
  216. #endif
  217. auto cloned_region = region->clone();
  218. child->m_regions.append(move(cloned_region));
  219. MM.mapRegion(*child, *child->m_regions.last());
  220. }
  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. #ifdef FORK_DEBUG
  238. 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);
  239. #endif
  240. ProcFileSystem::the().addProcess(*child);
  241. s_processes->prepend(child);
  242. system.nprocess++;
  243. #ifdef TASK_DEBUG
  244. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child->m_tss.eip);
  245. #endif
  246. return child;
  247. }
  248. pid_t Process::sys$fork(RegisterDump& regs)
  249. {
  250. auto* child = fork(regs);
  251. ASSERT(child);
  252. return child->pid();
  253. }
  254. int Process::exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  255. {
  256. auto parts = path.split('/');
  257. if (parts.isEmpty())
  258. return -ENOENT;
  259. int error;
  260. auto handle = VirtualFileSystem::the().open(path, error, 0, m_cwd ? m_cwd->inode : InodeIdentifier());
  261. if (!handle) {
  262. ASSERT(error != 0);
  263. return error;
  264. }
  265. if (!handle->metadata().mayExecute(m_uid, m_gid))
  266. return -EACCES;
  267. auto elfData = handle->readEntireFile();
  268. if (!elfData)
  269. return -EIO; // FIXME: Get a more detailed error from VFS.
  270. dword entry_eip = 0;
  271. PageDirectory* old_page_directory;
  272. PageDirectory* new_page_directory;
  273. {
  274. InterruptDisabler disabler;
  275. // Okay, here comes the sleight of hand, pay close attention..
  276. auto old_regions = move(m_regions);
  277. old_page_directory = m_page_directory;
  278. new_page_directory = reinterpret_cast<PageDirectory*>(kmalloc_page_aligned(sizeof(PageDirectory)));
  279. MM.populate_page_directory(*new_page_directory);
  280. m_page_directory = new_page_directory;
  281. MM.enter_process_paging_scope(*this);
  282. ELFLoader loader(move(elfData));
  283. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  284. ASSERT(size);
  285. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  286. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  287. return laddr.asPtr();
  288. };
  289. bool success = loader.load();
  290. if (!success) {
  291. m_page_directory = old_page_directory;
  292. MM.enter_process_paging_scope(*this);
  293. MM.release_page_directory(*new_page_directory);
  294. m_regions = move(old_regions);
  295. kprintf("sys$execve: Failure loading %s\n", path.characters());
  296. return -ENOEXEC;
  297. }
  298. entry_eip = (dword)loader.symbol_ptr("_start");
  299. if (!entry_eip) {
  300. m_page_directory = old_page_directory;
  301. MM.enter_process_paging_scope(*this);
  302. MM.release_page_directory(*new_page_directory);
  303. m_regions = move(old_regions);
  304. return -ENOEXEC;
  305. }
  306. }
  307. InterruptDisabler disabler;
  308. if (current == this)
  309. loadTaskRegister(s_kernelProcess->selector());
  310. m_name = parts.takeLast();
  311. dword old_esp0 = m_tss.esp0;
  312. memset(&m_tss, 0, sizeof(m_tss));
  313. m_tss.eflags = 0x0202;
  314. m_tss.eip = entry_eip;
  315. m_tss.cs = 0x1b;
  316. m_tss.ds = 0x23;
  317. m_tss.es = 0x23;
  318. m_tss.fs = 0x23;
  319. m_tss.gs = 0x23;
  320. m_tss.ss = 0x23;
  321. m_tss.cr3 = (dword)m_page_directory;
  322. auto* stack_region = allocate_region(LinearAddress(), defaultStackSize, "stack");
  323. ASSERT(stack_region);
  324. m_stackTop3 = stack_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  325. m_tss.esp = m_stackTop3;
  326. m_tss.ss0 = 0x10;
  327. m_tss.esp0 = old_esp0;
  328. m_tss.ss2 = m_pid;
  329. MM.release_page_directory(*old_page_directory);
  330. m_executable = handle->vnode();
  331. m_arguments = move(arguments);
  332. m_initialEnvironment = move(environment);
  333. #ifdef TASK_DEBUG
  334. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), filename, m_tss.eip);
  335. #endif
  336. if (current == this)
  337. yield();
  338. return 0;
  339. }
  340. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  341. {
  342. VALIDATE_USER_READ(filename, strlen(filename));
  343. if (argv) {
  344. for (size_t i = 0; argv[i]; ++i) {
  345. VALIDATE_USER_READ(argv[i], strlen(argv[i]));
  346. }
  347. }
  348. if (envp) {
  349. for (size_t i = 0; envp[i]; ++i) {
  350. VALIDATE_USER_READ(envp[i], strlen(envp[i]));
  351. }
  352. }
  353. String path(filename);
  354. auto parts = path.split('/');
  355. Vector<String> arguments;
  356. if (argv) {
  357. for (size_t i = 0; argv[i]; ++i) {
  358. arguments.append(argv[i]);
  359. }
  360. } else {
  361. arguments.append(parts.last());
  362. }
  363. Vector<String> environment;
  364. if (envp) {
  365. for (size_t i = 0; envp[i]; ++i) {
  366. environment.append(envp[i]);
  367. }
  368. }
  369. int rc = exec(path, move(arguments), move(environment));
  370. ASSERT(rc < 0);
  371. return rc;
  372. }
  373. pid_t Process::sys$spawn(const char* filename, const char** argv, const char** envp)
  374. {
  375. VALIDATE_USER_READ(filename, strlen(filename));
  376. if (argv) {
  377. for (size_t i = 0; argv[i]; ++i) {
  378. VALIDATE_USER_READ(argv[i], strlen(argv[i]));
  379. }
  380. }
  381. if (envp) {
  382. for (size_t i = 0; envp[i]; ++i) {
  383. VALIDATE_USER_READ(envp[i], strlen(envp[i]));
  384. }
  385. }
  386. String path(filename);
  387. auto parts = path.split('/');
  388. Vector<String> arguments;
  389. if (argv) {
  390. for (size_t i = 0; argv[i]; ++i) {
  391. arguments.append(argv[i]);
  392. }
  393. } else {
  394. arguments.append(parts.last());
  395. }
  396. Vector<String> environment;
  397. if (envp) {
  398. for (size_t i = 0; envp[i]; ++i) {
  399. environment.append(envp[i]);
  400. }
  401. }
  402. int error;
  403. auto* child = create_user_process(path, m_uid, m_gid, m_pid, error, move(arguments), move(environment), m_tty);
  404. if (child)
  405. return child->pid();
  406. return error;
  407. }
  408. 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)
  409. {
  410. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  411. auto parts = path.split('/');
  412. if (arguments.isEmpty()) {
  413. arguments.append(parts.last());
  414. }
  415. RetainPtr<VirtualFileSystem::Node> cwd;
  416. {
  417. InterruptDisabler disabler;
  418. if (auto* parent = Process::fromPID(parent_pid))
  419. cwd = parent->m_cwd.copyRef();
  420. }
  421. if (!cwd)
  422. cwd = VirtualFileSystem::the().root();
  423. auto* process = new Process(parts.takeLast(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  424. error = process->exec(path, move(arguments), move(environment));
  425. if (error != 0)
  426. return nullptr;
  427. ProcFileSystem::the().addProcess(*process);
  428. s_processes->prepend(process);
  429. system.nprocess++;
  430. #ifdef TASK_DEBUG
  431. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  432. #endif
  433. error = 0;
  434. return process;
  435. }
  436. int Process::sys$get_environment(char*** environ)
  437. {
  438. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "environ");
  439. if (!region)
  440. return -ENOMEM;
  441. MM.mapRegion(*this, *region);
  442. char* envpage = (char*)region->linearAddress.get();
  443. *environ = (char**)envpage;
  444. char* bufptr = envpage + (sizeof(char*) * (m_initialEnvironment.size() + 1));
  445. for (size_t i = 0; i < m_initialEnvironment.size(); ++i) {
  446. (*environ)[i] = bufptr;
  447. memcpy(bufptr, m_initialEnvironment[i].characters(), m_initialEnvironment[i].length());
  448. bufptr += m_initialEnvironment[i].length();
  449. *(bufptr++) = '\0';
  450. }
  451. (*environ)[m_initialEnvironment.size()] = nullptr;
  452. return 0;
  453. }
  454. int Process::sys$get_arguments(int* argc, char*** argv)
  455. {
  456. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "argv");
  457. if (!region)
  458. return -ENOMEM;
  459. MM.mapRegion(*this, *region);
  460. char* argpage = (char*)region->linearAddress.get();
  461. *argc = m_arguments.size();
  462. *argv = (char**)argpage;
  463. char* bufptr = argpage + (sizeof(char*) * m_arguments.size());
  464. for (size_t i = 0; i < m_arguments.size(); ++i) {
  465. (*argv)[i] = bufptr;
  466. memcpy(bufptr, m_arguments[i].characters(), m_arguments[i].length());
  467. bufptr += m_arguments[i].length();
  468. *(bufptr++) = '\0';
  469. }
  470. return 0;
  471. }
  472. Process* Process::createKernelProcess(void (*e)(), String&& name)
  473. {
  474. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  475. process->m_tss.eip = (dword)e;
  476. if (process->pid() != 0) {
  477. InterruptDisabler disabler;
  478. s_processes->prepend(process);
  479. system.nprocess++;
  480. ProcFileSystem::the().addProcess(*process);
  481. #ifdef TASK_DEBUG
  482. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  483. #endif
  484. }
  485. return process;
  486. }
  487. Process::Process(String&& name, uid_t uid, gid_t gid, pid_t parentPID, RingLevel ring, RetainPtr<VirtualFileSystem::Node>&& cwd, RetainPtr<VirtualFileSystem::Node>&& executable, TTY* tty, Process* fork_parent)
  488. : m_name(move(name))
  489. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  490. , m_uid(uid)
  491. , m_gid(gid)
  492. , m_state(Runnable)
  493. , m_ring(ring)
  494. , m_cwd(move(cwd))
  495. , m_executable(move(executable))
  496. , m_tty(tty)
  497. , m_parentPID(parentPID)
  498. {
  499. if (fork_parent) {
  500. m_sid = fork_parent->m_sid;
  501. m_pgid = fork_parent->m_pgid;
  502. } else {
  503. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  504. InterruptDisabler disabler;
  505. if (auto* parent = Process::fromPID(m_parentPID)) {
  506. m_sid = parent->m_sid;
  507. m_pgid = parent->m_pgid;
  508. }
  509. }
  510. m_page_directory = (PageDirectory*)kmalloc_page_aligned(sizeof(PageDirectory));
  511. MM.populate_page_directory(*m_page_directory);
  512. if (fork_parent) {
  513. m_file_descriptors.resize(fork_parent->m_file_descriptors.size());
  514. for (size_t i = 0; i < fork_parent->m_file_descriptors.size(); ++i) {
  515. if (!fork_parent->m_file_descriptors[i])
  516. continue;
  517. #ifdef FORK_DEBUG
  518. dbgprintf("fork: cloning fd %u... (%p) istty? %um\n", i, fork_parent->m_file_descriptors[i].ptr(), fork_parent->m_file_descriptors[i]->isTTY());
  519. #endif
  520. m_file_descriptors[i] = fork_parent->m_file_descriptors[i]->clone();
  521. }
  522. } else {
  523. m_file_descriptors.resize(m_max_open_file_descriptors);
  524. if (tty) {
  525. m_file_descriptors[0] = tty->open(O_RDONLY);
  526. m_file_descriptors[1] = tty->open(O_WRONLY);
  527. m_file_descriptors[2] = tty->open(O_WRONLY);
  528. }
  529. }
  530. if (fork_parent)
  531. m_nextRegion = fork_parent->m_nextRegion;
  532. else
  533. m_nextRegion = LinearAddress(0x10000000);
  534. if (fork_parent) {
  535. memcpy(&m_tss, &fork_parent->m_tss, sizeof(m_tss));
  536. } else {
  537. memset(&m_tss, 0, sizeof(m_tss));
  538. // Only IF is set when a process boots.
  539. m_tss.eflags = 0x0202;
  540. word cs, ds, ss;
  541. if (isRing0()) {
  542. cs = 0x08;
  543. ds = 0x10;
  544. ss = 0x10;
  545. } else {
  546. cs = 0x1b;
  547. ds = 0x23;
  548. ss = 0x23;
  549. }
  550. m_tss.ds = ds;
  551. m_tss.es = ds;
  552. m_tss.fs = ds;
  553. m_tss.gs = ds;
  554. m_tss.ss = ss;
  555. m_tss.cs = cs;
  556. }
  557. m_tss.cr3 = (dword)m_page_directory;
  558. if (isRing0()) {
  559. // FIXME: This memory is leaked.
  560. // But uh, there's also no kernel process termination, so I guess it's not technically leaked...
  561. dword stackBottom = (dword)kmalloc_eternal(defaultStackSize);
  562. m_stackTop0 = (stackBottom + defaultStackSize) & 0xffffff8;
  563. m_tss.esp = m_stackTop0;
  564. } else {
  565. if (fork_parent) {
  566. m_stackTop3 = fork_parent->m_stackTop3;
  567. } else {
  568. auto* region = allocate_region(LinearAddress(), defaultStackSize, "stack");
  569. ASSERT(region);
  570. m_stackTop3 = region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  571. m_tss.esp = m_stackTop3;
  572. }
  573. }
  574. if (isRing3()) {
  575. // Ring3 processes need a separate stack for Ring0.
  576. m_kernelStack = kmalloc(defaultStackSize);
  577. m_stackTop0 = ((DWORD)m_kernelStack + defaultStackSize) & 0xffffff8;
  578. m_tss.ss0 = 0x10;
  579. m_tss.esp0 = m_stackTop0;
  580. }
  581. // HACK: Ring2 SS in the TSS is the current PID.
  582. m_tss.ss2 = m_pid;
  583. m_farPtr.offset = 0x98765432;
  584. }
  585. Process::~Process()
  586. {
  587. InterruptDisabler disabler;
  588. ProcFileSystem::the().removeProcess(*this);
  589. system.nprocess--;
  590. gdt_free_entry(selector());
  591. if (m_kernelStack) {
  592. kfree(m_kernelStack);
  593. m_kernelStack = nullptr;
  594. }
  595. MM.release_page_directory(*m_page_directory);
  596. }
  597. void Process::dumpRegions()
  598. {
  599. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  600. kprintf("BEGIN END SIZE NAME\n");
  601. for (auto& region : m_regions) {
  602. kprintf("%x -- %x %x %s\n",
  603. region->linearAddress.get(),
  604. region->linearAddress.offset(region->size - 1).get(),
  605. region->size,
  606. region->name.characters());
  607. }
  608. }
  609. void Process::notify_waiters(pid_t waitee, int exit_status, int signal)
  610. {
  611. ASSERT_INTERRUPTS_DISABLED();
  612. for (auto* process = s_processes->head(); process; process = process->next()) {
  613. if (process->waitee() == waitee)
  614. process->m_waiteeStatus = (exit_status << 8) | (signal);
  615. }
  616. }
  617. void Process::sys$exit(int status)
  618. {
  619. cli();
  620. #ifdef TASK_DEBUG
  621. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  622. #endif
  623. set_state(Exiting);
  624. s_processes->remove(this);
  625. notify_waiters(m_pid, status, 0);
  626. if (!scheduleNewProcess()) {
  627. kprintf("Process::sys$exit: Failed to schedule a new process :(\n");
  628. HANG;
  629. }
  630. s_deadProcesses->append(this);
  631. switchNow();
  632. }
  633. void Process::send_signal(int signal, Process* sender)
  634. {
  635. ASSERT_INTERRUPTS_DISABLED();
  636. bool wasCurrent = current == sender;
  637. set_state(Exiting);
  638. s_processes->remove(this);
  639. notify_waiters(m_pid, 0, signal);
  640. if (wasCurrent) {
  641. kprintf("Current process committing suicide!\n");
  642. if (!scheduleNewProcess()) {
  643. kprintf("Process::send_signal: Failed to schedule a new process :(\n");
  644. HANG;
  645. }
  646. }
  647. s_deadProcesses->append(this);
  648. if (wasCurrent)
  649. switchNow();
  650. }
  651. void Process::processDidCrash(Process* crashedProcess)
  652. {
  653. ASSERT_INTERRUPTS_DISABLED();
  654. if (crashedProcess->state() == Crashing) {
  655. kprintf("Double crash :(\n");
  656. HANG;
  657. }
  658. crashedProcess->set_state(Crashing);
  659. crashedProcess->dumpRegions();
  660. s_processes->remove(crashedProcess);
  661. notify_waiters(crashedProcess->m_pid, 0, SIGSEGV);
  662. if (!scheduleNewProcess()) {
  663. kprintf("Process::processDidCrash: Failed to schedule a new process :(\n");
  664. HANG;
  665. }
  666. s_deadProcesses->append(crashedProcess);
  667. switchNow();
  668. }
  669. void Process::doHouseKeeping()
  670. {
  671. if (s_deadProcesses->isEmpty())
  672. return;
  673. InterruptDisabler disabler;
  674. Process* next = nullptr;
  675. for (auto* deadProcess = s_deadProcesses->head(); deadProcess; deadProcess = next) {
  676. next = deadProcess->next();
  677. delete deadProcess;
  678. }
  679. s_deadProcesses->clear();
  680. }
  681. void yield()
  682. {
  683. if (!current) {
  684. kprintf( "PANIC: yield() with !current" );
  685. HANG;
  686. }
  687. //kprintf("%s<%u> yield()\n", current->name().characters(), current->pid());
  688. InterruptDisabler disabler;
  689. if (!scheduleNewProcess())
  690. return;
  691. //kprintf("yield() jumping to new process: %x (%s)\n", current->farPtr().selector, current->name().characters());
  692. switchNow();
  693. }
  694. void switchNow()
  695. {
  696. Descriptor& descriptor = getGDTEntry(current->selector());
  697. descriptor.type = 9;
  698. flushGDT();
  699. asm("sti\n"
  700. "ljmp *(%%eax)\n"
  701. ::"a"(&current->farPtr())
  702. );
  703. }
  704. bool scheduleNewProcess()
  705. {
  706. ASSERT_INTERRUPTS_DISABLED();
  707. if (!current) {
  708. // XXX: The first ever context_switch() goes to the idle process.
  709. // This to setup a reliable place we can return to.
  710. return contextSwitch(Process::kernelProcess());
  711. }
  712. // Check and unblock processes whose wait conditions have been met.
  713. for (auto* process = s_processes->head(); process; process = process->next()) {
  714. if (process->state() == Process::BlockedSleep) {
  715. if (process->wakeupTime() <= system.uptime) {
  716. process->unblock();
  717. continue;
  718. }
  719. }
  720. if (process->state() == Process::BlockedWait) {
  721. if (!Process::fromPID(process->waitee())) {
  722. process->unblock();
  723. continue;
  724. }
  725. }
  726. if (process->state() == Process::BlockedRead) {
  727. ASSERT(process->m_fdBlockedOnRead != -1);
  728. if (process->m_file_descriptors[process->m_fdBlockedOnRead]->hasDataAvailableForRead()) {
  729. process->unblock();
  730. continue;
  731. }
  732. }
  733. }
  734. #ifdef SCHEDULER_DEBUG
  735. dbgprintf("Scheduler choices:\n");
  736. for (auto* process = s_processes->head(); process; process = process->next()) {
  737. //if (process->state() == Process::BlockedWait || process->state() == Process::BlockedSleep)
  738. // continue;
  739. dbgprintf("% 12s %s(%u) @ %w:%x\n", toString(process->state()), process->name().characters(), process->pid(), process->tss().cs, process->tss().eip);
  740. }
  741. #endif
  742. auto* prevHead = s_processes->head();
  743. for (;;) {
  744. // Move head to tail.
  745. s_processes->append(s_processes->removeHead());
  746. auto* process = s_processes->head();
  747. if (process->state() == Process::Runnable || process->state() == Process::Running) {
  748. #ifdef SCHEDULER_DEBUG
  749. dbgprintf("switch to %s(%u) (%p vs %p)\n", process->name().characters(), process->pid(), process, current);
  750. #endif
  751. return contextSwitch(process);
  752. }
  753. if (process == prevHead) {
  754. // Back at process_head, nothing wants to run.
  755. kprintf("Nothing wants to run!\n");
  756. kprintf("PID OWNER STATE NSCHED NAME\n");
  757. for (auto* process = s_processes->head(); process; process = process->next()) {
  758. kprintf("%w %w:%w %b %w %s\n",
  759. process->pid(),
  760. process->uid(),
  761. process->gid(),
  762. process->state(),
  763. process->timesScheduled(),
  764. process->name().characters());
  765. }
  766. kprintf("Switch to kernel process @ %w:%x\n", s_kernelProcess->tss().cs, s_kernelProcess->tss().eip);
  767. return contextSwitch(Process::kernelProcess());
  768. }
  769. }
  770. }
  771. static bool contextSwitch(Process* t)
  772. {
  773. t->setTicksLeft(5);
  774. t->didSchedule();
  775. if (current == t)
  776. return false;
  777. #ifdef SCHEDULER_DEBUG
  778. // Some sanity checking to force a crash earlier.
  779. auto csRPL = t->tss().cs & 3;
  780. auto ssRPL = t->tss().ss & 3;
  781. if (csRPL != ssRPL) {
  782. kprintf("Fuckup! Switching from %s(%u) to %s(%u) has RPL mismatch\n",
  783. current->name().characters(), current->pid(),
  784. t->name().characters(), t->pid()
  785. );
  786. kprintf("code: %w:%x\n", t->tss().cs, t->tss().eip);
  787. kprintf(" stk: %w:%x\n", t->tss().ss, t->tss().esp);
  788. ASSERT(csRPL == ssRPL);
  789. }
  790. #endif
  791. if (current) {
  792. // If the last process hasn't blocked (still marked as running),
  793. // mark it as runnable for the next round.
  794. if (current->state() == Process::Running)
  795. current->set_state(Process::Runnable);
  796. }
  797. current = t;
  798. t->set_state(Process::Running);
  799. #ifdef COOL_GLOBALS
  800. g_cool_globals->current_pid = t->pid();
  801. #endif
  802. if (!t->selector()) {
  803. t->setSelector(gdt_alloc_entry());
  804. auto& descriptor = getGDTEntry(t->selector());
  805. descriptor.setBase(&t->tss());
  806. descriptor.setLimit(0xffff);
  807. descriptor.dpl = 0;
  808. descriptor.segment_present = 1;
  809. descriptor.granularity = 1;
  810. descriptor.zero = 0;
  811. descriptor.operation_size = 1;
  812. descriptor.descriptor_type = 0;
  813. }
  814. auto& descriptor = getGDTEntry(t->selector());
  815. descriptor.type = 11; // Busy TSS
  816. flushGDT();
  817. return true;
  818. }
  819. Process* Process::fromPID(pid_t pid)
  820. {
  821. ASSERT_INTERRUPTS_DISABLED();
  822. for (auto* process = s_processes->head(); process; process = process->next()) {
  823. if (process->pid() == pid)
  824. return process;
  825. }
  826. return nullptr;
  827. }
  828. FileHandle* Process::fileHandleIfExists(int fd)
  829. {
  830. if (fd < 0)
  831. return nullptr;
  832. if ((unsigned)fd < m_file_descriptors.size())
  833. return m_file_descriptors[fd].ptr();
  834. return nullptr;
  835. }
  836. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, size_t size)
  837. {
  838. VALIDATE_USER_WRITE(buffer, size);
  839. auto* handle = fileHandleIfExists(fd);
  840. if (!handle)
  841. return -EBADF;
  842. return handle->get_dir_entries((byte*)buffer, size);
  843. }
  844. int Process::sys$lseek(int fd, off_t offset, int whence)
  845. {
  846. auto* handle = fileHandleIfExists(fd);
  847. if (!handle)
  848. return -EBADF;
  849. return handle->seek(offset, whence);
  850. }
  851. int Process::sys$ttyname_r(int fd, char* buffer, size_t size)
  852. {
  853. VALIDATE_USER_WRITE(buffer, size);
  854. auto* handle = fileHandleIfExists(fd);
  855. if (!handle)
  856. return -EBADF;
  857. if (!handle->isTTY())
  858. return -ENOTTY;
  859. auto ttyName = handle->tty()->ttyName();
  860. if (size < ttyName.length() + 1)
  861. return -ERANGE;
  862. strcpy(buffer, ttyName.characters());
  863. return 0;
  864. }
  865. ssize_t Process::sys$write(int fd, const void* data, size_t size)
  866. {
  867. VALIDATE_USER_READ(data, size);
  868. #ifdef DEBUG_IO
  869. kprintf("Process::sys$write: called(%d, %p, %u)\n", fd, data, size);
  870. #endif
  871. auto* handle = fileHandleIfExists(fd);
  872. #ifdef DEBUG_IO
  873. kprintf("Process::sys$write: handle=%p\n", handle);
  874. #endif
  875. if (!handle)
  876. return -EBADF;
  877. auto nwritten = handle->write((const byte*)data, size);
  878. #ifdef DEBUG_IO
  879. kprintf("Process::sys$write: nwritten=%u\n", nwritten);
  880. #endif
  881. return nwritten;
  882. }
  883. ssize_t Process::sys$read(int fd, void* outbuf, size_t nread)
  884. {
  885. VALIDATE_USER_WRITE(outbuf, nread);
  886. #ifdef DEBUG_IO
  887. kprintf("Process::sys$read: called(%d, %p, %u)\n", fd, outbuf, nread);
  888. #endif
  889. auto* handle = fileHandleIfExists(fd);
  890. #ifdef DEBUG_IO
  891. kprintf("Process::sys$read: handle=%p\n", handle);
  892. #endif
  893. if (!handle)
  894. return -EBADF;
  895. if (handle->isBlocking()) {
  896. if (!handle->hasDataAvailableForRead()) {
  897. m_fdBlockedOnRead = fd;
  898. block(BlockedRead);
  899. yield();
  900. }
  901. }
  902. nread = handle->read((byte*)outbuf, nread);
  903. #ifdef DEBUG_IO
  904. kprintf("Process::sys$read: nread=%u\n", nread);
  905. #endif
  906. return nread;
  907. }
  908. int Process::sys$close(int fd)
  909. {
  910. auto* handle = fileHandleIfExists(fd);
  911. if (!handle)
  912. return -EBADF;
  913. int rc = handle->close();
  914. m_file_descriptors[fd] = nullptr;
  915. return rc;
  916. }
  917. int Process::sys$lstat(const char* path, Unix::stat* statbuf)
  918. {
  919. VALIDATE_USER_WRITE(statbuf, sizeof(Unix::stat));
  920. int error;
  921. auto handle = VirtualFileSystem::the().open(move(path), error, O_NOFOLLOW_NOERROR, cwdInode());
  922. if (!handle)
  923. return error;
  924. handle->stat(statbuf);
  925. return 0;
  926. }
  927. int Process::sys$stat(const char* path, Unix::stat* statbuf)
  928. {
  929. VALIDATE_USER_WRITE(statbuf, sizeof(Unix::stat));
  930. int error;
  931. auto handle = VirtualFileSystem::the().open(move(path), error, 0, cwdInode());
  932. if (!handle)
  933. return error;
  934. handle->stat(statbuf);
  935. return 0;
  936. }
  937. int Process::sys$readlink(const char* path, char* buffer, size_t size)
  938. {
  939. VALIDATE_USER_READ(path, strlen(path));
  940. VALIDATE_USER_WRITE(buffer, size);
  941. int error;
  942. auto handle = VirtualFileSystem::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, cwdInode());
  943. if (!handle)
  944. return error;
  945. if (!handle->metadata().isSymbolicLink())
  946. return -EINVAL;
  947. auto contents = handle->readEntireFile();
  948. if (!contents)
  949. return -EIO; // FIXME: Get a more detailed error from VFS.
  950. memcpy(buffer, contents.pointer(), min(size, contents.size()));
  951. if (contents.size() + 1 < size)
  952. buffer[contents.size()] = '\0';
  953. return 0;
  954. }
  955. int Process::sys$chdir(const char* path)
  956. {
  957. VALIDATE_USER_READ(path, strlen(path));
  958. int error;
  959. auto handle = VirtualFileSystem::the().open(path, error, 0, cwdInode());
  960. if (!handle)
  961. return error;
  962. if (!handle->isDirectory())
  963. return -ENOTDIR;
  964. m_cwd = handle->vnode();
  965. return 0;
  966. }
  967. int Process::sys$getcwd(char* buffer, size_t size)
  968. {
  969. VALIDATE_USER_WRITE(buffer, size);
  970. auto path = VirtualFileSystem::the().absolutePath(cwdInode());
  971. if (path.isNull())
  972. return -EINVAL;
  973. if (size < path.length() + 1)
  974. return -ERANGE;
  975. strcpy(buffer, path.characters());
  976. return -ENOTIMPL;
  977. }
  978. size_t Process::number_of_open_file_descriptors() const
  979. {
  980. size_t count = 0;
  981. for (auto& handle : m_file_descriptors) {
  982. if (handle)
  983. ++count;
  984. }
  985. return count;
  986. }
  987. int Process::sys$open(const char* path, int options)
  988. {
  989. #ifdef DEBUG_IO
  990. kprintf("Process::sys$open(): PID=%u, path=%s {%u}\n", m_pid, path, pathLength);
  991. #endif
  992. VALIDATE_USER_READ(path, strlen(path));
  993. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  994. return -EMFILE;
  995. int error;
  996. auto handle = VirtualFileSystem::the().open(path, error, options, cwdInode());
  997. if (!handle)
  998. return error;
  999. if (options & O_DIRECTORY && !handle->isDirectory())
  1000. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1001. int fd = 0;
  1002. for (; fd < m_max_open_file_descriptors; ++fd) {
  1003. if (!m_file_descriptors[fd])
  1004. break;
  1005. }
  1006. handle->setFD(fd);
  1007. m_file_descriptors[fd] = move(handle);
  1008. return fd;
  1009. }
  1010. int Process::sys$uname(utsname* buf)
  1011. {
  1012. VALIDATE_USER_WRITE(buf, sizeof(utsname));
  1013. strcpy(buf->sysname, "Serenity");
  1014. strcpy(buf->release, "1.0-dev");
  1015. strcpy(buf->version, "FIXME");
  1016. strcpy(buf->machine, "i386");
  1017. strcpy(buf->nodename, getHostname().characters());
  1018. return 0;
  1019. }
  1020. int Process::sys$kill(pid_t pid, int signal)
  1021. {
  1022. if (pid == 0) {
  1023. // FIXME: Send to same-group processes.
  1024. ASSERT(pid != 0);
  1025. }
  1026. if (pid == -1) {
  1027. // FIXME: Send to all processes.
  1028. ASSERT(pid != -1);
  1029. }
  1030. ASSERT(pid != current->pid()); // FIXME: Support this scenario.
  1031. InterruptDisabler disabler;
  1032. auto* peer = Process::fromPID(pid);
  1033. if (!peer)
  1034. return -ESRCH;
  1035. peer->send_signal(signal, this);
  1036. return 0;
  1037. }
  1038. int Process::sys$sleep(unsigned seconds)
  1039. {
  1040. if (!seconds)
  1041. return 0;
  1042. sleep(seconds * TICKS_PER_SECOND);
  1043. return 0;
  1044. }
  1045. int Process::sys$gettimeofday(timeval* tv)
  1046. {
  1047. VALIDATE_USER_WRITE(tv, sizeof(tv));
  1048. InterruptDisabler disabler;
  1049. auto now = RTC::now();
  1050. tv->tv_sec = now;
  1051. tv->tv_usec = 0;
  1052. return 0;
  1053. }
  1054. uid_t Process::sys$getuid()
  1055. {
  1056. return m_uid;
  1057. }
  1058. gid_t Process::sys$getgid()
  1059. {
  1060. return m_gid;
  1061. }
  1062. pid_t Process::sys$getpid()
  1063. {
  1064. return m_pid;
  1065. }
  1066. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1067. {
  1068. if (wstatus)
  1069. VALIDATE_USER_WRITE(wstatus, sizeof(int));
  1070. InterruptDisabler disabler;
  1071. if (!Process::fromPID(waitee))
  1072. return -1;
  1073. m_waitee = waitee;
  1074. m_waiteeStatus = 0;
  1075. block(BlockedWait);
  1076. yield();
  1077. if (wstatus)
  1078. *wstatus = m_waiteeStatus;
  1079. return m_waitee;
  1080. }
  1081. void Process::unblock()
  1082. {
  1083. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1084. system.nblocked--;
  1085. m_state = Process::Runnable;
  1086. }
  1087. void Process::block(Process::State state)
  1088. {
  1089. ASSERT(current->state() == Process::Running);
  1090. system.nblocked++;
  1091. current->set_state(state);
  1092. }
  1093. void block(Process::State state)
  1094. {
  1095. current->block(state);
  1096. yield();
  1097. }
  1098. void sleep(DWORD ticks)
  1099. {
  1100. ASSERT(current->state() == Process::Running);
  1101. current->setWakeupTime(system.uptime + ticks);
  1102. current->block(Process::BlockedSleep);
  1103. yield();
  1104. }
  1105. Process* Process::kernelProcess()
  1106. {
  1107. ASSERT(s_kernelProcess);
  1108. return s_kernelProcess;
  1109. }
  1110. bool Process::isValidAddressForKernel(LinearAddress laddr) const
  1111. {
  1112. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1113. // This code allows access outside of the known used address ranges to get caught.
  1114. InterruptDisabler disabler;
  1115. if (laddr.get() >= ksyms().first().address && laddr.get() <= ksyms().last().address)
  1116. return true;
  1117. if (is_kmalloc_address((void*)laddr.get()))
  1118. return true;
  1119. return validate_user_read(laddr);
  1120. }
  1121. bool Process::validate_user_read(LinearAddress laddr) const
  1122. {
  1123. InterruptDisabler disabler;
  1124. return MM.validate_user_read(*this, laddr);
  1125. }
  1126. bool Process::validate_user_write(LinearAddress laddr) const
  1127. {
  1128. InterruptDisabler disabler;
  1129. return MM.validate_user_write(*this, laddr);
  1130. }
  1131. pid_t Process::sys$getsid(pid_t pid)
  1132. {
  1133. if (pid == 0)
  1134. return m_sid;
  1135. InterruptDisabler disabler;
  1136. auto* process = Process::fromPID(pid);
  1137. if (!process)
  1138. return -ESRCH;
  1139. if (m_sid != process->m_sid)
  1140. return -EPERM;
  1141. return process->m_sid;
  1142. }
  1143. pid_t Process::sys$setsid()
  1144. {
  1145. InterruptDisabler disabler;
  1146. bool found_process_with_same_pgid_as_my_pid = false;
  1147. forEachProcess([&] (auto& process) {
  1148. if (process.pgid() == pid()) {
  1149. found_process_with_same_pgid_as_my_pid = true;
  1150. return false;
  1151. }
  1152. return true;
  1153. });
  1154. if (found_process_with_same_pgid_as_my_pid)
  1155. return -EPERM;
  1156. m_sid = m_pid;
  1157. m_pgid = m_pid;
  1158. return m_sid;
  1159. }
  1160. pid_t Process::sys$getpgid(pid_t pid)
  1161. {
  1162. if (pid == 0)
  1163. return m_pgid;
  1164. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1165. auto* process = Process::fromPID(pid);
  1166. if (!process)
  1167. return -ESRCH;
  1168. return process->m_pgid;
  1169. }
  1170. pid_t Process::sys$getpgrp()
  1171. {
  1172. return m_pgid;
  1173. }
  1174. static pid_t get_sid_from_pgid(pid_t pgid)
  1175. {
  1176. InterruptDisabler disabler;
  1177. auto* group_leader = Process::fromPID(pgid);
  1178. if (!group_leader)
  1179. return -1;
  1180. return group_leader->sid();
  1181. }
  1182. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1183. {
  1184. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1185. pid_t pid = specified_pid ? specified_pid : m_pid;
  1186. if (specified_pgid < 0)
  1187. return -EINVAL;
  1188. auto* process = Process::fromPID(pid);
  1189. if (!process)
  1190. return -ESRCH;
  1191. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1192. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1193. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1194. if (current_sid != new_sid) {
  1195. // Can't move a process between sessions.
  1196. return -EPERM;
  1197. }
  1198. // FIXME: There are more EPERM conditions to check for here..
  1199. process->m_pgid = new_pgid;
  1200. return 0;
  1201. }
  1202. pid_t Process::sys$tcgetpgrp(int fd)
  1203. {
  1204. auto* handle = fileHandleIfExists(fd);
  1205. if (!handle)
  1206. return -EBADF;
  1207. if (!handle->isTTY())
  1208. return -ENOTTY;
  1209. auto& tty = *handle->tty();
  1210. if (&tty != m_tty)
  1211. return -ENOTTY;
  1212. return tty.pgid();
  1213. }
  1214. int Process::sys$tcsetpgrp(int fd, pid_t pgid)
  1215. {
  1216. if (pgid < 0)
  1217. return -EINVAL;
  1218. if (get_sid_from_pgid(pgid) != m_sid)
  1219. return -EINVAL;
  1220. auto* handle = fileHandleIfExists(fd);
  1221. if (!handle)
  1222. return -EBADF;
  1223. if (!handle->isTTY())
  1224. return -ENOTTY;
  1225. auto& tty = *handle->tty();
  1226. if (&tty != m_tty)
  1227. return -ENOTTY;
  1228. tty.set_pgid(pgid);
  1229. return 0;
  1230. }