Process.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. #include "types.h"
  2. #include "Process.h"
  3. #include "kmalloc.h"
  4. #include "StdLib.h"
  5. #include "i386.h"
  6. #include "system.h"
  7. #include <Kernel/FileDescriptor.h>
  8. #include <Kernel/VirtualFileSystem.h>
  9. #include "ELFLoader.h"
  10. #include "MemoryManager.h"
  11. #include "i8253.h"
  12. #include "RTC.h"
  13. #include <AK/StdLibExtras.h>
  14. #include <LibC/signal_numbers.h>
  15. #include <LibC/errno_numbers.h>
  16. #include "Syscall.h"
  17. #include "Scheduler.h"
  18. #include "FIFO.h"
  19. #include "KSyms.h"
  20. #include <WindowServer/WSWindow.h>
  21. #include "MasterPTY.h"
  22. //#define DEBUG_IO
  23. //#define TASK_DEBUG
  24. //#define FORK_DEBUG
  25. #define SIGNAL_DEBUG
  26. #define MAX_PROCESS_GIDS 32
  27. static const dword default_kernel_stack_size = 16384;
  28. static const dword default_userspace_stack_size = 65536;
  29. static pid_t next_pid;
  30. InlineLinkedList<Process>* g_processes;
  31. static String* s_hostname;
  32. static String& hostname_storage(InterruptDisabler&)
  33. {
  34. ASSERT(s_hostname);
  35. return *s_hostname;
  36. }
  37. static String get_hostname()
  38. {
  39. InterruptDisabler disabler;
  40. return hostname_storage(disabler).isolated_copy();
  41. }
  42. CoolGlobals* g_cool_globals;
  43. void Process::initialize()
  44. {
  45. #ifdef COOL_GLOBALS
  46. g_cool_globals = reinterpret_cast<CoolGlobals*>(0x1000);
  47. #endif
  48. next_pid = 0;
  49. g_processes = new InlineLinkedList<Process>;
  50. s_hostname = new String("courage");
  51. Scheduler::initialize();
  52. initialize_gui_statics();
  53. }
  54. Vector<pid_t> Process::all_pids()
  55. {
  56. InterruptDisabler disabler;
  57. Vector<pid_t> pids;
  58. pids.ensure_capacity(g_processes->size_slow());
  59. for (auto* process = g_processes->head(); process; process = process->next())
  60. pids.unchecked_append(process->pid());
  61. return pids;
  62. }
  63. Vector<Process*> Process::all_processes()
  64. {
  65. InterruptDisabler disabler;
  66. Vector<Process*> processes;
  67. processes.ensure_capacity(g_processes->size_slow());
  68. for (auto* process = g_processes->head(); process; process = process->next())
  69. processes.unchecked_append(process);
  70. return processes;
  71. }
  72. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  73. {
  74. size = PAGE_ROUND_UP(size);
  75. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  76. if (laddr.is_null()) {
  77. laddr = m_next_region;
  78. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  79. }
  80. laddr.mask(0xfffff000);
  81. m_regions.append(adopt(*new Region(laddr, size, move(name), is_readable, is_writable)));
  82. MM.map_region(*this, *m_regions.last());
  83. if (commit)
  84. m_regions.last()->commit();
  85. return m_regions.last().ptr();
  86. }
  87. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Inode>&& inode, String&& name, bool is_readable, bool is_writable)
  88. {
  89. size = PAGE_ROUND_UP(size);
  90. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  91. if (laddr.is_null()) {
  92. laddr = m_next_region;
  93. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  94. }
  95. laddr.mask(0xfffff000);
  96. m_regions.append(adopt(*new Region(laddr, size, move(inode), move(name), is_readable, is_writable)));
  97. MM.map_region(*this, *m_regions.last());
  98. return m_regions.last().ptr();
  99. }
  100. Region* Process::allocate_region_with_vmo(LinearAddress laddr, size_t size, RetainPtr<VMObject>&& vmo, size_t offset_in_vmo, String&& name, bool is_readable, bool is_writable)
  101. {
  102. ASSERT(vmo);
  103. size = PAGE_ROUND_UP(size);
  104. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  105. if (laddr.is_null()) {
  106. laddr = m_next_region;
  107. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  108. }
  109. laddr.mask(0xfffff000);
  110. offset_in_vmo &= PAGE_MASK;
  111. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  112. m_regions.append(adopt(*new Region(laddr, size, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  113. MM.map_region(*this, *m_regions.last());
  114. return m_regions.last().ptr();
  115. }
  116. bool Process::deallocate_region(Region& region)
  117. {
  118. InterruptDisabler disabler;
  119. for (size_t i = 0; i < m_regions.size(); ++i) {
  120. if (m_regions[i].ptr() == &region) {
  121. MM.unmap_region(region);
  122. m_regions.remove(i);
  123. return true;
  124. }
  125. }
  126. return false;
  127. }
  128. Region* Process::region_from_range(LinearAddress laddr, size_t size)
  129. {
  130. for (auto& region : m_regions) {
  131. if (region->laddr() == laddr && region->size() == size)
  132. return region.ptr();
  133. }
  134. return nullptr;
  135. }
  136. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  137. {
  138. if (!validate_read_str(name))
  139. return -EFAULT;
  140. auto* region = region_from_range(LinearAddress((dword)addr), size);
  141. if (!region)
  142. return -EINVAL;
  143. region->set_name(String(name));
  144. return 0;
  145. }
  146. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  147. {
  148. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  149. return (void*)-EFAULT;
  150. void* addr = (void*)params->addr;
  151. size_t size = params->size;
  152. int prot = params->prot;
  153. int flags = params->flags;
  154. int fd = params->fd;
  155. off_t offset = params->offset;
  156. if (size == 0)
  157. return (void*)-EINVAL;
  158. if ((dword)addr & ~PAGE_MASK || size & ~PAGE_MASK)
  159. return (void*)-EINVAL;
  160. if (flags & MAP_ANONYMOUS) {
  161. InterruptDisabler disabler;
  162. // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
  163. ASSERT(addr == nullptr);
  164. auto* region = allocate_region(LinearAddress(), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  165. if (!region)
  166. return (void*)-ENOMEM;
  167. return region->laddr().as_ptr();
  168. }
  169. if (offset & ~PAGE_MASK)
  170. return (void*)-EINVAL;
  171. auto* descriptor = file_descriptor(fd);
  172. if (!descriptor)
  173. return (void*)-EBADF;
  174. if (!descriptor->supports_mmap())
  175. return (void*)-ENODEV;
  176. // FIXME: If PROT_EXEC, check that the underlying file system isn't mounted noexec.
  177. auto region_name = descriptor->absolute_path();
  178. InterruptDisabler disabler;
  179. // FIXME: Implement mapping at a client-specified address. Most of the support is already in plcae.
  180. ASSERT(addr == nullptr);
  181. auto* region = allocate_file_backed_region(LinearAddress(), size, descriptor->inode(), move(region_name), prot & PROT_READ, prot & PROT_WRITE);
  182. if (!region)
  183. return (void*)-ENOMEM;
  184. return region->laddr().as_ptr();
  185. }
  186. int Process::sys$munmap(void* addr, size_t size)
  187. {
  188. InterruptDisabler disabler;
  189. auto* region = region_from_range(LinearAddress((dword)addr), size);
  190. if (!region)
  191. return -1;
  192. if (!deallocate_region(*region))
  193. return -1;
  194. return 0;
  195. }
  196. int Process::sys$gethostname(char* buffer, size_t size)
  197. {
  198. if (!validate_write(buffer, size))
  199. return -EFAULT;
  200. auto hostname = get_hostname();
  201. if (size < (hostname.length() + 1))
  202. return -ENAMETOOLONG;
  203. memcpy(buffer, hostname.characters(), size);
  204. return 0;
  205. }
  206. Process* Process::fork(RegisterDump& regs)
  207. {
  208. auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copy_ref(), m_executable.copy_ref(), m_tty, this);
  209. if (!child)
  210. return nullptr;
  211. memcpy(child->m_signal_action_data, m_signal_action_data, sizeof(m_signal_action_data));
  212. child->m_signal_mask = m_signal_mask;
  213. #ifdef FORK_DEBUG
  214. dbgprintf("fork: child=%p\n", child);
  215. #endif
  216. child->m_initial_arguments = m_initial_arguments;
  217. child->m_initial_environment = m_initial_environment;
  218. for (auto& region : m_regions) {
  219. #ifdef FORK_DEBUG
  220. dbgprintf("fork: cloning Region{%p} \"%s\" L%x\n", region.ptr(), region->name.characters(), region->laddr().get());
  221. #endif
  222. auto cloned_region = region->clone();
  223. child->m_regions.append(move(cloned_region));
  224. MM.map_region(*child, *child->m_regions.last());
  225. if (region.ptr() == m_display_framebuffer_region.ptr())
  226. child->m_display_framebuffer_region = child->m_regions.last().copy_ref();
  227. }
  228. for (auto gid : m_gids)
  229. child->m_gids.set(gid);
  230. child->m_tss.eax = 0; // fork() returns 0 in the child :^)
  231. child->m_tss.ebx = regs.ebx;
  232. child->m_tss.ecx = regs.ecx;
  233. child->m_tss.edx = regs.edx;
  234. child->m_tss.ebp = regs.ebp;
  235. child->m_tss.esp = regs.esp_if_crossRing;
  236. child->m_tss.esi = regs.esi;
  237. child->m_tss.edi = regs.edi;
  238. child->m_tss.eflags = regs.eflags;
  239. child->m_tss.eip = regs.eip;
  240. child->m_tss.cs = regs.cs;
  241. child->m_tss.ds = regs.ds;
  242. child->m_tss.es = regs.es;
  243. child->m_tss.fs = regs.fs;
  244. child->m_tss.gs = regs.gs;
  245. child->m_tss.ss = regs.ss_if_crossRing;
  246. child->m_fpu_state = m_fpu_state;
  247. child->m_has_used_fpu = m_has_used_fpu;
  248. #ifdef FORK_DEBUG
  249. 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);
  250. #endif
  251. {
  252. InterruptDisabler disabler;
  253. g_processes->prepend(child);
  254. system.nprocess++;
  255. }
  256. #ifdef TASK_DEBUG
  257. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child->m_tss.eip);
  258. #endif
  259. return child;
  260. }
  261. pid_t Process::sys$fork(RegisterDump& regs)
  262. {
  263. auto* child = fork(regs);
  264. ASSERT(child);
  265. return child->pid();
  266. }
  267. int Process::do_exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  268. {
  269. ASSERT(is_ring3());
  270. auto parts = path.split('/');
  271. if (parts.is_empty())
  272. return -ENOENT;
  273. int error;
  274. auto descriptor = VFS::the().open(path, error, 0, 0, *cwd_inode());
  275. if (!descriptor) {
  276. ASSERT(error != 0);
  277. return error;
  278. }
  279. if (!descriptor->metadata().may_execute(m_euid, m_gids))
  280. return -EACCES;
  281. if (!descriptor->metadata().size) {
  282. kprintf("exec() of 0-length binaries not supported\n");
  283. return -ENOTIMPL;
  284. }
  285. dword entry_eip = 0;
  286. // FIXME: Is there a race here?
  287. auto old_page_directory = move(m_page_directory);
  288. m_page_directory = PageDirectory::create();
  289. #ifdef MM_DEBUG
  290. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  291. #endif
  292. ProcessPagingScope paging_scope(*this);
  293. auto vmo = VMObject::create_file_backed(descriptor->inode());
  294. vmo->set_name(descriptor->absolute_path());
  295. RetainPtr<Region> region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copy_ref(), 0, "helper", true, false);
  296. // FIXME: Should we consider doing on-demand paging here? Is it actually useful?
  297. bool success = region->page_in();
  298. ASSERT(success);
  299. {
  300. InterruptDisabler disabler;
  301. // Okay, here comes the sleight of hand, pay close attention..
  302. auto old_regions = move(m_regions);
  303. ELFLoader loader(region->laddr().as_ptr());
  304. loader.map_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, size_t offset_in_image, bool is_readable, bool is_writable, const String& name) {
  305. ASSERT(size);
  306. ASSERT(alignment == PAGE_SIZE);
  307. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  308. (void) allocate_region_with_vmo(laddr, size, vmo.copy_ref(), offset_in_image, String(name), is_readable, is_writable);
  309. return laddr.as_ptr();
  310. };
  311. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  312. ASSERT(size);
  313. ASSERT(alignment == PAGE_SIZE);
  314. size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
  315. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  316. return laddr.as_ptr();
  317. };
  318. bool success = loader.load();
  319. if (!success) {
  320. m_page_directory = move(old_page_directory);
  321. // FIXME: RAII this somehow instead.
  322. ASSERT(current == this);
  323. MM.enter_process_paging_scope(*this);
  324. m_regions = move(old_regions);
  325. kprintf("sys$execve: Failure loading %s\n", path.characters());
  326. return -ENOEXEC;
  327. }
  328. entry_eip = loader.entry().get();
  329. if (!entry_eip) {
  330. m_page_directory = move(old_page_directory);
  331. // FIXME: RAII this somehow instead.
  332. ASSERT(current == this);
  333. MM.enter_process_paging_scope(*this);
  334. m_regions = move(old_regions);
  335. return -ENOEXEC;
  336. }
  337. }
  338. m_regions.append(move(region));
  339. m_signal_stack_kernel_region = nullptr;
  340. m_signal_stack_user_region = nullptr;
  341. m_display_framebuffer_region = nullptr;
  342. set_default_signal_dispositions();
  343. m_signal_mask = 0xffffffff;
  344. m_pending_signals = 0;
  345. for (size_t i = 0; i < m_fds.size(); ++i) {
  346. auto& daf = m_fds[i];
  347. if (daf.descriptor && daf.flags & FD_CLOEXEC) {
  348. daf.descriptor->close();
  349. daf = { };
  350. }
  351. }
  352. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  353. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  354. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  355. cli();
  356. Scheduler::prepare_to_modify_tss(*this);
  357. m_name = parts.take_last();
  358. dword old_esp0 = m_tss.esp0;
  359. memset(&m_tss, 0, sizeof(m_tss));
  360. m_tss.eflags = 0x0202;
  361. m_tss.eip = entry_eip;
  362. m_tss.cs = 0x1b;
  363. m_tss.ds = 0x23;
  364. m_tss.es = 0x23;
  365. m_tss.fs = 0x23;
  366. m_tss.gs = 0x23;
  367. m_tss.ss = 0x23;
  368. m_tss.cr3 = page_directory().cr3();
  369. m_stack_region = allocate_region(LinearAddress(), default_userspace_stack_size, "stack");
  370. ASSERT(m_stack_region);
  371. m_stack_top3 = m_stack_region->laddr().offset(default_userspace_stack_size).get();
  372. m_tss.esp = m_stack_top3;
  373. m_tss.ss0 = 0x10;
  374. m_tss.esp0 = old_esp0;
  375. m_tss.ss2 = m_pid;
  376. m_executable = descriptor->inode();
  377. m_initial_arguments = move(arguments);
  378. m_initial_environment = move(environment);
  379. #ifdef TASK_DEBUG
  380. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), m_tss.eip);
  381. #endif
  382. set_state(Skip1SchedulerPass);
  383. return 0;
  384. }
  385. int Process::exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
  386. {
  387. // The bulk of exec() is done by do_exec(), which ensures that all locals
  388. // are cleaned up by the time we yield-teleport below.
  389. int rc = do_exec(path, move(arguments), move(environment));
  390. if (rc < 0)
  391. return rc;
  392. if (current == this) {
  393. Scheduler::yield();
  394. ASSERT_NOT_REACHED();
  395. }
  396. return 0;
  397. }
  398. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  399. {
  400. if (!validate_read_str(filename))
  401. return -EFAULT;
  402. if (argv) {
  403. if (!validate_read_typed(argv))
  404. return -EFAULT;
  405. for (size_t i = 0; argv[i]; ++i) {
  406. if (!validate_read_str(argv[i]))
  407. return -EFAULT;
  408. }
  409. }
  410. if (envp) {
  411. if (!validate_read_typed(envp))
  412. return -EFAULT;
  413. for (size_t i = 0; envp[i]; ++i) {
  414. if (!validate_read_str(envp[i]))
  415. return -EFAULT;
  416. }
  417. }
  418. String path(filename);
  419. auto parts = path.split('/');
  420. Vector<String> arguments;
  421. if (argv) {
  422. for (size_t i = 0; argv[i]; ++i) {
  423. arguments.append(argv[i]);
  424. }
  425. } else {
  426. arguments.append(parts.last());
  427. }
  428. Vector<String> environment;
  429. if (envp) {
  430. for (size_t i = 0; envp[i]; ++i)
  431. environment.append(envp[i]);
  432. }
  433. int rc = exec(path, move(arguments), move(environment));
  434. ASSERT(rc < 0); // We should never continue after a successful exec!
  435. return rc;
  436. }
  437. 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)
  438. {
  439. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  440. auto parts = path.split('/');
  441. if (arguments.is_empty()) {
  442. arguments.append(parts.last());
  443. }
  444. RetainPtr<Inode> cwd;
  445. {
  446. InterruptDisabler disabler;
  447. if (auto* parent = Process::from_pid(parent_pid))
  448. cwd = parent->m_cwd.copy_ref();
  449. }
  450. if (!cwd)
  451. cwd = VFS::the().root_inode();
  452. auto* process = new Process(parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  453. error = process->exec(path, move(arguments), move(environment));
  454. if (error != 0) {
  455. delete process;
  456. return nullptr;
  457. }
  458. {
  459. InterruptDisabler disabler;
  460. g_processes->prepend(process);
  461. system.nprocess++;
  462. }
  463. #ifdef TASK_DEBUG
  464. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  465. #endif
  466. error = 0;
  467. return process;
  468. }
  469. int Process::sys$get_environment(char*** environ)
  470. {
  471. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "environ");
  472. if (!region)
  473. return -ENOMEM;
  474. MM.map_region(*this, *region);
  475. char* envpage = (char*)region->laddr().get();
  476. *environ = (char**)envpage;
  477. char* bufptr = envpage + (sizeof(char*) * (m_initial_environment.size() + 1));
  478. for (size_t i = 0; i < m_initial_environment.size(); ++i) {
  479. (*environ)[i] = bufptr;
  480. memcpy(bufptr, m_initial_environment[i].characters(), m_initial_environment[i].length());
  481. bufptr += m_initial_environment[i].length();
  482. *(bufptr++) = '\0';
  483. }
  484. (*environ)[m_initial_environment.size()] = nullptr;
  485. return 0;
  486. }
  487. int Process::sys$get_arguments(int* argc, char*** argv)
  488. {
  489. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "argv");
  490. if (!region)
  491. return -ENOMEM;
  492. MM.map_region(*this, *region);
  493. char* argpage = (char*)region->laddr().get();
  494. *argc = m_initial_arguments.size();
  495. *argv = (char**)argpage;
  496. char* bufptr = argpage + (sizeof(char*) * (m_initial_arguments.size() + 1));
  497. for (size_t i = 0; i < m_initial_arguments.size(); ++i) {
  498. (*argv)[i] = bufptr;
  499. memcpy(bufptr, m_initial_arguments[i].characters(), m_initial_arguments[i].length());
  500. bufptr += m_initial_arguments[i].length();
  501. *(bufptr++) = '\0';
  502. }
  503. (*argv)[m_initial_arguments.size()] = nullptr;
  504. return 0;
  505. }
  506. Process* Process::create_kernel_process(String&& name, void (*e)())
  507. {
  508. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  509. process->m_tss.eip = (dword)e;
  510. if (process->pid() != 0) {
  511. {
  512. InterruptDisabler disabler;
  513. g_processes->prepend(process);
  514. system.nprocess++;
  515. }
  516. #ifdef TASK_DEBUG
  517. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
  518. #endif
  519. }
  520. return process;
  521. }
  522. Process::Process(String&& name, uid_t uid, gid_t gid, pid_t ppid, RingLevel ring, RetainPtr<Inode>&& cwd, RetainPtr<Inode>&& executable, TTY* tty, Process* fork_parent)
  523. : m_name(move(name))
  524. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  525. , m_uid(uid)
  526. , m_gid(gid)
  527. , m_euid(uid)
  528. , m_egid(gid)
  529. , m_state(Runnable)
  530. , m_ring(ring)
  531. , m_cwd(move(cwd))
  532. , m_executable(move(executable))
  533. , m_tty(tty)
  534. , m_ppid(ppid)
  535. {
  536. set_default_signal_dispositions();
  537. memset(&m_fpu_state, 0, sizeof(FPUState));
  538. m_gids.set(m_gid);
  539. if (fork_parent) {
  540. m_sid = fork_parent->m_sid;
  541. m_pgid = fork_parent->m_pgid;
  542. } else {
  543. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  544. InterruptDisabler disabler;
  545. if (auto* parent = Process::from_pid(m_ppid)) {
  546. m_sid = parent->m_sid;
  547. m_pgid = parent->m_pgid;
  548. }
  549. }
  550. m_page_directory = PageDirectory::create();
  551. #ifdef MM_DEBUG
  552. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  553. #endif
  554. if (fork_parent) {
  555. m_fds.resize(fork_parent->m_fds.size());
  556. for (size_t i = 0; i < fork_parent->m_fds.size(); ++i) {
  557. if (!fork_parent->m_fds[i].descriptor)
  558. continue;
  559. #ifdef FORK_DEBUG
  560. dbgprintf("fork: cloning fd %u... (%p) istty? %u\n", i, fork_parent->m_fds[i].descriptor.ptr(), fork_parent->m_fds[i].descriptor->is_tty());
  561. #endif
  562. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  563. m_fds[i].flags = fork_parent->m_fds[i].flags;
  564. }
  565. } else {
  566. m_fds.resize(m_max_open_file_descriptors);
  567. if (tty) {
  568. int error;
  569. m_fds[0].set(tty->open(error, O_RDONLY));
  570. m_fds[1].set(tty->open(error, O_WRONLY));
  571. m_fds[2].set(tty->open(error, O_WRONLY));
  572. }
  573. }
  574. if (fork_parent)
  575. m_next_region = fork_parent->m_next_region;
  576. else
  577. m_next_region = LinearAddress(0x10000000);
  578. if (fork_parent) {
  579. memcpy(&m_tss, &fork_parent->m_tss, sizeof(m_tss));
  580. } else {
  581. memset(&m_tss, 0, sizeof(m_tss));
  582. // Only IF is set when a process boots.
  583. m_tss.eflags = 0x0202;
  584. word cs, ds, ss;
  585. if (is_ring0()) {
  586. cs = 0x08;
  587. ds = 0x10;
  588. ss = 0x10;
  589. } else {
  590. cs = 0x1b;
  591. ds = 0x23;
  592. ss = 0x23;
  593. }
  594. m_tss.ds = ds;
  595. m_tss.es = ds;
  596. m_tss.fs = ds;
  597. m_tss.gs = ds;
  598. m_tss.ss = ss;
  599. m_tss.cs = cs;
  600. }
  601. m_tss.cr3 = page_directory().cr3();
  602. if (is_ring0()) {
  603. // FIXME: This memory is leaked.
  604. // But uh, there's also no kernel process termination, so I guess it's not technically leaked...
  605. dword stack_bottom = (dword)kmalloc_eternal(default_kernel_stack_size);
  606. m_stack_top0 = (stack_bottom + default_kernel_stack_size) & 0xffffff8;
  607. m_tss.esp = m_stack_top0;
  608. } else {
  609. if (fork_parent) {
  610. m_stack_top3 = fork_parent->m_stack_top3;
  611. } else {
  612. auto* region = allocate_region(LinearAddress(), default_userspace_stack_size, "stack");
  613. ASSERT(region);
  614. m_stack_top3 = region->laddr().offset(default_userspace_stack_size).get();
  615. m_tss.esp = m_stack_top3;
  616. }
  617. }
  618. if (is_ring3()) {
  619. // Ring3 processes need a separate stack for Ring0.
  620. m_kernel_stack = kmalloc(default_kernel_stack_size);
  621. m_stack_top0 = ((dword)m_kernel_stack + default_kernel_stack_size) & 0xffffff8;
  622. m_tss.ss0 = 0x10;
  623. m_tss.esp0 = m_stack_top0;
  624. }
  625. // HACK: Ring2 SS in the TSS is the current PID.
  626. m_tss.ss2 = m_pid;
  627. m_far_ptr.offset = 0x98765432;
  628. }
  629. Process::~Process()
  630. {
  631. InterruptDisabler disabler;
  632. system.nprocess--;
  633. if (g_last_fpu_process == this)
  634. g_last_fpu_process = nullptr;
  635. if (selector())
  636. gdt_free_entry(selector());
  637. if (m_kernel_stack) {
  638. kfree(m_kernel_stack);
  639. m_kernel_stack = nullptr;
  640. }
  641. }
  642. void Process::dump_regions()
  643. {
  644. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  645. kprintf("BEGIN END SIZE NAME\n");
  646. for (auto& region : m_regions) {
  647. kprintf("%x -- %x %x %s\n",
  648. region->laddr().get(),
  649. region->laddr().offset(region->size() - 1).get(),
  650. region->size(),
  651. region->name().characters());
  652. }
  653. }
  654. void Process::sys$exit(int status)
  655. {
  656. cli();
  657. #ifdef TASK_DEBUG
  658. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  659. #endif
  660. die();
  661. m_termination_status = status;
  662. m_termination_signal = 0;
  663. Scheduler::pick_next_and_switch_now();
  664. ASSERT_NOT_REACHED();
  665. }
  666. void Process::terminate_due_to_signal(byte signal)
  667. {
  668. ASSERT_INTERRUPTS_DISABLED();
  669. ASSERT(signal < 32);
  670. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  671. m_termination_status = 0;
  672. m_termination_signal = signal;
  673. die();
  674. }
  675. void Process::send_signal(byte signal, Process* sender)
  676. {
  677. ASSERT_INTERRUPTS_DISABLED();
  678. ASSERT(signal < 32);
  679. m_pending_signals |= 1 << signal;
  680. if (sender)
  681. dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, name().characters(), pid());
  682. else
  683. dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, name().characters(), pid());
  684. }
  685. bool Process::has_unmasked_pending_signals() const
  686. {
  687. return m_pending_signals & m_signal_mask;
  688. }
  689. ShouldUnblockProcess Process::dispatch_one_pending_signal()
  690. {
  691. ASSERT_INTERRUPTS_DISABLED();
  692. dword signal_candidates = m_pending_signals & m_signal_mask;
  693. ASSERT(signal_candidates);
  694. byte signal = 0;
  695. for (; signal < 32; ++signal) {
  696. if (signal_candidates & (1 << signal)) {
  697. break;
  698. }
  699. }
  700. return dispatch_signal(signal);
  701. }
  702. ShouldUnblockProcess Process::dispatch_signal(byte signal)
  703. {
  704. ASSERT_INTERRUPTS_DISABLED();
  705. ASSERT(signal < 32);
  706. dbgprintf("dispatch_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  707. auto& action = m_signal_action_data[signal];
  708. // FIXME: Implement SA_SIGINFO signal handlers.
  709. ASSERT(!(action.flags & SA_SIGINFO));
  710. // Mark this signal as handled.
  711. m_pending_signals &= ~(1 << signal);
  712. auto handler_laddr = action.handler_or_sigaction;
  713. if (handler_laddr.is_null()) {
  714. // FIXME: Is termination really always the appropriate action?
  715. terminate_due_to_signal(signal);
  716. return ShouldUnblockProcess::No;
  717. }
  718. if (handler_laddr.as_ptr() == SIG_IGN) {
  719. dbgprintf("%s(%u) ignored signal %u\n", name().characters(), pid(), signal);
  720. return ShouldUnblockProcess::Yes;
  721. }
  722. Scheduler::prepare_to_modify_tss(*this);
  723. word ret_cs = m_tss.cs;
  724. dword ret_eip = m_tss.eip;
  725. dword ret_eflags = m_tss.eflags;
  726. bool interrupting_in_kernel = (ret_cs & 3) == 0;
  727. if (interrupting_in_kernel) {
  728. dbgprintf("dispatch_signal to %s(%u) in state=%s with return to %w:%x\n", name().characters(), pid(), to_string(state()), ret_cs, ret_eip);
  729. ASSERT(is_blocked());
  730. m_tss_to_resume_kernel = m_tss;
  731. #ifdef SIGNAL_DEBUG
  732. dbgprintf("resume tss pc: %w:%x\n", m_tss_to_resume_kernel.cs, m_tss_to_resume_kernel.eip);
  733. #endif
  734. }
  735. ProcessPagingScope paging_scope(*this);
  736. if (interrupting_in_kernel) {
  737. if (!m_signal_stack_user_region) {
  738. m_signal_stack_user_region = allocate_region(LinearAddress(), default_userspace_stack_size, "signal stack (user)");
  739. ASSERT(m_signal_stack_user_region);
  740. m_signal_stack_kernel_region = allocate_region(LinearAddress(), default_userspace_stack_size, "signal stack (kernel)");
  741. ASSERT(m_signal_stack_user_region);
  742. }
  743. m_tss.ss = 0x23;
  744. m_tss.esp = m_signal_stack_user_region->laddr().offset(default_userspace_stack_size).get() & 0xfffffff8;
  745. m_tss.ss0 = 0x10;
  746. m_tss.esp0 = m_signal_stack_kernel_region->laddr().offset(default_userspace_stack_size).get() & 0xfffffff8;
  747. push_value_on_stack(ret_eflags);
  748. push_value_on_stack(ret_cs);
  749. push_value_on_stack(ret_eip);
  750. } else {
  751. push_value_on_stack(ret_cs);
  752. push_value_on_stack(ret_eip);
  753. push_value_on_stack(ret_eflags);
  754. }
  755. // PUSHA
  756. dword old_esp = m_tss.esp;
  757. push_value_on_stack(m_tss.eax);
  758. push_value_on_stack(m_tss.ecx);
  759. push_value_on_stack(m_tss.edx);
  760. push_value_on_stack(m_tss.ebx);
  761. push_value_on_stack(old_esp);
  762. push_value_on_stack(m_tss.ebp);
  763. push_value_on_stack(m_tss.esi);
  764. push_value_on_stack(m_tss.edi);
  765. m_tss.eax = (dword)signal;
  766. m_tss.cs = 0x1b;
  767. m_tss.ds = 0x23;
  768. m_tss.es = 0x23;
  769. m_tss.fs = 0x23;
  770. m_tss.gs = 0x23;
  771. m_tss.eip = handler_laddr.get();
  772. if (m_return_to_ring3_from_signal_trampoline.is_null()) {
  773. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  774. // FIXME: Remap as read-only after setup.
  775. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "signal_trampoline", true, true);
  776. m_return_to_ring3_from_signal_trampoline = region->laddr();
  777. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.as_ptr();
  778. *code_ptr++ = 0x61; // popa
  779. *code_ptr++ = 0x9d; // popf
  780. *code_ptr++ = 0xc3; // ret
  781. *code_ptr++ = 0x0f; // ud2
  782. *code_ptr++ = 0x0b;
  783. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  784. *code_ptr++ = 0x61; // popa
  785. *code_ptr++ = 0xb8; // mov eax, <dword>
  786. *(dword*)code_ptr = Syscall::SC_sigreturn;
  787. code_ptr += sizeof(dword);
  788. *code_ptr++ = 0xcd; // int 0x80
  789. *code_ptr++ = 0x80;
  790. *code_ptr++ = 0x0f; // ud2
  791. *code_ptr++ = 0x0b;
  792. // FIXME: For !SA_NODEFER, maybe we could do something like emitting an int 0x80 syscall here that
  793. // unmasks the signal so it can be received again? I guess then I would need one trampoline
  794. // per signal number if it's hard-coded, but it's just a few bytes per each.
  795. }
  796. if (interrupting_in_kernel)
  797. push_value_on_stack(m_return_to_ring0_from_signal_trampoline.get());
  798. else
  799. push_value_on_stack(m_return_to_ring3_from_signal_trampoline.get());
  800. // FIXME: This state is such a hack. It avoids trouble if 'current' is the process receiving a signal.
  801. set_state(Skip1SchedulerPass);
  802. #ifdef SIGNAL_DEBUG
  803. dbgprintf("signal: Okay, %s(%u) {%s} has been primed with signal handler %w:%x\n", name().characters(), pid(), to_string(state()), m_tss.cs, m_tss.eip);
  804. #endif
  805. return ShouldUnblockProcess::Yes;
  806. }
  807. void Process::sys$sigreturn()
  808. {
  809. InterruptDisabler disabler;
  810. Scheduler::prepare_to_modify_tss(*this);
  811. m_tss = m_tss_to_resume_kernel;
  812. #ifdef SIGNAL_DEBUG
  813. dbgprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  814. dbgprintf(" -> resuming execution at %w:%x\n", m_tss.cs, m_tss.eip);
  815. #endif
  816. set_state(Skip1SchedulerPass);
  817. Scheduler::yield();
  818. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  819. ASSERT_NOT_REACHED();
  820. }
  821. void Process::push_value_on_stack(dword value)
  822. {
  823. m_tss.esp -= 4;
  824. dword* stack_ptr = (dword*)m_tss.esp;
  825. *stack_ptr = value;
  826. }
  827. void Process::crash()
  828. {
  829. ASSERT_INTERRUPTS_DISABLED();
  830. ASSERT(is_ring3());
  831. ASSERT(state() != Dead);
  832. m_termination_signal = SIGSEGV;
  833. dump_regions();
  834. die();
  835. Scheduler::pick_next_and_switch_now();
  836. ASSERT_NOT_REACHED();
  837. }
  838. Process* Process::from_pid(pid_t pid)
  839. {
  840. ASSERT_INTERRUPTS_DISABLED();
  841. for (auto* process = g_processes->head(); process; process = process->next()) {
  842. if (process->pid() == pid)
  843. return process;
  844. }
  845. return nullptr;
  846. }
  847. FileDescriptor* Process::file_descriptor(int fd)
  848. {
  849. if (fd < 0)
  850. return nullptr;
  851. if ((size_t)fd < m_fds.size())
  852. return m_fds[fd].descriptor.ptr();
  853. return nullptr;
  854. }
  855. const FileDescriptor* Process::file_descriptor(int fd) const
  856. {
  857. if (fd < 0)
  858. return nullptr;
  859. if ((size_t)fd < m_fds.size())
  860. return m_fds[fd].descriptor.ptr();
  861. return nullptr;
  862. }
  863. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, size_t size)
  864. {
  865. if (!validate_write(buffer, size))
  866. return -EFAULT;
  867. auto* descriptor = file_descriptor(fd);
  868. if (!descriptor)
  869. return -EBADF;
  870. return descriptor->get_dir_entries((byte*)buffer, size);
  871. }
  872. int Process::sys$lseek(int fd, off_t offset, int whence)
  873. {
  874. auto* descriptor = file_descriptor(fd);
  875. if (!descriptor)
  876. return -EBADF;
  877. return descriptor->seek(offset, whence);
  878. }
  879. int Process::sys$ttyname_r(int fd, char* buffer, size_t size)
  880. {
  881. if (!validate_write(buffer, size))
  882. return -EFAULT;
  883. auto* descriptor = file_descriptor(fd);
  884. if (!descriptor)
  885. return -EBADF;
  886. if (!descriptor->is_tty())
  887. return -ENOTTY;
  888. auto tty_name = descriptor->tty()->tty_name();
  889. if (size < tty_name.length() + 1)
  890. return -ERANGE;
  891. strcpy(buffer, tty_name.characters());
  892. return 0;
  893. }
  894. int Process::sys$ptsname_r(int fd, char* buffer, size_t size)
  895. {
  896. if (!validate_write(buffer, size))
  897. return -EFAULT;
  898. auto* descriptor = file_descriptor(fd);
  899. if (!descriptor)
  900. return -EBADF;
  901. auto* master_pty = descriptor->master_pty();
  902. if (!master_pty)
  903. return -ENOTTY;
  904. auto pts_name = master_pty->pts_name();
  905. if (size < pts_name.length() + 1)
  906. return -ERANGE;
  907. strcpy(buffer, pts_name.characters());
  908. return 0;
  909. }
  910. ssize_t Process::sys$write(int fd, const void* data, size_t size)
  911. {
  912. if (!validate_read(data, size))
  913. return -EFAULT;
  914. #ifdef DEBUG_IO
  915. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  916. #endif
  917. auto* descriptor = file_descriptor(fd);
  918. if (!descriptor)
  919. return -EBADF;
  920. ssize_t nwritten = 0;
  921. if (descriptor->is_blocking()) {
  922. while (nwritten < (ssize_t)size) {
  923. #ifdef IO_DEBUG
  924. dbgprintf("while %u < %u\n", nwritten, size);
  925. #endif
  926. if (!descriptor->can_write(*this)) {
  927. #ifdef IO_DEBUG
  928. dbgprintf("block write on %d\n", fd);
  929. #endif
  930. m_blocked_fd = fd;
  931. block(BlockedWrite);
  932. Scheduler::yield();
  933. }
  934. ssize_t rc = descriptor->write(*this, (const byte*)data + nwritten, size - nwritten);
  935. #ifdef IO_DEBUG
  936. dbgprintf(" -> write returned %d\n", rc);
  937. #endif
  938. if (rc < 0) {
  939. // FIXME: Support returning partial nwritten with errno.
  940. ASSERT(nwritten == 0);
  941. return rc;
  942. }
  943. if (rc == 0)
  944. break;
  945. if (has_unmasked_pending_signals()) {
  946. block(BlockedSignal);
  947. Scheduler::yield();
  948. if (nwritten == 0)
  949. return -EINTR;
  950. }
  951. nwritten += rc;
  952. }
  953. } else {
  954. nwritten = descriptor->write(*this, (const byte*)data, size);
  955. }
  956. if (has_unmasked_pending_signals()) {
  957. block(BlockedSignal);
  958. Scheduler::yield();
  959. if (nwritten == 0)
  960. return -EINTR;
  961. }
  962. #ifdef DEBUG_IO
  963. dbgprintf("%s(%u) sys$write: nwritten=%u\n", name().characters(), pid(), nwritten);
  964. #endif
  965. return nwritten;
  966. }
  967. ssize_t Process::sys$read(int fd, void* outbuf, size_t nread)
  968. {
  969. if (!validate_write(outbuf, nread))
  970. return -EFAULT;
  971. #ifdef DEBUG_IO
  972. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, outbuf, nread);
  973. #endif
  974. auto* descriptor = file_descriptor(fd);
  975. if (!descriptor)
  976. return -EBADF;
  977. #ifdef DEBUG_IO
  978. dbgprintf(" > descriptor:%p, is_blocking:%u, can_read:%u\n", descriptor, descriptor->is_blocking(), descriptor->can_read(*this));
  979. dbgprintf(" > inode:K%x, device:K%x\n", descriptor->inode(), descriptor->character_device());
  980. #endif
  981. if (descriptor->is_blocking()) {
  982. if (!descriptor->can_read(*this)) {
  983. m_blocked_fd = fd;
  984. block(BlockedRead);
  985. sched_yield();
  986. if (m_was_interrupted_while_blocked)
  987. return -EINTR;
  988. }
  989. }
  990. nread = descriptor->read(*this, (byte*)outbuf, nread);
  991. #ifdef DEBUG_IO
  992. dbgprintf("%s(%u) Process::sys$read: nread=%u\n", name().characters(), pid(), nread);
  993. #endif
  994. return nread;
  995. }
  996. int Process::sys$close(int fd)
  997. {
  998. auto* descriptor = file_descriptor(fd);
  999. if (!descriptor)
  1000. return -EBADF;
  1001. int rc = descriptor->close();
  1002. m_fds[fd] = { };
  1003. return rc;
  1004. }
  1005. int Process::sys$utime(const char* pathname, const utimbuf* buf)
  1006. {
  1007. if (!validate_read_str(pathname))
  1008. return -EFAULT;
  1009. if (buf && !validate_read_typed(buf))
  1010. return -EFAULT;
  1011. String path(pathname);
  1012. int error;
  1013. auto descriptor = VFS::the().open(move(path), error, 0, 0, *cwd_inode());
  1014. if (!descriptor)
  1015. return error;
  1016. auto& inode = *descriptor->inode();
  1017. if (inode.fs().is_readonly())
  1018. return -EROFS;
  1019. time_t atime;
  1020. time_t mtime;
  1021. if (buf) {
  1022. atime = buf->actime;
  1023. mtime = buf->modtime;
  1024. } else {
  1025. auto now = RTC::now();
  1026. mtime = now;
  1027. atime = now;
  1028. }
  1029. inode.set_atime(atime);
  1030. inode.set_mtime(mtime);
  1031. return 0;
  1032. }
  1033. int Process::sys$access(const char* pathname, int mode)
  1034. {
  1035. (void) mode;
  1036. if (!validate_read_str(pathname))
  1037. return -EFAULT;
  1038. ASSERT_NOT_REACHED();
  1039. }
  1040. int Process::sys$fcntl(int fd, int cmd, dword arg)
  1041. {
  1042. (void) cmd;
  1043. (void) arg;
  1044. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  1045. auto* descriptor = file_descriptor(fd);
  1046. if (!descriptor)
  1047. return -EBADF;
  1048. // NOTE: The FD flags are not shared between FileDescriptor objects.
  1049. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1050. switch (cmd) {
  1051. case F_DUPFD: {
  1052. int arg_fd = (int)arg;
  1053. if (arg_fd < 0)
  1054. return -EINVAL;
  1055. int new_fd = -1;
  1056. for (int i = arg_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1057. if (!m_fds[i]) {
  1058. new_fd = i;
  1059. break;
  1060. }
  1061. }
  1062. if (new_fd == -1)
  1063. return -EMFILE;
  1064. m_fds[new_fd].set(descriptor);
  1065. break;
  1066. }
  1067. case F_GETFD:
  1068. return m_fds[fd].flags;
  1069. case F_SETFD:
  1070. m_fds[fd].flags = arg;
  1071. break;
  1072. case F_GETFL:
  1073. return descriptor->file_flags();
  1074. case F_SETFL:
  1075. // FIXME: Support changing O_NONBLOCK
  1076. descriptor->set_file_flags(arg);
  1077. break;
  1078. default:
  1079. ASSERT_NOT_REACHED();
  1080. }
  1081. return 0;
  1082. }
  1083. int Process::sys$fstat(int fd, stat* statbuf)
  1084. {
  1085. if (!validate_write_typed(statbuf))
  1086. return -EFAULT;
  1087. auto* descriptor = file_descriptor(fd);
  1088. if (!descriptor)
  1089. return -EBADF;
  1090. return descriptor->fstat(statbuf);
  1091. }
  1092. int Process::sys$lstat(const char* path, stat* statbuf)
  1093. {
  1094. if (!validate_write_typed(statbuf))
  1095. return -EFAULT;
  1096. int error;
  1097. auto descriptor = VFS::the().open(move(path), error, O_NOFOLLOW_NOERROR | O_DONT_OPEN_DEVICE, 0, *cwd_inode());
  1098. if (!descriptor)
  1099. return error;
  1100. return descriptor->fstat(statbuf);
  1101. }
  1102. int Process::sys$stat(const char* path, stat* statbuf)
  1103. {
  1104. if (!validate_write_typed(statbuf))
  1105. return -EFAULT;
  1106. int error;
  1107. auto descriptor = VFS::the().open(move(path), error, O_DONT_OPEN_DEVICE, 0, *cwd_inode());
  1108. if (!descriptor)
  1109. return error;
  1110. return descriptor->fstat(statbuf);
  1111. }
  1112. int Process::sys$readlink(const char* path, char* buffer, size_t size)
  1113. {
  1114. if (!validate_read_str(path))
  1115. return -EFAULT;
  1116. if (!validate_write(buffer, size))
  1117. return -EFAULT;
  1118. int error;
  1119. auto descriptor = VFS::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, 0, *cwd_inode());
  1120. if (!descriptor)
  1121. return error;
  1122. if (!descriptor->metadata().is_symlink())
  1123. return -EINVAL;
  1124. auto contents = descriptor->read_entire_file(*this);
  1125. if (!contents)
  1126. return -EIO; // FIXME: Get a more detailed error from VFS.
  1127. memcpy(buffer, contents.pointer(), min(size, contents.size()));
  1128. if (contents.size() + 1 < size)
  1129. buffer[contents.size()] = '\0';
  1130. return 0;
  1131. }
  1132. int Process::sys$chdir(const char* path)
  1133. {
  1134. if (!validate_read_str(path))
  1135. return -EFAULT;
  1136. int error;
  1137. auto descriptor = VFS::the().open(path, error, 0, 0, *cwd_inode());
  1138. if (!descriptor)
  1139. return error;
  1140. if (!descriptor->is_directory())
  1141. return -ENOTDIR;
  1142. m_cwd = descriptor->inode();
  1143. return 0;
  1144. }
  1145. int Process::sys$getcwd(char* buffer, size_t size)
  1146. {
  1147. if (!validate_write(buffer, size))
  1148. return -EFAULT;
  1149. ASSERT(cwd_inode());
  1150. auto path = VFS::the().absolute_path(*cwd_inode());
  1151. if (path.is_null())
  1152. return -EINVAL;
  1153. if (size < path.length() + 1)
  1154. return -ERANGE;
  1155. strcpy(buffer, path.characters());
  1156. return 0;
  1157. }
  1158. size_t Process::number_of_open_file_descriptors() const
  1159. {
  1160. size_t count = 0;
  1161. for (auto& descriptor : m_fds) {
  1162. if (descriptor)
  1163. ++count;
  1164. }
  1165. return count;
  1166. }
  1167. int Process::sys$open(const char* path, int options, mode_t mode)
  1168. {
  1169. #ifdef DEBUG_IO
  1170. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  1171. #endif
  1172. if (!validate_read_str(path))
  1173. return -EFAULT;
  1174. if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
  1175. return -EMFILE;
  1176. int error = -EWHYTHO;
  1177. ASSERT(cwd_inode());
  1178. auto descriptor = VFS::the().open(path, error, options, mode, *cwd_inode());
  1179. if (!descriptor)
  1180. return error;
  1181. if (options & O_DIRECTORY && !descriptor->is_directory())
  1182. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  1183. if (options & O_NONBLOCK)
  1184. descriptor->set_blocking(false);
  1185. int fd = 0;
  1186. for (; fd < (int)m_max_open_file_descriptors; ++fd) {
  1187. if (!m_fds[fd])
  1188. break;
  1189. }
  1190. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1191. m_fds[fd].set(move(descriptor), flags);
  1192. return fd;
  1193. }
  1194. int Process::alloc_fd()
  1195. {
  1196. int fd = -1;
  1197. for (int i = 0; i < (int)m_max_open_file_descriptors; ++i) {
  1198. if (!m_fds[i]) {
  1199. fd = i;
  1200. break;
  1201. }
  1202. }
  1203. return fd;
  1204. }
  1205. int Process::sys$pipe(int pipefd[2])
  1206. {
  1207. if (!validate_write_typed(pipefd))
  1208. return -EFAULT;
  1209. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1210. return -EMFILE;
  1211. auto fifo = FIFO::create();
  1212. int reader_fd = alloc_fd();
  1213. m_fds[reader_fd].set(FileDescriptor::create_pipe_reader(*fifo));
  1214. pipefd[0] = reader_fd;
  1215. int writer_fd = alloc_fd();
  1216. m_fds[writer_fd].set(FileDescriptor::create_pipe_writer(*fifo));
  1217. pipefd[1] = writer_fd;
  1218. return 0;
  1219. }
  1220. int Process::sys$killpg(int pgrp, int signum)
  1221. {
  1222. if (signum < 1 || signum >= 32)
  1223. return -EINVAL;
  1224. (void) pgrp;
  1225. ASSERT_NOT_REACHED();
  1226. }
  1227. int Process::sys$setuid(uid_t)
  1228. {
  1229. ASSERT_NOT_REACHED();
  1230. }
  1231. int Process::sys$setgid(gid_t)
  1232. {
  1233. ASSERT_NOT_REACHED();
  1234. }
  1235. unsigned Process::sys$alarm(unsigned seconds)
  1236. {
  1237. (void) seconds;
  1238. ASSERT_NOT_REACHED();
  1239. }
  1240. int Process::sys$uname(utsname* buf)
  1241. {
  1242. if (!validate_write_typed(buf))
  1243. return -EFAULT;
  1244. strcpy(buf->sysname, "Serenity");
  1245. strcpy(buf->release, "1.0-dev");
  1246. strcpy(buf->version, "FIXME");
  1247. strcpy(buf->machine, "i386");
  1248. strcpy(buf->nodename, get_hostname().characters());
  1249. return 0;
  1250. }
  1251. int Process::sys$isatty(int fd)
  1252. {
  1253. auto* descriptor = file_descriptor(fd);
  1254. if (!descriptor)
  1255. return -EBADF;
  1256. if (!descriptor->is_tty())
  1257. return -ENOTTY;
  1258. return 1;
  1259. }
  1260. int Process::sys$kill(pid_t pid, int signal)
  1261. {
  1262. if (pid == 0) {
  1263. // FIXME: Send to same-group processes.
  1264. ASSERT(pid != 0);
  1265. }
  1266. if (pid == -1) {
  1267. // FIXME: Send to all processes.
  1268. ASSERT(pid != -1);
  1269. }
  1270. ASSERT(pid != current->pid()); // FIXME: Support this scenario.
  1271. InterruptDisabler disabler;
  1272. auto* peer = Process::from_pid(pid);
  1273. if (!peer)
  1274. return -ESRCH;
  1275. peer->send_signal(signal, this);
  1276. return 0;
  1277. }
  1278. int Process::sys$usleep(useconds_t usec)
  1279. {
  1280. if (!usec)
  1281. return 0;
  1282. sleep(usec / 1000);
  1283. if (m_wakeup_time > system.uptime) {
  1284. ASSERT(m_was_interrupted_while_blocked);
  1285. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1286. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1287. }
  1288. return 0;
  1289. }
  1290. int Process::sys$sleep(unsigned seconds)
  1291. {
  1292. if (!seconds)
  1293. return 0;
  1294. sleep(seconds * TICKS_PER_SECOND);
  1295. if (m_wakeup_time > system.uptime) {
  1296. ASSERT(m_was_interrupted_while_blocked);
  1297. dword ticks_left_until_original_wakeup_time = m_wakeup_time - system.uptime;
  1298. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1299. }
  1300. return 0;
  1301. }
  1302. int Process::sys$gettimeofday(timeval* tv)
  1303. {
  1304. if (!validate_write_typed(tv))
  1305. return -EFAULT;
  1306. InterruptDisabler disabler;
  1307. auto now = RTC::now();
  1308. tv->tv_sec = now;
  1309. tv->tv_usec = PIT::ticks_since_boot() % 1000;
  1310. return 0;
  1311. }
  1312. uid_t Process::sys$getuid()
  1313. {
  1314. return m_uid;
  1315. }
  1316. gid_t Process::sys$getgid()
  1317. {
  1318. return m_gid;
  1319. }
  1320. uid_t Process::sys$geteuid()
  1321. {
  1322. return m_euid;
  1323. }
  1324. gid_t Process::sys$getegid()
  1325. {
  1326. return m_egid;
  1327. }
  1328. pid_t Process::sys$getpid()
  1329. {
  1330. return m_pid;
  1331. }
  1332. pid_t Process::sys$getppid()
  1333. {
  1334. return m_ppid;
  1335. }
  1336. mode_t Process::sys$umask(mode_t mask)
  1337. {
  1338. auto old_mask = m_umask;
  1339. m_umask = mask;
  1340. return old_mask;
  1341. }
  1342. int Process::reap(Process& process)
  1343. {
  1344. InterruptDisabler disabler;
  1345. int exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1346. if (process.ppid()) {
  1347. auto* parent = Process::from_pid(process.ppid());
  1348. if (parent) {
  1349. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1350. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1351. }
  1352. }
  1353. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), to_string(process.state()));
  1354. ASSERT(process.state() == Dead);
  1355. g_processes->remove(&process);
  1356. delete &process;
  1357. return exit_status;
  1358. }
  1359. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1360. {
  1361. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1362. // FIXME: Respect options
  1363. (void) options;
  1364. if (wstatus)
  1365. if (!validate_write_typed(wstatus))
  1366. return -EFAULT;
  1367. int dummy_wstatus;
  1368. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1369. {
  1370. InterruptDisabler disabler;
  1371. if (waitee != -1 && !Process::from_pid(waitee))
  1372. return -ECHILD;
  1373. }
  1374. if (options & WNOHANG) {
  1375. if (waitee == -1) {
  1376. pid_t reaped_pid = 0;
  1377. InterruptDisabler disabler;
  1378. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1379. if (process.state() == Dead) {
  1380. reaped_pid = process.pid();
  1381. exit_status = reap(process);
  1382. }
  1383. return true;
  1384. });
  1385. return reaped_pid;
  1386. } else {
  1387. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1388. auto* waitee_process = Process::from_pid(waitee);
  1389. if (!waitee_process)
  1390. return -ECHILD;
  1391. if (waitee_process->state() == Dead) {
  1392. exit_status = reap(*waitee_process);
  1393. return waitee;
  1394. }
  1395. return 0;
  1396. }
  1397. }
  1398. m_waitee_pid = waitee;
  1399. block(BlockedWait);
  1400. sched_yield();
  1401. if (m_was_interrupted_while_blocked)
  1402. return -EINTR;
  1403. Process* waitee_process;
  1404. {
  1405. InterruptDisabler disabler;
  1406. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1407. waitee_process = Process::from_pid(m_waitee_pid);
  1408. }
  1409. ASSERT(waitee_process);
  1410. exit_status = reap(*waitee_process);
  1411. return m_waitee_pid;
  1412. }
  1413. void Process::unblock()
  1414. {
  1415. if (current == this) {
  1416. system.nblocked--;
  1417. m_state = Process::Running;
  1418. return;
  1419. }
  1420. ASSERT(m_state != Process::Runnable && m_state != Process::Running);
  1421. system.nblocked--;
  1422. m_state = Process::Runnable;
  1423. }
  1424. void Process::block(Process::State new_state)
  1425. {
  1426. if (state() != Process::Running) {
  1427. kprintf("Process::block: %s(%u) block(%u/%s) with state=%u/%s\n", name().characters(), pid(), new_state, to_string(new_state), state(), to_string(state()));
  1428. }
  1429. ASSERT(state() == Process::Running);
  1430. system.nblocked++;
  1431. m_was_interrupted_while_blocked = false;
  1432. set_state(new_state);
  1433. }
  1434. void block(Process::State state)
  1435. {
  1436. current->block(state);
  1437. sched_yield();
  1438. }
  1439. void sleep(dword ticks)
  1440. {
  1441. ASSERT(current->state() == Process::Running);
  1442. current->set_wakeup_time(system.uptime + ticks);
  1443. current->block(Process::BlockedSleep);
  1444. sched_yield();
  1445. }
  1446. static bool is_inside_kernel_code(LinearAddress laddr)
  1447. {
  1448. // FIXME: What if we're indexing into the ksym with the highest address though?
  1449. return laddr.get() >= ksym_lowest_address && laddr.get() <= ksym_highest_address;
  1450. }
  1451. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1452. {
  1453. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1454. // This code allows access outside of the known used address ranges to get caught.
  1455. InterruptDisabler disabler;
  1456. if (is_inside_kernel_code(laddr))
  1457. return true;
  1458. if (is_kmalloc_address(laddr.as_ptr()))
  1459. return true;
  1460. return validate_read(laddr.as_ptr(), 1);
  1461. }
  1462. bool Process::validate_read(const void* address, size_t size) const
  1463. {
  1464. if (is_ring0()) {
  1465. if (is_inside_kernel_code(LinearAddress((dword)address)))
  1466. return true;
  1467. if (is_kmalloc_address(address))
  1468. return true;
  1469. }
  1470. ASSERT(size);
  1471. if (!size)
  1472. return false;
  1473. LinearAddress first_address((dword)address);
  1474. LinearAddress last_address = first_address.offset(size - 1);
  1475. if (first_address.page_base() != last_address.page_base()) {
  1476. if (!MM.validate_user_read(*this, last_address))
  1477. return false;
  1478. }
  1479. return MM.validate_user_read(*this, first_address);
  1480. }
  1481. bool Process::validate_write(void* address, size_t size) const
  1482. {
  1483. if (is_ring0()) {
  1484. if (is_kmalloc_address(address))
  1485. return true;
  1486. }
  1487. ASSERT(size);
  1488. if (!size)
  1489. return false;
  1490. LinearAddress first_address((dword)address);
  1491. LinearAddress last_address = first_address.offset(size - 1);
  1492. if (first_address.page_base() != last_address.page_base()) {
  1493. if (!MM.validate_user_write(*this, last_address))
  1494. return false;
  1495. }
  1496. return MM.validate_user_write(*this, last_address);
  1497. }
  1498. pid_t Process::sys$getsid(pid_t pid)
  1499. {
  1500. if (pid == 0)
  1501. return m_sid;
  1502. InterruptDisabler disabler;
  1503. auto* process = Process::from_pid(pid);
  1504. if (!process)
  1505. return -ESRCH;
  1506. if (m_sid != process->m_sid)
  1507. return -EPERM;
  1508. return process->m_sid;
  1509. }
  1510. pid_t Process::sys$setsid()
  1511. {
  1512. InterruptDisabler disabler;
  1513. bool found_process_with_same_pgid_as_my_pid = false;
  1514. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1515. found_process_with_same_pgid_as_my_pid = true;
  1516. return false;
  1517. });
  1518. if (found_process_with_same_pgid_as_my_pid)
  1519. return -EPERM;
  1520. m_sid = m_pid;
  1521. m_pgid = m_pid;
  1522. return m_sid;
  1523. }
  1524. pid_t Process::sys$getpgid(pid_t pid)
  1525. {
  1526. if (pid == 0)
  1527. return m_pgid;
  1528. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1529. auto* process = Process::from_pid(pid);
  1530. if (!process)
  1531. return -ESRCH;
  1532. return process->m_pgid;
  1533. }
  1534. pid_t Process::sys$getpgrp()
  1535. {
  1536. return m_pgid;
  1537. }
  1538. static pid_t get_sid_from_pgid(pid_t pgid)
  1539. {
  1540. InterruptDisabler disabler;
  1541. auto* group_leader = Process::from_pid(pgid);
  1542. if (!group_leader)
  1543. return -1;
  1544. return group_leader->sid();
  1545. }
  1546. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1547. {
  1548. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1549. pid_t pid = specified_pid ? specified_pid : m_pid;
  1550. if (specified_pgid < 0)
  1551. return -EINVAL;
  1552. auto* process = Process::from_pid(pid);
  1553. if (!process)
  1554. return -ESRCH;
  1555. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1556. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1557. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1558. if (current_sid != new_sid) {
  1559. // Can't move a process between sessions.
  1560. return -EPERM;
  1561. }
  1562. // FIXME: There are more EPERM conditions to check for here..
  1563. process->m_pgid = new_pgid;
  1564. return 0;
  1565. }
  1566. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1567. {
  1568. auto* descriptor = file_descriptor(fd);
  1569. if (!descriptor)
  1570. return -EBADF;
  1571. if (!descriptor->is_character_device())
  1572. return -ENOTTY;
  1573. return descriptor->character_device()->ioctl(*this, request, arg);
  1574. }
  1575. int Process::sys$getdtablesize()
  1576. {
  1577. return m_max_open_file_descriptors;
  1578. }
  1579. int Process::sys$dup(int old_fd)
  1580. {
  1581. auto* descriptor = file_descriptor(old_fd);
  1582. if (!descriptor)
  1583. return -EBADF;
  1584. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1585. return -EMFILE;
  1586. int new_fd = 0;
  1587. for (; new_fd < (int)m_max_open_file_descriptors; ++new_fd) {
  1588. if (!m_fds[new_fd])
  1589. break;
  1590. }
  1591. m_fds[new_fd].set(descriptor);
  1592. return new_fd;
  1593. }
  1594. int Process::sys$dup2(int old_fd, int new_fd)
  1595. {
  1596. auto* descriptor = file_descriptor(old_fd);
  1597. if (!descriptor)
  1598. return -EBADF;
  1599. if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
  1600. return -EMFILE;
  1601. m_fds[new_fd].set(descriptor);
  1602. return new_fd;
  1603. }
  1604. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1605. {
  1606. if (old_set) {
  1607. if (!validate_read_typed(old_set))
  1608. return -EFAULT;
  1609. *old_set = m_signal_mask;
  1610. }
  1611. if (set) {
  1612. if (!validate_read_typed(set))
  1613. return -EFAULT;
  1614. switch (how) {
  1615. case SIG_BLOCK:
  1616. m_signal_mask &= ~(*set);
  1617. break;
  1618. case SIG_UNBLOCK:
  1619. m_signal_mask |= *set;
  1620. break;
  1621. case SIG_SETMASK:
  1622. m_signal_mask = *set;
  1623. break;
  1624. default:
  1625. return -EINVAL;
  1626. }
  1627. }
  1628. return 0;
  1629. }
  1630. int Process::sys$sigpending(sigset_t* set)
  1631. {
  1632. if (!validate_read_typed(set))
  1633. return -EFAULT;
  1634. *set = m_pending_signals;
  1635. return 0;
  1636. }
  1637. void Process::set_default_signal_dispositions()
  1638. {
  1639. // FIXME: Set up all the right default actions. See signal(7).
  1640. memset(&m_signal_action_data, 0, sizeof(m_signal_action_data));
  1641. m_signal_action_data[SIGCHLD].handler_or_sigaction = LinearAddress((dword)SIG_IGN);
  1642. }
  1643. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1644. {
  1645. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1646. return -EINVAL;
  1647. if (!validate_read_typed(act))
  1648. return -EFAULT;
  1649. InterruptDisabler disabler; // FIXME: This should use a narrower lock.
  1650. auto& action = m_signal_action_data[signum];
  1651. if (old_act) {
  1652. if (!validate_write_typed(old_act))
  1653. return -EFAULT;
  1654. old_act->sa_flags = action.flags;
  1655. old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
  1656. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1657. }
  1658. action.restorer = LinearAddress((dword)act->sa_restorer);
  1659. action.flags = act->sa_flags;
  1660. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1661. return 0;
  1662. }
  1663. int Process::sys$getgroups(int count, gid_t* gids)
  1664. {
  1665. if (count < 0)
  1666. return -EINVAL;
  1667. ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
  1668. if (!count)
  1669. return m_gids.size();
  1670. if (count != (int)m_gids.size())
  1671. return -EINVAL;
  1672. if (!validate_write_typed(gids, m_gids.size()))
  1673. return -EFAULT;
  1674. size_t i = 0;
  1675. for (auto gid : m_gids)
  1676. gids[i++] = gid;
  1677. return 0;
  1678. }
  1679. int Process::sys$setgroups(size_t count, const gid_t* gids)
  1680. {
  1681. if (!is_root())
  1682. return -EPERM;
  1683. if (count >= MAX_PROCESS_GIDS)
  1684. return -EINVAL;
  1685. if (!validate_read(gids, count))
  1686. return -EFAULT;
  1687. m_gids.clear();
  1688. m_gids.set(m_gid);
  1689. for (size_t i = 0; i < count; ++i)
  1690. m_gids.set(gids[i]);
  1691. return 0;
  1692. }
  1693. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1694. {
  1695. if (!validate_read_str(pathname))
  1696. return -EFAULT;
  1697. size_t pathname_length = strlen(pathname);
  1698. if (pathname_length == 0)
  1699. return -EINVAL;
  1700. if (pathname_length >= 255)
  1701. return -ENAMETOOLONG;
  1702. int error;
  1703. if (!VFS::the().mkdir(String(pathname, pathname_length), mode, *cwd_inode(), error))
  1704. return error;
  1705. return 0;
  1706. }
  1707. clock_t Process::sys$times(tms* times)
  1708. {
  1709. if (!validate_write_typed(times))
  1710. return -EFAULT;
  1711. times->tms_utime = m_ticks_in_user;
  1712. times->tms_stime = m_ticks_in_kernel;
  1713. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1714. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1715. return 0;
  1716. }
  1717. struct vbe_info_structure {
  1718. char signature[4]; // must be "VESA" to indicate valid VBE support
  1719. word version; // VBE version; high byte is major version, low byte is minor version
  1720. dword oem; // segment:offset pointer to OEM
  1721. dword capabilities; // bitfield that describes card capabilities
  1722. dword video_modes; // segment:offset pointer to list of supported video modes
  1723. word video_memory; // amount of video memory in 64KB blocks
  1724. word software_rev; // software revision
  1725. dword vendor; // segment:offset to card vendor string
  1726. dword product_name; // segment:offset to card model name
  1727. dword product_rev; // segment:offset pointer to product revision
  1728. char reserved[222]; // reserved for future expansion
  1729. char oem_data[256]; // OEM BIOSes store their strings in this area
  1730. } __attribute__ ((packed));
  1731. struct vbe_mode_info_structure {
  1732. word attributes; // deprecated, only bit 7 should be of interest to you, and it indicates the mode supports a linear frame buffer.
  1733. byte window_a; // deprecated
  1734. byte window_b; // deprecated
  1735. word granularity; // deprecated; used while calculating bank numbers
  1736. word window_size;
  1737. word segment_a;
  1738. word segment_b;
  1739. dword win_func_ptr; // deprecated; used to switch banks from protected mode without returning to real mode
  1740. word pitch; // number of bytes per horizontal line
  1741. word width; // width in pixels
  1742. word height; // height in pixels
  1743. byte w_char; // unused...
  1744. byte y_char; // ...
  1745. byte planes;
  1746. byte bpp; // bits per pixel in this mode
  1747. byte banks; // deprecated; total number of banks in this mode
  1748. byte memory_model;
  1749. byte bank_size; // deprecated; size of a bank, almost always 64 KB but may be 16 KB...
  1750. byte image_pages;
  1751. byte reserved0;
  1752. byte red_mask;
  1753. byte red_position;
  1754. byte green_mask;
  1755. byte green_position;
  1756. byte blue_mask;
  1757. byte blue_position;
  1758. byte reserved_mask;
  1759. byte reserved_position;
  1760. byte direct_color_attributes;
  1761. dword framebuffer; // physical address of the linear frame buffer; write here to draw to the screen
  1762. dword off_screen_mem_off;
  1763. word off_screen_mem_size; // size of memory in the framebuffer but not being displayed on the screen
  1764. byte reserved1[206];
  1765. } __attribute__ ((packed));
  1766. DisplayInfo Process::get_display_info()
  1767. {
  1768. DisplayInfo info;
  1769. //auto* vinfo = reinterpret_cast<vbe_info_structure*>(0xc000);
  1770. auto* vmode = reinterpret_cast<vbe_mode_info_structure*>(0x2000);
  1771. dbgprintf("VESA framebuffer, %ux%u, %u bpp @ P%x\n", vmode->width, vmode->height, vmode->bpp, vmode->framebuffer);
  1772. dbgprintf("Returning display info in %s<%u>\n", name().characters(), pid());
  1773. info.width = vmode->width;
  1774. info.height = vmode->height;
  1775. info.bpp = vmode->bpp;
  1776. info.pitch = vmode->pitch;
  1777. size_t framebuffer_size = info.pitch * info.height;
  1778. if (!m_display_framebuffer_region) {
  1779. auto framebuffer_vmo = VMObject::create_framebuffer_wrapper(PhysicalAddress(vmode->framebuffer), framebuffer_size);
  1780. m_display_framebuffer_region = allocate_region_with_vmo(LinearAddress(0xe0000000), framebuffer_size, move(framebuffer_vmo), 0, "framebuffer", true, true);
  1781. }
  1782. info.framebuffer = m_display_framebuffer_region->laddr().as_ptr();
  1783. return info;
  1784. }
  1785. int Process::sys$select(const Syscall::SC_select_params* params)
  1786. {
  1787. if (!validate_read_typed(params))
  1788. return -EFAULT;
  1789. if (params->writefds && !validate_read_typed(params->writefds))
  1790. return -EFAULT;
  1791. if (params->readfds && !validate_read_typed(params->readfds))
  1792. return -EFAULT;
  1793. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1794. return -EFAULT;
  1795. if (params->timeout && !validate_read_typed(params->timeout))
  1796. return -EFAULT;
  1797. int nfds = params->nfds;
  1798. fd_set* writefds = params->writefds;
  1799. fd_set* readfds = params->readfds;
  1800. fd_set* exceptfds = params->exceptfds;
  1801. auto* timeout = params->timeout;
  1802. // FIXME: Implement exceptfds support.
  1803. ASSERT(!exceptfds);
  1804. if (timeout) {
  1805. m_select_timeout = *timeout;
  1806. m_select_has_timeout = true;
  1807. } else {
  1808. m_select_has_timeout = false;
  1809. }
  1810. if (nfds < 0)
  1811. return -EINVAL;
  1812. // FIXME: Return -EINTR if a signal is caught.
  1813. // FIXME: Return -EINVAL if timeout is invalid.
  1814. auto transfer_fds = [this, nfds] (fd_set* set, auto& vector) -> int {
  1815. if (!set)
  1816. return 0;
  1817. vector.clear_with_capacity();
  1818. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1819. for (int i = 0; i < nfds; ++i) {
  1820. if (bitmap.get(i)) {
  1821. if (!file_descriptor(i))
  1822. return -EBADF;
  1823. vector.append(i);
  1824. }
  1825. }
  1826. return 0;
  1827. };
  1828. int error = 0;
  1829. error = transfer_fds(writefds, m_select_write_fds);
  1830. if (error)
  1831. return error;
  1832. error = transfer_fds(readfds, m_select_read_fds);
  1833. if (error)
  1834. return error;
  1835. #ifdef DEBUG_IO
  1836. dbgprintf("%s<%u> selecting on (read:%u, write:%u), wakeup_req:%u, timeout=%p\n", name().characters(), pid(), m_select_read_fds.size(), m_select_write_fds.size(), m_wakeup_requested, timeout);
  1837. #endif
  1838. if (!m_wakeup_requested && (!timeout || (timeout->tv_sec || timeout->tv_usec))) {
  1839. block(BlockedSelect);
  1840. Scheduler::yield();
  1841. }
  1842. m_wakeup_requested = false;
  1843. int markedfds = 0;
  1844. if (readfds) {
  1845. memset(readfds, 0, sizeof(fd_set));
  1846. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1847. for (int fd : m_select_read_fds) {
  1848. auto* descriptor = file_descriptor(fd);
  1849. if (!descriptor)
  1850. continue;
  1851. if (descriptor->can_read(*this)) {
  1852. bitmap.set(fd, true);
  1853. ++markedfds;
  1854. }
  1855. }
  1856. }
  1857. if (writefds) {
  1858. memset(writefds, 0, sizeof(fd_set));
  1859. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1860. for (int fd : m_select_write_fds) {
  1861. auto* descriptor = file_descriptor(fd);
  1862. if (!descriptor)
  1863. continue;
  1864. if (descriptor->can_write(*this)) {
  1865. bitmap.set(fd, true);
  1866. ++markedfds;
  1867. }
  1868. }
  1869. }
  1870. return markedfds;
  1871. }
  1872. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1873. {
  1874. if (!validate_read_typed(fds))
  1875. return -EFAULT;
  1876. m_select_write_fds.clear_with_capacity();
  1877. m_select_read_fds.clear_with_capacity();
  1878. for (int i = 0; i < nfds; ++i) {
  1879. if (fds[i].events & POLLIN)
  1880. m_select_read_fds.append(fds[i].fd);
  1881. if (fds[i].events & POLLOUT)
  1882. m_select_write_fds.append(fds[i].fd);
  1883. }
  1884. if (!m_wakeup_requested && timeout < 0) {
  1885. block(BlockedSelect);
  1886. Scheduler::yield();
  1887. }
  1888. m_wakeup_requested = false;
  1889. int fds_with_revents = 0;
  1890. for (int i = 0; i < nfds; ++i) {
  1891. auto* descriptor = file_descriptor(fds[i].fd);
  1892. if (!descriptor) {
  1893. fds[i].revents = POLLNVAL;
  1894. continue;
  1895. }
  1896. fds[i].revents = 0;
  1897. if (fds[i].events & POLLIN && descriptor->can_read(*this))
  1898. fds[i].revents |= POLLIN;
  1899. if (fds[i].events & POLLOUT && descriptor->can_write(*this))
  1900. fds[i].revents |= POLLOUT;
  1901. if (fds[i].revents)
  1902. ++fds_with_revents;
  1903. }
  1904. return fds_with_revents;
  1905. }
  1906. Inode* Process::cwd_inode()
  1907. {
  1908. // FIXME: This is retarded factoring.
  1909. if (!m_cwd)
  1910. m_cwd = VFS::the().root_inode();
  1911. return m_cwd.ptr();
  1912. }
  1913. int Process::sys$unlink(const char* pathname)
  1914. {
  1915. if (!validate_read_str(pathname))
  1916. return -EFAULT;
  1917. int error;
  1918. if (!VFS::the().unlink(String(pathname), *cwd_inode(), error))
  1919. return error;
  1920. return 0;
  1921. }
  1922. int Process::sys$rmdir(const char* pathname)
  1923. {
  1924. if (!validate_read_str(pathname))
  1925. return -EFAULT;
  1926. int error;
  1927. if (!VFS::the().rmdir(String(pathname), *cwd_inode(), error))
  1928. return error;
  1929. return 0;
  1930. }
  1931. int Process::sys$read_tsc(dword* lsw, dword* msw)
  1932. {
  1933. if (!validate_write_typed(lsw))
  1934. return -EFAULT;
  1935. if (!validate_write_typed(msw))
  1936. return -EFAULT;
  1937. read_tsc(*lsw, *msw);
  1938. return 0;
  1939. }
  1940. int Process::sys$chmod(const char* pathname, mode_t mode)
  1941. {
  1942. if (!validate_read_str(pathname))
  1943. return -EFAULT;
  1944. int error;
  1945. if (!VFS::the().chmod(String(pathname), mode, *cwd_inode(), error))
  1946. return error;
  1947. return 0;
  1948. }
  1949. void Process::die()
  1950. {
  1951. set_state(Dead);
  1952. m_fds.clear();
  1953. m_tty = nullptr;
  1954. destroy_all_windows();
  1955. InterruptDisabler disabler;
  1956. if (auto* parent_process = Process::from_pid(m_ppid)) {
  1957. parent_process->send_signal(SIGCHLD, this);
  1958. }
  1959. }
  1960. size_t Process::amount_virtual() const
  1961. {
  1962. size_t amount = 0;
  1963. for (auto& region : m_regions) {
  1964. amount += region->size();
  1965. }
  1966. return amount;
  1967. }
  1968. size_t Process::amount_resident() const
  1969. {
  1970. // FIXME: This will double count if multiple regions use the same physical page.
  1971. size_t amount = 0;
  1972. for (auto& region : m_regions) {
  1973. amount += region->amount_resident();
  1974. }
  1975. return amount;
  1976. }
  1977. size_t Process::amount_shared() const
  1978. {
  1979. // FIXME: This will double count if multiple regions use the same physical page.
  1980. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage retain counts,
  1981. // and each PhysicalPage is only retained by its VMObject. This needs to be refactored
  1982. // so that every Region contributes +1 retain to each of its PhysicalPages.
  1983. size_t amount = 0;
  1984. for (auto& region : m_regions) {
  1985. amount += region->amount_shared();
  1986. }
  1987. return amount;
  1988. }