Process.cpp 38 KB

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