Process.cpp 40 KB

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