Process.cpp 42 KB

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