Process.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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 SIGNAL_DEBUG
  24. #define MAX_PROCESS_GIDS 32
  25. // FIXME: Only do a single validation for accesses that don't span multiple pages.
  26. // FIXME: Some places pass strlen(arg1) as arg2. This doesn't seem entirely perfect..
  27. #define VALIDATE_USER_READ_WITH_RETURN_TYPE(b, s, ret_type) \
  28. do { \
  29. LinearAddress laddr((dword)(b)); \
  30. if (!validate_user_read(laddr) || !validate_user_read(laddr.offset((s) - 1))) { \
  31. dbgprintf("Bad read address passed to syscall: %p +%u\n", laddr.get(), (s)); \
  32. return (ret_type)-EFAULT; \
  33. } \
  34. } while(0)
  35. #define VALIDATE_USER_READ(b, s) VALIDATE_USER_READ_WITH_RETURN_TYPE(b, s, int)
  36. #define VALIDATE_USER_WRITE(b, s) \
  37. do { \
  38. LinearAddress laddr((dword)(b)); \
  39. if (!validate_user_write(laddr) || !validate_user_write(laddr.offset((s) - 1))) { \
  40. dbgprintf("Bad write address passed to syscall: %p +%u\n", laddr.get(), (s)); \
  41. return -EFAULT; \
  42. } \
  43. } while(0)
  44. static const DWORD defaultStackSize = 16384;
  45. static pid_t next_pid;
  46. InlineLinkedList<Process>* g_processes;
  47. static String* s_hostname;
  48. static String& hostnameStorage(InterruptDisabler&)
  49. {
  50. ASSERT(s_hostname);
  51. return *s_hostname;
  52. }
  53. static String getHostname()
  54. {
  55. InterruptDisabler disabler;
  56. return hostnameStorage(disabler).isolatedCopy();
  57. }
  58. CoolGlobals* g_cool_globals;
  59. void Process::initialize()
  60. {
  61. #ifdef COOL_GLOBALS
  62. g_cool_globals = reinterpret_cast<CoolGlobals*>(0x1000);
  63. #endif
  64. next_pid = 0;
  65. g_processes = new InlineLinkedList<Process>;
  66. s_hostname = new String("birx");
  67. Scheduler::initialize();
  68. }
  69. Vector<Process*> Process::allProcesses()
  70. {
  71. InterruptDisabler disabler;
  72. Vector<Process*> processes;
  73. processes.ensureCapacity(g_processes->sizeSlow());
  74. for (auto* process = g_processes->head(); process; process = process->next())
  75. processes.append(process);
  76. return processes;
  77. }
  78. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable)
  79. {
  80. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  81. if (laddr.is_null()) {
  82. laddr = m_nextRegion;
  83. m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
  84. }
  85. laddr.mask(0xfffff000);
  86. unsigned page_count = ceilDiv(size, PAGE_SIZE);
  87. auto physical_pages = MM.allocate_physical_pages(page_count);
  88. ASSERT(physical_pages.size() == page_count);
  89. m_regions.append(adopt(*new Region(laddr, size, move(physical_pages), move(name), is_readable, is_writable)));
  90. MM.mapRegion(*this, *m_regions.last());
  91. return m_regions.last().ptr();
  92. }
  93. bool Process::deallocate_region(Region& region)
  94. {
  95. InterruptDisabler disabler;
  96. for (size_t i = 0; i < m_regions.size(); ++i) {
  97. if (m_regions[i].ptr() == &region) {
  98. MM.unmapRegion(*this, region);
  99. m_regions.remove(i);
  100. return true;
  101. }
  102. }
  103. return false;
  104. }
  105. Region* Process::regionFromRange(LinearAddress laddr, size_t size)
  106. {
  107. for (auto& region : m_regions) {
  108. if (region->linearAddress == laddr && region->size == size)
  109. return region.ptr();
  110. }
  111. return nullptr;
  112. }
  113. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  114. {
  115. VALIDATE_USER_READ(name, strlen(name));
  116. auto* region = regionFromRange(LinearAddress((dword)addr), size);
  117. if (!region)
  118. return -EINVAL;
  119. region->name = name;
  120. return 0;
  121. }
  122. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  123. {
  124. VALIDATE_USER_READ_WITH_RETURN_TYPE(params, sizeof(Syscall::SC_mmap_params), void*);
  125. InterruptDisabler disabler;
  126. void* addr = (void*)params->addr;
  127. size_t size = params->size;
  128. int prot = params->prot;
  129. int flags = params->flags;
  130. int fd = params->fd;
  131. Unix::off_t offset = params->offset;
  132. // FIXME: Implement mapping at a client-preferred address. Most of the support is already in plcae.
  133. ASSERT(addr == nullptr);
  134. auto* region = allocate_region(LinearAddress(), size, "mmap");
  135. if (!region)
  136. return (void*)-1;
  137. return (void*)region->linearAddress.get();
  138. }
  139. int Process::sys$munmap(void* addr, size_t size)
  140. {
  141. InterruptDisabler disabler;
  142. auto* region = regionFromRange(LinearAddress((dword)addr), size);
  143. if (!region)
  144. return -1;
  145. if (!deallocate_region(*region))
  146. return -1;
  147. return 0;
  148. }
  149. int Process::sys$gethostname(char* buffer, size_t size)
  150. {
  151. VALIDATE_USER_WRITE(buffer, size);
  152. auto hostname = getHostname();
  153. if (size < (hostname.length() + 1))
  154. return -ENAMETOOLONG;
  155. memcpy(buffer, hostname.characters(), size);
  156. return 0;
  157. }
  158. Process* Process::fork(RegisterDump& regs)
  159. {
  160. auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copyRef(), m_executable.copyRef(), m_tty, this);
  161. #ifdef FORK_DEBUG
  162. dbgprintf("fork: child=%p\n", child);
  163. #endif
  164. #if 0
  165. // FIXME: An honest fork() would copy these. Needs a Vector copy ctor.
  166. child->m_arguments = m_arguments;
  167. child->m_initialEnvironment = m_initialEnvironment;
  168. #endif
  169. for (auto& region : m_regions) {
  170. #ifdef FORK_DEBUG
  171. dbgprintf("fork: cloning Region{%p}\n", region.ptr());
  172. #endif
  173. auto cloned_region = region->clone();
  174. child->m_regions.append(move(cloned_region));
  175. MM.mapRegion(*child, *child->m_regions.last());
  176. }
  177. child->m_tss.eax = 0; // fork() returns 0 in the child :^)
  178. child->m_tss.ebx = regs.ebx;
  179. child->m_tss.ecx = regs.ecx;
  180. child->m_tss.edx = regs.edx;
  181. child->m_tss.ebp = regs.ebp;
  182. child->m_tss.esp = regs.esp_if_crossRing;
  183. child->m_tss.esi = regs.esi;
  184. child->m_tss.edi = regs.edi;
  185. child->m_tss.eflags = regs.eflags;
  186. child->m_tss.eip = regs.eip;
  187. child->m_tss.cs = regs.cs;
  188. child->m_tss.ds = regs.ds;
  189. child->m_tss.es = regs.es;
  190. child->m_tss.fs = regs.fs;
  191. child->m_tss.gs = regs.gs;
  192. child->m_tss.ss = regs.ss_if_crossRing;
  193. #ifdef FORK_DEBUG
  194. 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);
  195. #endif
  196. ProcFileSystem::the().addProcess(*child);
  197. g_processes->prepend(child);
  198. system.nprocess++;
  199. #ifdef TASK_DEBUG
  200. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child->m_tss.eip);
  201. #endif
  202. return child;
  203. }
  204. pid_t Process::sys$fork(RegisterDump& regs)
  205. {
  206. auto* child = fork(regs);
  207. ASSERT(child);
  208. return child->pid();
  209. }
  210. int Process::exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  211. {
  212. auto parts = path.split('/');
  213. if (parts.isEmpty())
  214. return -ENOENT;
  215. int error;
  216. auto descriptor = VirtualFileSystem::the().open(path, error, 0, m_cwd ? m_cwd->inode : InodeIdentifier());
  217. if (!descriptor) {
  218. ASSERT(error != 0);
  219. return error;
  220. }
  221. if (!descriptor->metadata().mayExecute(m_euid, m_gids))
  222. return -EACCES;
  223. auto elfData = descriptor->readEntireFile();
  224. if (!elfData)
  225. return -EIO; // FIXME: Get a more detailed error from VFS.
  226. dword entry_eip = 0;
  227. PageDirectory* old_page_directory;
  228. PageDirectory* new_page_directory;
  229. {
  230. InterruptDisabler disabler;
  231. // Okay, here comes the sleight of hand, pay close attention..
  232. auto old_regions = move(m_regions);
  233. old_page_directory = m_page_directory;
  234. new_page_directory = reinterpret_cast<PageDirectory*>(kmalloc_page_aligned(sizeof(PageDirectory)));
  235. MM.populate_page_directory(*new_page_directory);
  236. m_page_directory = new_page_directory;
  237. MM.enter_process_paging_scope(*this);
  238. ELFLoader loader(move(elfData));
  239. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  240. ASSERT(size);
  241. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  242. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  243. return laddr.asPtr();
  244. };
  245. bool success = loader.load();
  246. if (!success) {
  247. m_page_directory = old_page_directory;
  248. MM.enter_process_paging_scope(*this);
  249. MM.release_page_directory(*new_page_directory);
  250. m_regions = move(old_regions);
  251. kprintf("sys$execve: Failure loading %s\n", path.characters());
  252. return -ENOEXEC;
  253. }
  254. entry_eip = (dword)loader.symbol_ptr("_start");
  255. if (!entry_eip) {
  256. m_page_directory = old_page_directory;
  257. MM.enter_process_paging_scope(*this);
  258. MM.release_page_directory(*new_page_directory);
  259. m_regions = move(old_regions);
  260. return -ENOEXEC;
  261. }
  262. }
  263. InterruptDisabler disabler;
  264. Scheduler::prepare_to_modify_tss(*this);
  265. m_name = parts.takeLast();
  266. dword old_esp0 = m_tss.esp0;
  267. memset(&m_tss, 0, sizeof(m_tss));
  268. m_tss.eflags = 0x0202;
  269. m_tss.eip = entry_eip;
  270. m_tss.cs = 0x1b;
  271. m_tss.ds = 0x23;
  272. m_tss.es = 0x23;
  273. m_tss.fs = 0x23;
  274. m_tss.gs = 0x23;
  275. m_tss.ss = 0x23;
  276. m_tss.cr3 = (dword)m_page_directory;
  277. m_stack_region = allocate_region(LinearAddress(), defaultStackSize, "stack");
  278. ASSERT(m_stack_region);
  279. m_stackTop3 = m_stack_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  280. m_tss.esp = m_stackTop3;
  281. m_tss.ss0 = 0x10;
  282. m_tss.esp0 = old_esp0;
  283. m_tss.ss2 = m_pid;
  284. MM.release_page_directory(*old_page_directory);
  285. m_executable = descriptor->vnode();
  286. m_arguments = move(arguments);
  287. m_initialEnvironment = move(environment);
  288. #ifdef TASK_DEBUG
  289. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), m_tss.eip);
  290. #endif
  291. set_state(Skip1SchedulerPass);
  292. if (current == this) {
  293. bool success = Scheduler::yield();
  294. ASSERT(success);
  295. }
  296. return 0;
  297. }
  298. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  299. {
  300. VALIDATE_USER_READ(filename, strlen(filename));
  301. if (argv) {
  302. for (size_t i = 0; argv[i]; ++i) {
  303. VALIDATE_USER_READ(argv[i], strlen(argv[i]));
  304. }
  305. }
  306. if (envp) {
  307. for (size_t i = 0; envp[i]; ++i) {
  308. VALIDATE_USER_READ(envp[i], strlen(envp[i]));
  309. }
  310. }
  311. String path(filename);
  312. auto parts = path.split('/');
  313. Vector<String> arguments;
  314. if (argv) {
  315. for (size_t i = 0; argv[i]; ++i) {
  316. arguments.append(argv[i]);
  317. }
  318. } else {
  319. arguments.append(parts.last());
  320. }
  321. Vector<String> environment;
  322. if (envp) {
  323. for (size_t i = 0; envp[i]; ++i) {
  324. environment.append(envp[i]);
  325. }
  326. }
  327. int rc = exec(path, move(arguments), move(environment));
  328. ASSERT(rc < 0); // We should never continue after a successful exec!
  329. return rc;
  330. }
  331. pid_t Process::sys$spawn(const char* filename, const char** argv, const char** envp)
  332. {
  333. VALIDATE_USER_READ(filename, strlen(filename));
  334. if (argv) {
  335. for (size_t i = 0; argv[i]; ++i) {
  336. VALIDATE_USER_READ(argv[i], strlen(argv[i]));
  337. }
  338. }
  339. if (envp) {
  340. for (size_t i = 0; envp[i]; ++i) {
  341. VALIDATE_USER_READ(envp[i], strlen(envp[i]));
  342. }
  343. }
  344. String path(filename);
  345. auto parts = path.split('/');
  346. Vector<String> arguments;
  347. if (argv) {
  348. for (size_t i = 0; argv[i]; ++i) {
  349. arguments.append(argv[i]);
  350. }
  351. } else {
  352. arguments.append(parts.last());
  353. }
  354. Vector<String> environment;
  355. if (envp) {
  356. for (size_t i = 0; envp[i]; ++i) {
  357. environment.append(envp[i]);
  358. }
  359. }
  360. int error;
  361. auto* child = create_user_process(path, m_uid, m_gid, m_pid, error, move(arguments), move(environment), m_tty);
  362. if (child)
  363. return child->pid();
  364. return error;
  365. }
  366. 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)
  367. {
  368. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  369. auto parts = path.split('/');
  370. if (arguments.isEmpty()) {
  371. arguments.append(parts.last());
  372. }
  373. RetainPtr<VirtualFileSystem::Node> cwd;
  374. {
  375. InterruptDisabler disabler;
  376. if (auto* parent = Process::from_pid(parent_pid))
  377. cwd = parent->m_cwd.copyRef();
  378. }
  379. if (!cwd)
  380. cwd = VirtualFileSystem::the().root();
  381. auto* process = new Process(parts.takeLast(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  382. error = process->exec(path, move(arguments), move(environment));
  383. if (error != 0)
  384. return nullptr;
  385. ProcFileSystem::the().addProcess(*process);
  386. g_processes->prepend(process);
  387. system.nprocess++;
  388. #ifdef TASK_DEBUG
  389. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  390. #endif
  391. error = 0;
  392. return process;
  393. }
  394. int Process::sys$get_environment(char*** environ)
  395. {
  396. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "environ");
  397. if (!region)
  398. return -ENOMEM;
  399. MM.mapRegion(*this, *region);
  400. char* envpage = (char*)region->linearAddress.get();
  401. *environ = (char**)envpage;
  402. char* bufptr = envpage + (sizeof(char*) * (m_initialEnvironment.size() + 1));
  403. for (size_t i = 0; i < m_initialEnvironment.size(); ++i) {
  404. (*environ)[i] = bufptr;
  405. memcpy(bufptr, m_initialEnvironment[i].characters(), m_initialEnvironment[i].length());
  406. bufptr += m_initialEnvironment[i].length();
  407. *(bufptr++) = '\0';
  408. }
  409. (*environ)[m_initialEnvironment.size()] = nullptr;
  410. return 0;
  411. }
  412. int Process::sys$get_arguments(int* argc, char*** argv)
  413. {
  414. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "argv");
  415. if (!region)
  416. return -ENOMEM;
  417. MM.mapRegion(*this, *region);
  418. char* argpage = (char*)region->linearAddress.get();
  419. *argc = m_arguments.size();
  420. *argv = (char**)argpage;
  421. char* bufptr = argpage + (sizeof(char*) * m_arguments.size());
  422. for (size_t i = 0; i < m_arguments.size(); ++i) {
  423. (*argv)[i] = bufptr;
  424. memcpy(bufptr, m_arguments[i].characters(), m_arguments[i].length());
  425. bufptr += m_arguments[i].length();
  426. *(bufptr++) = '\0';
  427. }
  428. return 0;
  429. }
  430. Process* Process::create_kernel_process(void (*e)(), String&& name)
  431. {
  432. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  433. process->m_tss.eip = (dword)e;
  434. if (process->pid() != 0) {
  435. InterruptDisabler disabler;
  436. g_processes->prepend(process);
  437. system.nprocess++;
  438. ProcFileSystem::the().addProcess(*process);
  439. #ifdef TASK_DEBUG
  440. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  441. #endif
  442. }
  443. return process;
  444. }
  445. 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)
  446. : m_name(move(name))
  447. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  448. , m_uid(uid)
  449. , m_gid(gid)
  450. , m_euid(uid)
  451. , m_egid(gid)
  452. , m_state(Runnable)
  453. , m_ring(ring)
  454. , m_cwd(move(cwd))
  455. , m_executable(move(executable))
  456. , m_tty(tty)
  457. , m_ppid(ppid)
  458. {
  459. m_gids.set(m_gid);
  460. if (fork_parent) {
  461. m_sid = fork_parent->m_sid;
  462. m_pgid = fork_parent->m_pgid;
  463. } else {
  464. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  465. InterruptDisabler disabler;
  466. if (auto* parent = Process::from_pid(m_ppid)) {
  467. m_sid = parent->m_sid;
  468. m_pgid = parent->m_pgid;
  469. }
  470. }
  471. m_page_directory = (PageDirectory*)kmalloc_page_aligned(sizeof(PageDirectory));
  472. MM.populate_page_directory(*m_page_directory);
  473. if (fork_parent) {
  474. m_file_descriptors.resize(fork_parent->m_file_descriptors.size());
  475. for (size_t i = 0; i < fork_parent->m_file_descriptors.size(); ++i) {
  476. if (!fork_parent->m_file_descriptors[i])
  477. continue;
  478. #ifdef FORK_DEBUG
  479. dbgprintf("fork: cloning fd %u... (%p) istty? %um\n", i, fork_parent->m_file_descriptors[i].ptr(), fork_parent->m_file_descriptors[i]->isTTY());
  480. #endif
  481. m_file_descriptors[i] = fork_parent->m_file_descriptors[i]->clone();
  482. }
  483. } else {
  484. m_file_descriptors.resize(m_max_open_file_descriptors);
  485. if (tty) {
  486. m_file_descriptors[0] = tty->open(O_RDONLY);
  487. m_file_descriptors[1] = tty->open(O_WRONLY);
  488. m_file_descriptors[2] = tty->open(O_WRONLY);
  489. }
  490. }
  491. if (fork_parent)
  492. m_nextRegion = fork_parent->m_nextRegion;
  493. else
  494. m_nextRegion = LinearAddress(0x10000000);
  495. if (fork_parent) {
  496. memcpy(&m_tss, &fork_parent->m_tss, sizeof(m_tss));
  497. } else {
  498. memset(&m_tss, 0, sizeof(m_tss));
  499. // Only IF is set when a process boots.
  500. m_tss.eflags = 0x0202;
  501. word cs, ds, ss;
  502. if (isRing0()) {
  503. cs = 0x08;
  504. ds = 0x10;
  505. ss = 0x10;
  506. } else {
  507. cs = 0x1b;
  508. ds = 0x23;
  509. ss = 0x23;
  510. }
  511. m_tss.ds = ds;
  512. m_tss.es = ds;
  513. m_tss.fs = ds;
  514. m_tss.gs = ds;
  515. m_tss.ss = ss;
  516. m_tss.cs = cs;
  517. }
  518. m_tss.cr3 = (dword)m_page_directory;
  519. if (isRing0()) {
  520. // FIXME: This memory is leaked.
  521. // But uh, there's also no kernel process termination, so I guess it's not technically leaked...
  522. dword stackBottom = (dword)kmalloc_eternal(defaultStackSize);
  523. m_stackTop0 = (stackBottom + defaultStackSize) & 0xffffff8;
  524. m_tss.esp = m_stackTop0;
  525. } else {
  526. if (fork_parent) {
  527. m_stackTop3 = fork_parent->m_stackTop3;
  528. } else {
  529. auto* region = allocate_region(LinearAddress(), defaultStackSize, "stack");
  530. ASSERT(region);
  531. m_stackTop3 = region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  532. m_tss.esp = m_stackTop3;
  533. }
  534. }
  535. if (isRing3()) {
  536. // Ring3 processes need a separate stack for Ring0.
  537. m_kernelStack = kmalloc(defaultStackSize);
  538. m_stackTop0 = ((DWORD)m_kernelStack + defaultStackSize) & 0xffffff8;
  539. m_tss.ss0 = 0x10;
  540. m_tss.esp0 = m_stackTop0;
  541. }
  542. // HACK: Ring2 SS in the TSS is the current PID.
  543. m_tss.ss2 = m_pid;
  544. m_farPtr.offset = 0x98765432;
  545. }
  546. Process::~Process()
  547. {
  548. InterruptDisabler disabler;
  549. ProcFileSystem::the().removeProcess(*this);
  550. system.nprocess--;
  551. gdt_free_entry(selector());
  552. if (m_kernelStack) {
  553. kfree(m_kernelStack);
  554. m_kernelStack = nullptr;
  555. }
  556. MM.release_page_directory(*m_page_directory);
  557. }
  558. void Process::dumpRegions()
  559. {
  560. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  561. kprintf("BEGIN END SIZE NAME\n");
  562. for (auto& region : m_regions) {
  563. kprintf("%x -- %x %x %s\n",
  564. region->linearAddress.get(),
  565. region->linearAddress.offset(region->size - 1).get(),
  566. region->size,
  567. region->name.characters());
  568. }
  569. }
  570. void Process::sys$exit(int status)
  571. {
  572. cli();
  573. #ifdef TASK_DEBUG
  574. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  575. #endif
  576. set_state(Dead);
  577. m_termination_status = status;
  578. m_termination_signal = 0;
  579. Scheduler::pick_next_and_switch_now();
  580. ASSERT_NOT_REACHED();
  581. }
  582. void Process::terminate_due_to_signal(byte signal)
  583. {
  584. ASSERT_INTERRUPTS_DISABLED();
  585. ASSERT(signal < 32);
  586. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  587. m_termination_status = 0;
  588. m_termination_signal = signal;
  589. set_state(Dead);
  590. }
  591. void Process::send_signal(byte signal, Process* sender)
  592. {
  593. ASSERT_INTERRUPTS_DISABLED();
  594. ASSERT(signal < 32);
  595. m_pending_signals |= 1 << signal;
  596. if (sender)
  597. dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, name().characters(), pid());
  598. else
  599. dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, name().characters(), pid());
  600. }
  601. bool Process::has_unmasked_pending_signals() const
  602. {
  603. return m_pending_signals & ~m_signal_mask;
  604. }
  605. void Process::dispatch_one_pending_signal()
  606. {
  607. ASSERT_INTERRUPTS_DISABLED();
  608. dword signal_candidates = m_pending_signals & ~m_signal_mask;
  609. ASSERT(signal_candidates);
  610. byte signal = 0;
  611. for (; signal < 32; ++signal) {
  612. if (signal_candidates & (1 << signal)) {
  613. break;
  614. }
  615. }
  616. dispatch_signal(signal);
  617. }
  618. void Process::dispatch_signal(byte signal)
  619. {
  620. ASSERT_INTERRUPTS_DISABLED();
  621. ASSERT(signal < 32);
  622. dbgprintf("dispatch_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  623. auto& action = m_signal_action_data[signal];
  624. // FIXME: Implement SA_SIGINFO signal handlers.
  625. ASSERT(!(action.flags & SA_SIGINFO));
  626. auto handler_laddr = action.handler_or_sigaction;
  627. if (handler_laddr.is_null()) {
  628. // FIXME: Is termination really always the appropriate action?
  629. return terminate_due_to_signal(signal);
  630. }
  631. Scheduler::prepare_to_modify_tss(*this);
  632. word ret_cs = m_tss.cs;
  633. dword ret_eip = m_tss.eip;
  634. dword ret_eflags = m_tss.eflags;
  635. bool interrupting_in_kernel = (ret_cs & 3) == 0;
  636. if (interrupting_in_kernel) {
  637. dbgprintf("dispatch_signal to %s(%u) in state=%s with return to %w:%x\n", name().characters(), pid(), toString(state()), ret_cs, ret_eip);
  638. ASSERT(is_blocked());
  639. m_tss_to_resume_kernel = m_tss;
  640. #ifdef SIGNAL_DEBUG
  641. dbgprintf("resume tss pc: %w:%x\n", m_tss_to_resume_kernel.cs, m_tss_to_resume_kernel.eip);
  642. #endif
  643. }
  644. ProcessPagingScope pagingScope(*this);
  645. if (interrupting_in_kernel) {
  646. if (!m_signal_stack_user_region) {
  647. m_signal_stack_user_region = allocate_region(LinearAddress(), defaultStackSize, "signal stack (user)");
  648. ASSERT(m_signal_stack_user_region);
  649. m_signal_stack_kernel_region = allocate_region(LinearAddress(), defaultStackSize, "signal stack (kernel)");
  650. ASSERT(m_signal_stack_user_region);
  651. }
  652. m_tss.ss = 0x23;
  653. m_tss.esp = m_signal_stack_user_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  654. m_tss.ss0 = 0x10;
  655. m_tss.esp0 = m_signal_stack_kernel_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
  656. push_value_on_stack(ret_eflags);
  657. push_value_on_stack(ret_cs);
  658. push_value_on_stack(ret_eip);
  659. } else {
  660. push_value_on_stack(ret_cs);
  661. push_value_on_stack(ret_eip);
  662. push_value_on_stack(ret_eflags);
  663. }
  664. // PUSHA
  665. dword old_esp = m_tss.esp;
  666. push_value_on_stack(m_tss.eax);
  667. push_value_on_stack(m_tss.ecx);
  668. push_value_on_stack(m_tss.edx);
  669. push_value_on_stack(m_tss.ebx);
  670. push_value_on_stack(old_esp);
  671. push_value_on_stack(m_tss.ebp);
  672. push_value_on_stack(m_tss.esi);
  673. push_value_on_stack(m_tss.edi);
  674. m_tss.eax = (dword)signal;
  675. m_tss.cs = 0x1b;
  676. m_tss.ds = 0x23;
  677. m_tss.es = 0x23;
  678. m_tss.fs = 0x23;
  679. m_tss.gs = 0x23;
  680. m_tss.eip = handler_laddr.get();
  681. if (m_return_to_ring3_from_signal_trampoline.is_null()) {
  682. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  683. // FIXME: Remap as read-only after setup.
  684. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "signal_trampoline", true, true);
  685. m_return_to_ring3_from_signal_trampoline = region->linearAddress;
  686. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.asPtr();
  687. *code_ptr++ = 0x61; // popa
  688. *code_ptr++ = 0x9d; // popf
  689. *code_ptr++ = 0xc3; // ret
  690. *code_ptr++ = 0x0f; // ud2
  691. *code_ptr++ = 0x0b;
  692. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  693. *code_ptr++ = 0x61; // popa
  694. *code_ptr++ = 0xb8; // mov eax, <dword>
  695. *(dword*)code_ptr = Syscall::SC_sigreturn;
  696. code_ptr += sizeof(dword);
  697. *code_ptr++ = 0xcd; // int 0x80
  698. *code_ptr++ = 0x80;
  699. *code_ptr++ = 0x0f; // ud2
  700. *code_ptr++ = 0x0b;
  701. // FIXME: For !SA_NODEFER, maybe we could do something like emitting an int 0x80 syscall here that
  702. // unmasks the signal so it can be received again? I guess then I would need one trampoline
  703. // per signal number if it's hard-coded, but it's just a few bytes per each.
  704. }
  705. if (interrupting_in_kernel)
  706. push_value_on_stack(m_return_to_ring0_from_signal_trampoline.get());
  707. else
  708. push_value_on_stack(m_return_to_ring3_from_signal_trampoline.get());
  709. m_pending_signals &= ~(1 << signal);
  710. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  711. set_state(Skip1SchedulerPass);
  712. #ifdef SIGNAL_DEBUG
  713. dbgprintf("signal: Okay, %s(%u) {%s} has been primed with signal handler %w:%x\n", name().characters(), pid(), toString(state()), m_tss.cs, m_tss.eip);
  714. #endif
  715. }
  716. void Process::sys$sigreturn()
  717. {
  718. InterruptDisabler disabler;
  719. Scheduler::prepare_to_modify_tss(*this);
  720. m_tss = m_tss_to_resume_kernel;
  721. #ifdef SIGNAL_DEBUG
  722. dbgprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  723. dbgprintf(" -> resuming execution at %w:%x\n", m_tss.cs, m_tss.eip);
  724. #endif
  725. set_state(Skip1SchedulerPass);
  726. Scheduler::yield();
  727. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  728. ASSERT_NOT_REACHED();
  729. }
  730. void Process::push_value_on_stack(dword value)
  731. {
  732. m_tss.esp -= 4;
  733. dword* stack_ptr = (dword*)m_tss.esp;
  734. *stack_ptr = value;
  735. }
  736. void Process::crash()
  737. {
  738. ASSERT_INTERRUPTS_DISABLED();
  739. ASSERT(state() != Dead);
  740. m_termination_signal = SIGSEGV;
  741. set_state(Dead);
  742. dumpRegions();
  743. Scheduler::pick_next_and_switch_now();
  744. ASSERT_NOT_REACHED();
  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. void Process::reap(pid_t pid)
  1077. {
  1078. InterruptDisabler disabler;
  1079. auto* process = Process::from_pid(pid);
  1080. ASSERT(process);
  1081. dbgprintf("reap: %s(%u) {%s}\n", process->name().characters(), process->pid(), toString(process->state()));
  1082. ASSERT(process->state() == Dead);
  1083. g_processes->remove(process);
  1084. delete process;
  1085. }
  1086. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1087. {
  1088. if (wstatus)
  1089. VALIDATE_USER_WRITE(wstatus, sizeof(int));
  1090. {
  1091. InterruptDisabler disabler;
  1092. if (!Process::from_pid(waitee))
  1093. return -ECHILD;
  1094. }
  1095. m_waitee = waitee;
  1096. m_waitee_status = 0;
  1097. block(BlockedWait);
  1098. sched_yield();
  1099. if (m_was_interrupted_while_blocked)
  1100. return -EINTR;
  1101. reap(waitee);
  1102. if (wstatus)
  1103. *wstatus = m_waitee_status;
  1104. return m_waitee;
  1105. }
  1106. void Process::unblock()
  1107. {
  1108. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1109. system.nblocked--;
  1110. m_state = Process::Runnable;
  1111. }
  1112. void Process::block(Process::State state)
  1113. {
  1114. ASSERT(current->state() == Process::Running);
  1115. system.nblocked++;
  1116. m_was_interrupted_while_blocked = false;
  1117. set_state(state);
  1118. }
  1119. void block(Process::State state)
  1120. {
  1121. current->block(state);
  1122. sched_yield();
  1123. }
  1124. void sleep(DWORD ticks)
  1125. {
  1126. ASSERT(current->state() == Process::Running);
  1127. current->setWakeupTime(system.uptime + ticks);
  1128. current->block(Process::BlockedSleep);
  1129. sched_yield();
  1130. }
  1131. bool Process::isValidAddressForKernel(LinearAddress laddr) const
  1132. {
  1133. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1134. // This code allows access outside of the known used address ranges to get caught.
  1135. InterruptDisabler disabler;
  1136. if (laddr.get() >= ksyms().first().address && laddr.get() <= ksyms().last().address)
  1137. return true;
  1138. if (is_kmalloc_address((void*)laddr.get()))
  1139. return true;
  1140. return validate_user_read(laddr);
  1141. }
  1142. bool Process::validate_user_read(LinearAddress laddr) const
  1143. {
  1144. InterruptDisabler disabler;
  1145. return MM.validate_user_read(*this, laddr);
  1146. }
  1147. bool Process::validate_user_write(LinearAddress laddr) const
  1148. {
  1149. InterruptDisabler disabler;
  1150. return MM.validate_user_write(*this, laddr);
  1151. }
  1152. pid_t Process::sys$getsid(pid_t pid)
  1153. {
  1154. if (pid == 0)
  1155. return m_sid;
  1156. InterruptDisabler disabler;
  1157. auto* process = Process::from_pid(pid);
  1158. if (!process)
  1159. return -ESRCH;
  1160. if (m_sid != process->m_sid)
  1161. return -EPERM;
  1162. return process->m_sid;
  1163. }
  1164. pid_t Process::sys$setsid()
  1165. {
  1166. InterruptDisabler disabler;
  1167. bool found_process_with_same_pgid_as_my_pid = false;
  1168. Process::for_each_in_pgrp(pid(), [&] (auto& process) {
  1169. found_process_with_same_pgid_as_my_pid = true;
  1170. return false;
  1171. });
  1172. if (found_process_with_same_pgid_as_my_pid)
  1173. return -EPERM;
  1174. m_sid = m_pid;
  1175. m_pgid = m_pid;
  1176. return m_sid;
  1177. }
  1178. pid_t Process::sys$getpgid(pid_t pid)
  1179. {
  1180. if (pid == 0)
  1181. return m_pgid;
  1182. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1183. auto* process = Process::from_pid(pid);
  1184. if (!process)
  1185. return -ESRCH;
  1186. return process->m_pgid;
  1187. }
  1188. pid_t Process::sys$getpgrp()
  1189. {
  1190. return m_pgid;
  1191. }
  1192. static pid_t get_sid_from_pgid(pid_t pgid)
  1193. {
  1194. InterruptDisabler disabler;
  1195. auto* group_leader = Process::from_pid(pgid);
  1196. if (!group_leader)
  1197. return -1;
  1198. return group_leader->sid();
  1199. }
  1200. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1201. {
  1202. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1203. pid_t pid = specified_pid ? specified_pid : m_pid;
  1204. if (specified_pgid < 0)
  1205. return -EINVAL;
  1206. auto* process = Process::from_pid(pid);
  1207. if (!process)
  1208. return -ESRCH;
  1209. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1210. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1211. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1212. if (current_sid != new_sid) {
  1213. // Can't move a process between sessions.
  1214. return -EPERM;
  1215. }
  1216. // FIXME: There are more EPERM conditions to check for here..
  1217. process->m_pgid = new_pgid;
  1218. return 0;
  1219. }
  1220. pid_t Process::sys$tcgetpgrp(int fd)
  1221. {
  1222. auto* descriptor = file_descriptor(fd);
  1223. if (!descriptor)
  1224. return -EBADF;
  1225. if (!descriptor->isTTY())
  1226. return -ENOTTY;
  1227. auto& tty = *descriptor->tty();
  1228. if (&tty != m_tty)
  1229. return -ENOTTY;
  1230. return tty.pgid();
  1231. }
  1232. int Process::sys$tcsetpgrp(int fd, pid_t pgid)
  1233. {
  1234. if (pgid < 0)
  1235. return -EINVAL;
  1236. if (get_sid_from_pgid(pgid) != m_sid)
  1237. return -EINVAL;
  1238. auto* descriptor = file_descriptor(fd);
  1239. if (!descriptor)
  1240. return -EBADF;
  1241. if (!descriptor->isTTY())
  1242. return -ENOTTY;
  1243. auto& tty = *descriptor->tty();
  1244. if (&tty != m_tty)
  1245. return -ENOTTY;
  1246. tty.set_pgid(pgid);
  1247. return 0;
  1248. }
  1249. int Process::sys$getdtablesize()
  1250. {
  1251. return m_max_open_file_descriptors;
  1252. }
  1253. int Process::sys$dup(int old_fd)
  1254. {
  1255. auto* descriptor = file_descriptor(old_fd);
  1256. if (!descriptor)
  1257. return -EBADF;
  1258. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1259. return -EMFILE;
  1260. int new_fd = 0;
  1261. for (; new_fd < m_max_open_file_descriptors; ++new_fd) {
  1262. if (!m_file_descriptors[new_fd])
  1263. break;
  1264. }
  1265. m_file_descriptors[new_fd] = descriptor;
  1266. return new_fd;
  1267. }
  1268. int Process::sys$dup2(int old_fd, int new_fd)
  1269. {
  1270. auto* descriptor = file_descriptor(old_fd);
  1271. if (!descriptor)
  1272. return -EBADF;
  1273. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1274. return -EMFILE;
  1275. m_file_descriptors[new_fd] = descriptor;
  1276. return new_fd;
  1277. }
  1278. Unix::sighandler_t Process::sys$signal(int signum, Unix::sighandler_t handler)
  1279. {
  1280. // FIXME: Fail with -EINVAL if attepmting to catch or ignore SIGKILL or SIGSTOP.
  1281. if (signum >= 32)
  1282. return (Unix::sighandler_t)-EINVAL;
  1283. dbgprintf("sys$signal: %d => L%x\n", signum, handler);
  1284. return nullptr;
  1285. }
  1286. int Process::sys$sigaction(int signum, const Unix::sigaction* act, Unix::sigaction* old_act)
  1287. {
  1288. // FIXME: Fail with -EINVAL if attepmting to change action for SIGKILL or SIGSTOP.
  1289. if (signum >= 32)
  1290. return -EINVAL;
  1291. VALIDATE_USER_READ(act, sizeof(Unix::sigaction));
  1292. InterruptDisabler disabler; // FIXME: This should use a narrower lock.
  1293. auto& action = m_signal_action_data[signum];
  1294. if (old_act) {
  1295. VALIDATE_USER_WRITE(old_act, sizeof(Unix::sigaction));
  1296. old_act->sa_flags = action.flags;
  1297. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1298. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1299. }
  1300. action.restorer = LinearAddress((dword)act->sa_restorer);
  1301. action.flags = act->sa_flags;
  1302. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1303. return 0;
  1304. }
  1305. int Process::sys$getgroups(int count, gid_t* gids)
  1306. {
  1307. if (count < 0)
  1308. return -EINVAL;
  1309. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1310. if (!count)
  1311. return m_gids.size();
  1312. if (count != m_gids.size())
  1313. return -EINVAL;
  1314. VALIDATE_USER_WRITE(gids, sizeof(gid_t) * count);
  1315. size_t i = 0;
  1316. for (auto gid : m_gids)
  1317. gids[i++] = gid;
  1318. return 0;
  1319. }
  1320. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1321. {
  1322. if (!is_root())
  1323. return -EPERM;
  1324. if (count >= MAX_PROCESS_GIDS)
  1325. return -EINVAL;
  1326. VALIDATE_USER_READ(gids, sizeof(gid_t) * count);
  1327. m_gids.clear();
  1328. m_gids.set(m_gid);
  1329. for (size_t i = 0; i < count; ++i)
  1330. m_gids.set(gids[i]);
  1331. return 0;
  1332. }