Process.cpp 42 KB

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