Process.cpp 43 KB

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