Process.cpp 42 KB

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