Process.cpp 50 KB

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