Process.cpp 51 KB

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