Process.cpp 42 KB

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