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