Process.cpp 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555
  1. #include <AK/Types.h>
  2. #include "Process.h"
  3. #include "kmalloc.h"
  4. #include "StdLib.h"
  5. #include "i386.h"
  6. #include <Kernel/FileSystem/FileDescriptor.h>
  7. #include <Kernel/FileSystem/VirtualFileSystem.h>
  8. #include <Kernel/Devices/NullDevice.h>
  9. #include <Kernel/ELF/ELFLoader.h>
  10. #include <Kernel/VM/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 <Kernel/FileSystem/FIFO.h>
  19. #include "KSyms.h"
  20. #include <Kernel/Net/Socket.h>
  21. #include <Kernel/TTY/MasterPTY.h>
  22. #include <Kernel/ELF/exec_elf.h>
  23. #include <AK/StringBuilder.h>
  24. #include <Kernel/SharedMemory.h>
  25. #include <Kernel/ProcessTracer.h>
  26. //#define DEBUG_IO
  27. //#define TASK_DEBUG
  28. //#define FORK_DEBUG
  29. #define SIGNAL_DEBUG
  30. //#define SHARED_BUFFER_DEBUG
  31. static pid_t next_pid;
  32. InlineLinkedList<Process>* g_processes;
  33. static String* s_hostname;
  34. static Lock* s_hostname_lock;
  35. void Process::initialize()
  36. {
  37. next_pid = 0;
  38. g_processes = new InlineLinkedList<Process>;
  39. s_hostname = new String("courage");
  40. s_hostname_lock = new Lock;
  41. }
  42. Vector<pid_t> Process::all_pids()
  43. {
  44. Vector<pid_t> pids;
  45. InterruptDisabler disabler;
  46. pids.ensure_capacity(g_processes->size_slow());
  47. for (auto* process = g_processes->head(); process; process = process->next())
  48. pids.append(process->pid());
  49. return pids;
  50. }
  51. Vector<Process*> Process::all_processes()
  52. {
  53. Vector<Process*> processes;
  54. InterruptDisabler disabler;
  55. processes.ensure_capacity(g_processes->size_slow());
  56. for (auto* process = g_processes->head(); process; process = process->next())
  57. processes.append(process);
  58. return processes;
  59. }
  60. bool Process::in_group(gid_t gid) const
  61. {
  62. return m_gids.contains(gid);
  63. }
  64. Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable, bool commit)
  65. {
  66. size = PAGE_ROUND_UP(size);
  67. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  68. if (laddr.is_null()) {
  69. laddr = m_next_region;
  70. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  71. }
  72. laddr.mask(0xfffff000);
  73. m_regions.append(adopt(*new Region(laddr, size, move(name), is_readable, is_writable)));
  74. MM.map_region(*this, *m_regions.last());
  75. if (commit)
  76. m_regions.last()->commit();
  77. return m_regions.last().ptr();
  78. }
  79. Region* Process::allocate_file_backed_region(LinearAddress laddr, size_t size, RetainPtr<Inode>&& inode, String&& name, bool is_readable, bool is_writable)
  80. {
  81. size = PAGE_ROUND_UP(size);
  82. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  83. if (laddr.is_null()) {
  84. laddr = m_next_region;
  85. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  86. }
  87. laddr.mask(0xfffff000);
  88. m_regions.append(adopt(*new Region(laddr, size, move(inode), move(name), is_readable, is_writable)));
  89. MM.map_region(*this, *m_regions.last());
  90. return m_regions.last().ptr();
  91. }
  92. Region* Process::allocate_region_with_vmo(LinearAddress laddr, size_t size, Retained<VMObject>&& vmo, size_t offset_in_vmo, String&& name, bool is_readable, bool is_writable)
  93. {
  94. size = PAGE_ROUND_UP(size);
  95. // FIXME: This needs sanity checks. What if this overlaps existing regions?
  96. if (laddr.is_null()) {
  97. laddr = m_next_region;
  98. m_next_region = m_next_region.offset(size).offset(PAGE_SIZE);
  99. }
  100. laddr.mask(0xfffff000);
  101. offset_in_vmo &= PAGE_MASK;
  102. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  103. m_regions.append(adopt(*new Region(laddr, size, move(vmo), offset_in_vmo, move(name), is_readable, is_writable)));
  104. MM.map_region(*this, *m_regions.last());
  105. return m_regions.last().ptr();
  106. }
  107. bool Process::deallocate_region(Region& region)
  108. {
  109. InterruptDisabler disabler;
  110. for (int i = 0; i < m_regions.size(); ++i) {
  111. if (m_regions[i] == &region) {
  112. MM.unmap_region(region);
  113. m_regions.remove(i);
  114. return true;
  115. }
  116. }
  117. return false;
  118. }
  119. Region* Process::region_from_range(LinearAddress laddr, size_t size)
  120. {
  121. size = PAGE_ROUND_UP(size);
  122. for (auto& region : m_regions) {
  123. if (region->laddr() == laddr && region->size() == size)
  124. return region.ptr();
  125. }
  126. return nullptr;
  127. }
  128. int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
  129. {
  130. if (!validate_read_str(name))
  131. return -EFAULT;
  132. auto* region = region_from_range(LinearAddress((dword)addr), size);
  133. if (!region)
  134. return -EINVAL;
  135. region->set_name(String(name));
  136. return 0;
  137. }
  138. void* Process::sys$mmap(const Syscall::SC_mmap_params* params)
  139. {
  140. if (!validate_read(params, sizeof(Syscall::SC_mmap_params)))
  141. return (void*)-EFAULT;
  142. void* addr = (void*)params->addr;
  143. size_t size = params->size;
  144. int prot = params->prot;
  145. int flags = params->flags;
  146. int fd = params->fd;
  147. off_t offset = params->offset;
  148. if (size == 0)
  149. return (void*)-EINVAL;
  150. if ((dword)addr & ~PAGE_MASK)
  151. return (void*)-EINVAL;
  152. if (flags & MAP_ANONYMOUS) {
  153. auto* region = allocate_region(LinearAddress((dword)addr), size, "mmap", prot & PROT_READ, prot & PROT_WRITE, false);
  154. if (!region)
  155. return (void*)-ENOMEM;
  156. if (flags & MAP_SHARED)
  157. region->set_shared(true);
  158. return region->laddr().as_ptr();
  159. }
  160. if (offset & ~PAGE_MASK)
  161. return (void*)-EINVAL;
  162. auto* descriptor = file_descriptor(fd);
  163. if (!descriptor)
  164. return (void*)-EBADF;
  165. auto region_or_error = descriptor->mmap(*this, LinearAddress((dword)addr), offset, size, prot);
  166. if (region_or_error.is_error())
  167. return (void*)(int)region_or_error.error();
  168. auto region = region_or_error.value();
  169. if (flags & MAP_SHARED)
  170. region->set_shared(true);
  171. return region->laddr().as_ptr();
  172. }
  173. int Process::sys$munmap(void* addr, size_t size)
  174. {
  175. auto* region = region_from_range(LinearAddress((dword)addr), size);
  176. if (!region)
  177. return -EINVAL;
  178. if (!deallocate_region(*region))
  179. return -EINVAL;
  180. return 0;
  181. }
  182. int Process::sys$gethostname(char* buffer, ssize_t size)
  183. {
  184. if (size < 0)
  185. return -EINVAL;
  186. if (!validate_write(buffer, size))
  187. return -EFAULT;
  188. LOCKER(*s_hostname_lock);
  189. if (size < (s_hostname->length() + 1))
  190. return -ENAMETOOLONG;
  191. strcpy(buffer, s_hostname->characters());
  192. return 0;
  193. }
  194. Process* Process::fork(RegisterDump& regs)
  195. {
  196. 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);
  197. if (!child)
  198. return nullptr;
  199. #ifdef FORK_DEBUG
  200. dbgprintf("fork: child=%p\n", child);
  201. #endif
  202. for (auto& region : m_regions) {
  203. #ifdef FORK_DEBUG
  204. dbgprintf("fork: cloning Region{%p} \"%s\" L%x\n", region.ptr(), region->name().characters(), region->laddr().get());
  205. #endif
  206. auto cloned_region = region->clone();
  207. child->m_regions.append(move(cloned_region));
  208. MM.map_region(*child, *child->m_regions.last());
  209. }
  210. for (auto gid : m_gids)
  211. child->m_gids.set(gid);
  212. auto& child_tss = child->main_thread().m_tss;
  213. child_tss.eax = 0; // fork() returns 0 in the child :^)
  214. child_tss.ebx = regs.ebx;
  215. child_tss.ecx = regs.ecx;
  216. child_tss.edx = regs.edx;
  217. child_tss.ebp = regs.ebp;
  218. child_tss.esp = regs.esp_if_crossRing;
  219. child_tss.esi = regs.esi;
  220. child_tss.edi = regs.edi;
  221. child_tss.eflags = regs.eflags;
  222. child_tss.eip = regs.eip;
  223. child_tss.cs = regs.cs;
  224. child_tss.ds = regs.ds;
  225. child_tss.es = regs.es;
  226. child_tss.fs = regs.fs;
  227. child_tss.gs = regs.gs;
  228. child_tss.ss = regs.ss_if_crossRing;
  229. #ifdef FORK_DEBUG
  230. dbgprintf("fork: child will begin executing at %w:%x with stack %w:%x, kstack %w:%x\n", child_tss.cs, child_tss.eip, child_tss.ss, child_tss.esp, child_tss.ss0, child_tss.esp0);
  231. #endif
  232. {
  233. InterruptDisabler disabler;
  234. g_processes->prepend(child);
  235. }
  236. #ifdef TASK_DEBUG
  237. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child_tss.eip);
  238. #endif
  239. child->main_thread().set_state(Thread::State::Skip1SchedulerPass);
  240. return child;
  241. }
  242. pid_t Process::sys$fork(RegisterDump& regs)
  243. {
  244. auto* child = fork(regs);
  245. ASSERT(child);
  246. return child->pid();
  247. }
  248. int Process::do_exec(String path, Vector<String> arguments, Vector<String> environment)
  249. {
  250. ASSERT(is_ring3());
  251. dbgprintf("%s(%d) do_exec(%s): thread_count() = %d\n", m_name.characters(), m_pid, path.characters(), thread_count());
  252. // FIXME(Thread): Kill any threads the moment we commit to the exec().
  253. if (thread_count() != 1) {
  254. dbgprintf("Gonna die because I have many threads! These are the threads:\n");
  255. for_each_thread([] (Thread& thread) {
  256. dbgprintf("Thread{%p}: TID=%d, PID=%d\n", &thread, thread.tid(), thread.pid());
  257. return IterationDecision::Continue;
  258. });
  259. ASSERT(thread_count() == 1);
  260. ASSERT_NOT_REACHED();
  261. }
  262. auto parts = path.split('/');
  263. if (parts.is_empty())
  264. return -ENOENT;
  265. auto result = VFS::the().open(path.view(), 0, 0, cwd_inode());
  266. if (result.is_error())
  267. return result.error();
  268. auto descriptor = result.value();
  269. if (!descriptor->metadata().may_execute(m_euid, m_gids))
  270. return -EACCES;
  271. if (!descriptor->metadata().size) {
  272. return -ENOTIMPL;
  273. }
  274. dword entry_eip = 0;
  275. // FIXME: Is there a race here?
  276. auto old_page_directory = move(m_page_directory);
  277. m_page_directory = PageDirectory::create();
  278. #ifdef MM_DEBUG
  279. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  280. #endif
  281. ProcessPagingScope paging_scope(*this);
  282. auto vmo = VMObject::create_file_backed(descriptor->inode());
  283. #if 0
  284. // FIXME: I would like to do this, but it would instantiate all the damn inodes.
  285. vmo->set_name(descriptor->absolute_path());
  286. #else
  287. vmo->set_name("ELF image");
  288. #endif
  289. RetainPtr<Region> region = allocate_region_with_vmo(LinearAddress(), descriptor->metadata().size, vmo.copy_ref(), 0, "executable", true, false);
  290. if (this != &current->process()) {
  291. // FIXME: Don't force-load the entire executable at once, let the on-demand pager take care of it.
  292. bool success = region->page_in();
  293. ASSERT(success);
  294. }
  295. {
  296. // Okay, here comes the sleight of hand, pay close attention..
  297. auto old_regions = move(m_regions);
  298. m_regions.append(*region);
  299. ELFLoader loader(region->laddr().as_ptr());
  300. 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) {
  301. ASSERT(size);
  302. ASSERT(alignment == PAGE_SIZE);
  303. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  304. (void) allocate_region_with_vmo(laddr, size, vmo.copy_ref(), offset_in_image, String(name), is_readable, is_writable);
  305. return laddr.as_ptr();
  306. };
  307. loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
  308. ASSERT(size);
  309. ASSERT(alignment == PAGE_SIZE);
  310. size += laddr.get() & 0xfff;
  311. laddr.mask(0xffff000);
  312. size = ceil_div(size, PAGE_SIZE) * PAGE_SIZE;
  313. (void) allocate_region(laddr, size, String(name), is_readable, is_writable);
  314. return laddr.as_ptr();
  315. };
  316. bool success = loader.load();
  317. if (!success || !loader.entry().get()) {
  318. m_page_directory = move(old_page_directory);
  319. // FIXME: RAII this somehow instead.
  320. ASSERT(&current->process() == this);
  321. MM.enter_process_paging_scope(*this);
  322. m_regions = move(old_regions);
  323. kprintf("do_exec: Failure loading %s\n", path.characters());
  324. return -ENOEXEC;
  325. }
  326. entry_eip = loader.entry().get();
  327. }
  328. kfree(current->m_kernel_stack_for_signal_handler);
  329. current->m_kernel_stack_for_signal_handler = nullptr;
  330. current->m_signal_stack_user_region = nullptr;
  331. current->set_default_signal_dispositions();
  332. current->m_signal_mask = 0;
  333. current->m_pending_signals = 0;
  334. for (int i = 0; i < m_fds.size(); ++i) {
  335. auto& daf = m_fds[i];
  336. if (daf.descriptor && daf.flags & FD_CLOEXEC) {
  337. daf.descriptor->close();
  338. daf = { };
  339. }
  340. }
  341. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  342. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  343. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  344. if (&current->process() == this)
  345. cli();
  346. Scheduler::prepare_to_modify_tss(main_thread());
  347. m_name = parts.take_last();
  348. // ss0 sp!!!!!!!!!
  349. dword old_esp0 = main_thread().m_tss.esp0;
  350. memset(&main_thread().m_tss, 0, sizeof(main_thread().m_tss));
  351. main_thread().m_tss.eflags = 0x0202;
  352. main_thread().m_tss.eip = entry_eip;
  353. main_thread().m_tss.cs = 0x1b;
  354. main_thread().m_tss.ds = 0x23;
  355. main_thread().m_tss.es = 0x23;
  356. main_thread().m_tss.fs = 0x23;
  357. main_thread().m_tss.gs = 0x23;
  358. main_thread().m_tss.ss = 0x23;
  359. main_thread().m_tss.cr3 = page_directory().cr3();
  360. main_thread().make_userspace_stack_for_main_thread(move(arguments), move(environment));
  361. main_thread().m_tss.ss0 = 0x10;
  362. main_thread().m_tss.esp0 = old_esp0;
  363. main_thread().m_tss.ss2 = m_pid;
  364. m_executable = descriptor->inode();
  365. if (descriptor->metadata().is_setuid())
  366. m_euid = descriptor->metadata().uid;
  367. if (descriptor->metadata().is_setgid())
  368. m_egid = descriptor->metadata().gid;
  369. #ifdef TASK_DEBUG
  370. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), main_thread().tss().eip);
  371. #endif
  372. main_thread().set_state(Thread::State::Skip1SchedulerPass);
  373. return 0;
  374. }
  375. int Process::exec(String path, Vector<String> arguments, Vector<String> environment)
  376. {
  377. // The bulk of exec() is done by do_exec(), which ensures that all locals
  378. // are cleaned up by the time we yield-teleport below.
  379. int rc = do_exec(move(path), move(arguments), move(environment));
  380. if (rc < 0)
  381. return rc;
  382. if (&current->process() == this) {
  383. Scheduler::yield();
  384. ASSERT_NOT_REACHED();
  385. }
  386. return 0;
  387. }
  388. int Process::sys$execve(const char* filename, const char** argv, const char** envp)
  389. {
  390. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  391. // On success, the kernel stack will be lost.
  392. if (!validate_read_str(filename))
  393. return -EFAULT;
  394. if (!*filename)
  395. return -ENOENT;
  396. if (argv) {
  397. if (!validate_read_typed(argv))
  398. return -EFAULT;
  399. for (size_t i = 0; argv[i]; ++i) {
  400. if (!validate_read_str(argv[i]))
  401. return -EFAULT;
  402. }
  403. }
  404. if (envp) {
  405. if (!validate_read_typed(envp))
  406. return -EFAULT;
  407. for (size_t i = 0; envp[i]; ++i) {
  408. if (!validate_read_str(envp[i]))
  409. return -EFAULT;
  410. }
  411. }
  412. String path(filename);
  413. Vector<String> arguments;
  414. Vector<String> environment;
  415. {
  416. auto parts = path.split('/');
  417. if (argv) {
  418. for (size_t i = 0; argv[i]; ++i) {
  419. arguments.append(argv[i]);
  420. }
  421. } else {
  422. arguments.append(parts.last());
  423. }
  424. if (envp) {
  425. for (size_t i = 0; envp[i]; ++i)
  426. environment.append(envp[i]);
  427. }
  428. }
  429. int rc = exec(move(path), move(arguments), move(environment));
  430. ASSERT(rc < 0); // We should never continue after a successful exec!
  431. return rc;
  432. }
  433. 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)
  434. {
  435. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  436. auto parts = path.split('/');
  437. if (arguments.is_empty()) {
  438. arguments.append(parts.last());
  439. }
  440. RetainPtr<Inode> cwd;
  441. {
  442. InterruptDisabler disabler;
  443. if (auto* parent = Process::from_pid(parent_pid))
  444. cwd = parent->m_cwd.copy_ref();
  445. }
  446. if (!cwd)
  447. cwd = VFS::the().root_inode();
  448. auto* process = new Process(parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  449. error = process->exec(path, move(arguments), move(environment));
  450. if (error != 0) {
  451. delete process;
  452. return nullptr;
  453. }
  454. {
  455. InterruptDisabler disabler;
  456. g_processes->prepend(process);
  457. }
  458. #ifdef TASK_DEBUG
  459. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->main_thread().tss().eip);
  460. #endif
  461. error = 0;
  462. return process;
  463. }
  464. Process* Process::create_kernel_process(String&& name, void (*e)())
  465. {
  466. auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  467. process->main_thread().tss().eip = (dword)e;
  468. if (process->pid() != 0) {
  469. InterruptDisabler disabler;
  470. g_processes->prepend(process);
  471. #ifdef TASK_DEBUG
  472. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->main_thread().tss().eip);
  473. #endif
  474. }
  475. process->main_thread().set_state(Thread::State::Runnable);
  476. return process;
  477. }
  478. 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)
  479. : m_name(move(name))
  480. , m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
  481. , m_uid(uid)
  482. , m_gid(gid)
  483. , m_euid(uid)
  484. , m_egid(gid)
  485. , m_ring(ring)
  486. , m_cwd(move(cwd))
  487. , m_executable(move(executable))
  488. , m_tty(tty)
  489. , m_ppid(ppid)
  490. {
  491. dbgprintf("Process: New process PID=%u with name=%s\n", m_pid, m_name.characters());
  492. m_page_directory = PageDirectory::create();
  493. #ifdef MM_DEBUG
  494. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  495. #endif
  496. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the main thread in the new process.
  497. if (fork_parent)
  498. m_main_thread = current->clone(*this);
  499. else
  500. m_main_thread = new Thread(*this);
  501. m_gids.set(m_gid);
  502. if (fork_parent) {
  503. m_sid = fork_parent->m_sid;
  504. m_pgid = fork_parent->m_pgid;
  505. } else {
  506. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  507. InterruptDisabler disabler;
  508. if (auto* parent = Process::from_pid(m_ppid)) {
  509. m_sid = parent->m_sid;
  510. m_pgid = parent->m_pgid;
  511. }
  512. }
  513. if (fork_parent) {
  514. m_fds.resize(fork_parent->m_fds.size());
  515. for (int i = 0; i < fork_parent->m_fds.size(); ++i) {
  516. if (!fork_parent->m_fds[i].descriptor)
  517. continue;
  518. #ifdef FORK_DEBUG
  519. 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());
  520. #endif
  521. m_fds[i].descriptor = fork_parent->m_fds[i].descriptor->clone();
  522. m_fds[i].flags = fork_parent->m_fds[i].flags;
  523. }
  524. } else {
  525. m_fds.resize(m_max_open_file_descriptors);
  526. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  527. m_fds[0].set(*device_to_use_as_tty.open(O_RDONLY).value());
  528. m_fds[1].set(*device_to_use_as_tty.open(O_WRONLY).value());
  529. m_fds[2].set(*device_to_use_as_tty.open(O_WRONLY).value());
  530. }
  531. if (fork_parent)
  532. m_next_region = fork_parent->m_next_region;
  533. else
  534. m_next_region = LinearAddress(0x10000000);
  535. if (fork_parent) {
  536. m_sid = fork_parent->m_sid;
  537. m_pgid = fork_parent->m_pgid;
  538. m_umask = fork_parent->m_umask;
  539. }
  540. }
  541. Process::~Process()
  542. {
  543. dbgprintf("~Process{%p} name=%s pid=%d, m_fds=%d\n", this, m_name.characters(), pid(), m_fds.size());
  544. delete m_main_thread;
  545. m_main_thread = nullptr;
  546. Vector<Thread*, 16> my_threads;
  547. for_each_thread([&my_threads] (auto& thread) {
  548. my_threads.append(&thread);
  549. return IterationDecision::Continue;
  550. });
  551. for (auto* thread : my_threads)
  552. delete thread;
  553. }
  554. void Process::dump_regions()
  555. {
  556. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  557. kprintf("BEGIN END SIZE NAME\n");
  558. for (auto& region : m_regions) {
  559. kprintf("%x -- %x %x %s\n",
  560. region->laddr().get(),
  561. region->laddr().offset(region->size() - 1).get(),
  562. region->size(),
  563. region->name().characters());
  564. }
  565. }
  566. void Process::sys$exit(int status)
  567. {
  568. cli();
  569. #ifdef TASK_DEBUG
  570. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  571. #endif
  572. m_termination_status = status;
  573. m_termination_signal = 0;
  574. die();
  575. ASSERT_NOT_REACHED();
  576. }
  577. void Process::create_signal_trampolines_if_needed()
  578. {
  579. if (!m_return_to_ring3_from_signal_trampoline.is_null())
  580. return;
  581. // FIXME: This should be a global trampoline shared by all processes, not one created per process!
  582. // FIXME: Remap as read-only after setup.
  583. auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "Signal trampolines", true, true);
  584. m_return_to_ring3_from_signal_trampoline = region->laddr();
  585. byte* code_ptr = m_return_to_ring3_from_signal_trampoline.as_ptr();
  586. *code_ptr++ = 0x58; // pop eax (Argument to signal handler (ignored here))
  587. *code_ptr++ = 0x5a; // pop edx (Original signal mask to restore)
  588. *code_ptr++ = 0xb8; // mov eax, <dword>
  589. *(dword*)code_ptr = Syscall::SC_restore_signal_mask;
  590. code_ptr += sizeof(dword);
  591. *code_ptr++ = 0xcd; // int 0x82
  592. *code_ptr++ = 0x82;
  593. *code_ptr++ = 0x83; // add esp, (stack alignment padding)
  594. *code_ptr++ = 0xc4;
  595. *code_ptr++ = sizeof(dword) * 3;
  596. *code_ptr++ = 0x61; // popa
  597. *code_ptr++ = 0x9d; // popf
  598. *code_ptr++ = 0xc3; // ret
  599. *code_ptr++ = 0x0f; // ud2
  600. *code_ptr++ = 0x0b;
  601. m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
  602. *code_ptr++ = 0x58; // pop eax (Argument to signal handler (ignored here))
  603. *code_ptr++ = 0x5a; // pop edx (Original signal mask to restore)
  604. *code_ptr++ = 0xb8; // mov eax, <dword>
  605. *(dword*)code_ptr = Syscall::SC_restore_signal_mask;
  606. code_ptr += sizeof(dword);
  607. *code_ptr++ = 0xcd; // int 0x82
  608. // NOTE: Stack alignment padding doesn't matter when returning to ring0.
  609. // Nothing matters really, as we're returning by replacing the entire TSS.
  610. *code_ptr++ = 0x82;
  611. *code_ptr++ = 0xb8; // mov eax, <dword>
  612. *(dword*)code_ptr = Syscall::SC_sigreturn;
  613. code_ptr += sizeof(dword);
  614. *code_ptr++ = 0xcd; // int 0x82
  615. *code_ptr++ = 0x82;
  616. *code_ptr++ = 0x0f; // ud2
  617. *code_ptr++ = 0x0b;
  618. }
  619. int Process::sys$restore_signal_mask(dword mask)
  620. {
  621. current->m_signal_mask = mask;
  622. return 0;
  623. }
  624. void Process::sys$sigreturn()
  625. {
  626. InterruptDisabler disabler;
  627. Scheduler::prepare_to_modify_tss(*current);
  628. current->m_tss = *current->m_tss_to_resume_kernel;
  629. current->m_tss_to_resume_kernel.clear();
  630. #ifdef SIGNAL_DEBUG
  631. kprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
  632. auto& tss = current->tss();
  633. kprintf(" -> resuming execution at %w:%x stack %w:%x flags %x cr3 %x\n", tss.cs, tss.eip, tss.ss, tss.esp, tss.eflags, tss.cr3);
  634. #endif
  635. current->set_state(Thread::State::Skip1SchedulerPass);
  636. Scheduler::yield();
  637. kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
  638. ASSERT_NOT_REACHED();
  639. }
  640. void Process::crash()
  641. {
  642. ASSERT_INTERRUPTS_DISABLED();
  643. ASSERT(!is_dead());
  644. m_termination_signal = SIGSEGV;
  645. dump_regions();
  646. ASSERT(is_ring3());
  647. die();
  648. ASSERT_NOT_REACHED();
  649. }
  650. Process* Process::from_pid(pid_t pid)
  651. {
  652. ASSERT_INTERRUPTS_DISABLED();
  653. for (auto* process = g_processes->head(); process; process = process->next()) {
  654. if (process->pid() == pid)
  655. return process;
  656. }
  657. return nullptr;
  658. }
  659. FileDescriptor* Process::file_descriptor(int fd)
  660. {
  661. if (fd < 0)
  662. return nullptr;
  663. if (fd < m_fds.size())
  664. return m_fds[fd].descriptor.ptr();
  665. return nullptr;
  666. }
  667. const FileDescriptor* Process::file_descriptor(int fd) const
  668. {
  669. if (fd < 0)
  670. return nullptr;
  671. if (fd < m_fds.size())
  672. return m_fds[fd].descriptor.ptr();
  673. return nullptr;
  674. }
  675. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, ssize_t size)
  676. {
  677. if (size < 0)
  678. return -EINVAL;
  679. if (!validate_write(buffer, size))
  680. return -EFAULT;
  681. auto* descriptor = file_descriptor(fd);
  682. if (!descriptor)
  683. return -EBADF;
  684. return descriptor->get_dir_entries((byte*)buffer, size);
  685. }
  686. int Process::sys$lseek(int fd, off_t offset, int whence)
  687. {
  688. auto* descriptor = file_descriptor(fd);
  689. if (!descriptor)
  690. return -EBADF;
  691. return descriptor->seek(offset, whence);
  692. }
  693. int Process::sys$ttyname_r(int fd, char* buffer, ssize_t size)
  694. {
  695. if (size < 0)
  696. return -EINVAL;
  697. if (!validate_write(buffer, size))
  698. return -EFAULT;
  699. auto* descriptor = file_descriptor(fd);
  700. if (!descriptor)
  701. return -EBADF;
  702. if (!descriptor->is_tty())
  703. return -ENOTTY;
  704. auto tty_name = descriptor->tty()->tty_name();
  705. if (size < tty_name.length() + 1)
  706. return -ERANGE;
  707. strcpy(buffer, tty_name.characters());
  708. return 0;
  709. }
  710. int Process::sys$ptsname_r(int fd, char* buffer, ssize_t size)
  711. {
  712. if (size < 0)
  713. return -EINVAL;
  714. if (!validate_write(buffer, size))
  715. return -EFAULT;
  716. auto* descriptor = file_descriptor(fd);
  717. if (!descriptor)
  718. return -EBADF;
  719. auto* master_pty = descriptor->master_pty();
  720. if (!master_pty)
  721. return -ENOTTY;
  722. auto pts_name = master_pty->pts_name();
  723. if (size < pts_name.length() + 1)
  724. return -ERANGE;
  725. strcpy(buffer, pts_name.characters());
  726. return 0;
  727. }
  728. ssize_t Process::sys$write(int fd, const byte* data, ssize_t size)
  729. {
  730. if (size < 0)
  731. return -EINVAL;
  732. if (size == 0)
  733. return 0;
  734. if (!validate_read(data, size))
  735. return -EFAULT;
  736. #ifdef DEBUG_IO
  737. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  738. #endif
  739. auto* descriptor = file_descriptor(fd);
  740. if (!descriptor)
  741. return -EBADF;
  742. ssize_t nwritten = 0;
  743. if (descriptor->is_blocking()) {
  744. while (nwritten < (ssize_t)size) {
  745. #ifdef IO_DEBUG
  746. dbgprintf("while %u < %u\n", nwritten, size);
  747. #endif
  748. if (!descriptor->can_write()) {
  749. #ifdef IO_DEBUG
  750. dbgprintf("block write on %d\n", fd);
  751. #endif
  752. current->block(Thread::State::BlockedWrite, *descriptor);
  753. }
  754. ssize_t rc = descriptor->write((const byte*)data + nwritten, size - nwritten);
  755. #ifdef IO_DEBUG
  756. dbgprintf(" -> write returned %d\n", rc);
  757. #endif
  758. if (rc < 0) {
  759. // FIXME: Support returning partial nwritten with errno.
  760. ASSERT(nwritten == 0);
  761. return rc;
  762. }
  763. if (rc == 0)
  764. break;
  765. if (current->has_unmasked_pending_signals()) {
  766. current->block(Thread::State::BlockedSignal);
  767. if (nwritten == 0)
  768. return -EINTR;
  769. }
  770. nwritten += rc;
  771. }
  772. } else {
  773. nwritten = descriptor->write((const byte*)data, size);
  774. }
  775. if (current->has_unmasked_pending_signals()) {
  776. current->block(Thread::State::BlockedSignal);
  777. if (nwritten == 0)
  778. return -EINTR;
  779. }
  780. return nwritten;
  781. }
  782. ssize_t Process::sys$read(int fd, byte* buffer, ssize_t size)
  783. {
  784. if (size < 0)
  785. return -EINVAL;
  786. if (size == 0)
  787. return 0;
  788. if (!validate_write(buffer, size))
  789. return -EFAULT;
  790. #ifdef DEBUG_IO
  791. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, buffer, size);
  792. #endif
  793. auto* descriptor = file_descriptor(fd);
  794. if (!descriptor)
  795. return -EBADF;
  796. if (descriptor->is_blocking()) {
  797. if (!descriptor->can_read()) {
  798. current->block(Thread::State::BlockedRead, *descriptor);
  799. if (current->m_was_interrupted_while_blocked)
  800. return -EINTR;
  801. }
  802. }
  803. return descriptor->read(buffer, size);
  804. }
  805. int Process::sys$close(int fd)
  806. {
  807. auto* descriptor = file_descriptor(fd);
  808. if (!descriptor)
  809. return -EBADF;
  810. int rc = descriptor->close();
  811. m_fds[fd] = { };
  812. return rc;
  813. }
  814. int Process::sys$utime(const char* pathname, const utimbuf* buf)
  815. {
  816. if (!validate_read_str(pathname))
  817. return -EFAULT;
  818. if (buf && !validate_read_typed(buf))
  819. return -EFAULT;
  820. time_t atime;
  821. time_t mtime;
  822. if (buf) {
  823. atime = buf->actime;
  824. mtime = buf->modtime;
  825. } else {
  826. struct timeval now;
  827. kgettimeofday(now);
  828. mtime = now.tv_sec;
  829. atime = now.tv_sec;
  830. }
  831. return VFS::the().utime(StringView(pathname), cwd_inode(), atime, mtime);
  832. }
  833. int Process::sys$access(const char* pathname, int mode)
  834. {
  835. if (!validate_read_str(pathname))
  836. return -EFAULT;
  837. return VFS::the().access(StringView(pathname), mode, cwd_inode());
  838. }
  839. int Process::sys$fcntl(int fd, int cmd, dword arg)
  840. {
  841. (void) cmd;
  842. (void) arg;
  843. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  844. auto* descriptor = file_descriptor(fd);
  845. if (!descriptor)
  846. return -EBADF;
  847. // NOTE: The FD flags are not shared between FileDescriptor objects.
  848. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  849. switch (cmd) {
  850. case F_DUPFD: {
  851. int arg_fd = (int)arg;
  852. if (arg_fd < 0)
  853. return -EINVAL;
  854. int new_fd = alloc_fd(arg_fd);
  855. if (new_fd < 0)
  856. return new_fd;
  857. m_fds[new_fd].set(*descriptor);
  858. break;
  859. }
  860. case F_GETFD:
  861. return m_fds[fd].flags;
  862. case F_SETFD:
  863. m_fds[fd].flags = arg;
  864. break;
  865. case F_GETFL:
  866. return descriptor->file_flags();
  867. case F_SETFL:
  868. // FIXME: Support changing O_NONBLOCK
  869. descriptor->set_file_flags(arg);
  870. break;
  871. default:
  872. ASSERT_NOT_REACHED();
  873. }
  874. return 0;
  875. }
  876. int Process::sys$fstat(int fd, stat* statbuf)
  877. {
  878. if (!validate_write_typed(statbuf))
  879. return -EFAULT;
  880. auto* descriptor = file_descriptor(fd);
  881. if (!descriptor)
  882. return -EBADF;
  883. return descriptor->fstat(*statbuf);
  884. }
  885. int Process::sys$lstat(const char* path, stat* statbuf)
  886. {
  887. if (!validate_write_typed(statbuf))
  888. return -EFAULT;
  889. return VFS::the().stat(StringView(path), O_NOFOLLOW_NOERROR, cwd_inode(), *statbuf);
  890. }
  891. int Process::sys$stat(const char* path, stat* statbuf)
  892. {
  893. if (!validate_write_typed(statbuf))
  894. return -EFAULT;
  895. return VFS::the().stat(StringView(path), O_NOFOLLOW_NOERROR, cwd_inode(), *statbuf);
  896. }
  897. int Process::sys$readlink(const char* path, char* buffer, ssize_t size)
  898. {
  899. if (size < 0)
  900. return -EINVAL;
  901. if (!validate_read_str(path))
  902. return -EFAULT;
  903. if (!validate_write(buffer, size))
  904. return -EFAULT;
  905. auto result = VFS::the().open(path, O_RDONLY | O_NOFOLLOW_NOERROR, 0, cwd_inode());
  906. if (result.is_error())
  907. return result.error();
  908. auto descriptor = result.value();
  909. if (!descriptor->metadata().is_symlink())
  910. return -EINVAL;
  911. auto contents = descriptor->read_entire_file();
  912. if (!contents)
  913. return -EIO; // FIXME: Get a more detailed error from VFS.
  914. memcpy(buffer, contents.pointer(), min(size, (ssize_t)contents.size()));
  915. if (contents.size() + 1 < size)
  916. buffer[contents.size()] = '\0';
  917. return 0;
  918. }
  919. int Process::sys$chdir(const char* path)
  920. {
  921. if (!validate_read_str(path))
  922. return -EFAULT;
  923. auto directory_or_error = VFS::the().open_directory(StringView(path), cwd_inode());
  924. if (directory_or_error.is_error())
  925. return directory_or_error.error();
  926. m_cwd = *directory_or_error.value();
  927. return 0;
  928. }
  929. int Process::sys$getcwd(char* buffer, ssize_t size)
  930. {
  931. if (size < 0)
  932. return -EINVAL;
  933. if (!validate_write(buffer, size))
  934. return -EFAULT;
  935. auto path_or_error = VFS::the().absolute_path(cwd_inode());
  936. if (path_or_error.is_error())
  937. return path_or_error.error();
  938. auto path = path_or_error.value();
  939. if (size < path.length() + 1)
  940. return -ERANGE;
  941. strcpy(buffer, path.characters());
  942. return 0;
  943. }
  944. int Process::number_of_open_file_descriptors() const
  945. {
  946. int count = 0;
  947. for (auto& descriptor : m_fds) {
  948. if (descriptor)
  949. ++count;
  950. }
  951. return count;
  952. }
  953. int Process::sys$open(const char* path, int options, mode_t mode)
  954. {
  955. #ifdef DEBUG_IO
  956. dbgprintf("%s(%u) sys$open(\"%s\")\n", name().characters(), pid(), path);
  957. #endif
  958. if (!validate_read_str(path))
  959. return -EFAULT;
  960. int fd = alloc_fd();
  961. if (fd < 0)
  962. return fd;
  963. auto result = VFS::the().open(path, options, mode & ~umask(), cwd_inode());
  964. if (result.is_error())
  965. return result.error();
  966. auto descriptor = result.value();
  967. if (options & O_DIRECTORY && !descriptor->is_directory())
  968. return -ENOTDIR; // FIXME: This should be handled by VFS::open.
  969. if (options & O_NONBLOCK)
  970. descriptor->set_blocking(false);
  971. dword flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  972. m_fds[fd].set(move(descriptor), flags);
  973. return fd;
  974. }
  975. int Process::alloc_fd(int first_candidate_fd)
  976. {
  977. int fd = -EMFILE;
  978. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  979. if (!m_fds[i]) {
  980. fd = i;
  981. break;
  982. }
  983. }
  984. return fd;
  985. }
  986. int Process::sys$pipe(int pipefd[2])
  987. {
  988. if (!validate_write_typed(pipefd))
  989. return -EFAULT;
  990. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  991. return -EMFILE;
  992. auto fifo = FIFO::create(m_uid);
  993. int reader_fd = alloc_fd();
  994. m_fds[reader_fd].set(fifo->open_direction(FIFO::Reader));
  995. pipefd[0] = reader_fd;
  996. int writer_fd = alloc_fd();
  997. m_fds[writer_fd].set(fifo->open_direction(FIFO::Writer));
  998. pipefd[1] = writer_fd;
  999. return 0;
  1000. }
  1001. int Process::sys$killpg(int pgrp, int signum)
  1002. {
  1003. if (signum < 1 || signum >= 32)
  1004. return -EINVAL;
  1005. (void) pgrp;
  1006. ASSERT_NOT_REACHED();
  1007. }
  1008. int Process::sys$setuid(uid_t uid)
  1009. {
  1010. if (uid != m_uid && !is_superuser())
  1011. return -EPERM;
  1012. m_uid = uid;
  1013. m_euid = uid;
  1014. return 0;
  1015. }
  1016. int Process::sys$setgid(gid_t gid)
  1017. {
  1018. if (gid != m_gid && !is_superuser())
  1019. return -EPERM;
  1020. m_gid = gid;
  1021. m_egid = gid;
  1022. return 0;
  1023. }
  1024. unsigned Process::sys$alarm(unsigned seconds)
  1025. {
  1026. (void) seconds;
  1027. ASSERT_NOT_REACHED();
  1028. }
  1029. int Process::sys$uname(utsname* buf)
  1030. {
  1031. if (!validate_write_typed(buf))
  1032. return -EFAULT;
  1033. strcpy(buf->sysname, "Serenity");
  1034. strcpy(buf->release, "1.0-dev");
  1035. strcpy(buf->version, "FIXME");
  1036. strcpy(buf->machine, "i386");
  1037. LOCKER(*s_hostname_lock);
  1038. strncpy(buf->nodename, s_hostname->characters(), sizeof(utsname::nodename));
  1039. return 0;
  1040. }
  1041. int Process::sys$isatty(int fd)
  1042. {
  1043. auto* descriptor = file_descriptor(fd);
  1044. if (!descriptor)
  1045. return -EBADF;
  1046. if (!descriptor->is_tty())
  1047. return -ENOTTY;
  1048. return 1;
  1049. }
  1050. int Process::sys$kill(pid_t pid, int signal)
  1051. {
  1052. if (signal < 0 || signal >= 32)
  1053. return -EINVAL;
  1054. if (pid == 0) {
  1055. // FIXME: Send to same-group processes.
  1056. ASSERT(pid != 0);
  1057. }
  1058. if (pid == -1) {
  1059. // FIXME: Send to all processes.
  1060. ASSERT(pid != -1);
  1061. }
  1062. if (pid == m_pid) {
  1063. current->send_signal(signal, this);
  1064. Scheduler::yield();
  1065. return 0;
  1066. }
  1067. InterruptDisabler disabler;
  1068. auto* peer = Process::from_pid(pid);
  1069. if (!peer)
  1070. return -ESRCH;
  1071. // FIXME: Allow sending SIGCONT to everyone in the process group.
  1072. // FIXME: Should setuid processes have some special treatment here?
  1073. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  1074. return -EPERM;
  1075. if (peer->is_ring0() && signal == SIGKILL) {
  1076. kprintf("%s(%u) attempted to send SIGKILL to ring 0 process %s(%u)\n", name().characters(), m_pid, peer->name().characters(), peer->pid());
  1077. return -EPERM;
  1078. }
  1079. peer->send_signal(signal, this);
  1080. return 0;
  1081. }
  1082. int Process::sys$usleep(useconds_t usec)
  1083. {
  1084. if (!usec)
  1085. return 0;
  1086. current->sleep(usec / 1000);
  1087. if (current->m_wakeup_time > g_uptime) {
  1088. ASSERT(current->m_was_interrupted_while_blocked);
  1089. dword ticks_left_until_original_wakeup_time = current->m_wakeup_time - g_uptime;
  1090. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1091. }
  1092. return 0;
  1093. }
  1094. int Process::sys$sleep(unsigned seconds)
  1095. {
  1096. if (!seconds)
  1097. return 0;
  1098. current->sleep(seconds * TICKS_PER_SECOND);
  1099. if (current->m_wakeup_time > g_uptime) {
  1100. ASSERT(current->m_was_interrupted_while_blocked);
  1101. dword ticks_left_until_original_wakeup_time = current->m_wakeup_time - g_uptime;
  1102. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1103. }
  1104. return 0;
  1105. }
  1106. void kgettimeofday(timeval& tv)
  1107. {
  1108. tv.tv_sec = RTC::boot_time() + PIT::seconds_since_boot();
  1109. tv.tv_usec = PIT::ticks_this_second() * 1000;
  1110. }
  1111. int Process::sys$gettimeofday(timeval* tv)
  1112. {
  1113. if (!validate_write_typed(tv))
  1114. return -EFAULT;
  1115. kgettimeofday(*tv);
  1116. return 0;
  1117. }
  1118. uid_t Process::sys$getuid()
  1119. {
  1120. return m_uid;
  1121. }
  1122. gid_t Process::sys$getgid()
  1123. {
  1124. return m_gid;
  1125. }
  1126. uid_t Process::sys$geteuid()
  1127. {
  1128. return m_euid;
  1129. }
  1130. gid_t Process::sys$getegid()
  1131. {
  1132. return m_egid;
  1133. }
  1134. pid_t Process::sys$getpid()
  1135. {
  1136. return m_pid;
  1137. }
  1138. pid_t Process::sys$getppid()
  1139. {
  1140. return m_ppid;
  1141. }
  1142. mode_t Process::sys$umask(mode_t mask)
  1143. {
  1144. auto old_mask = m_umask;
  1145. m_umask = mask & 0777;
  1146. return old_mask;
  1147. }
  1148. int Process::reap(Process& process)
  1149. {
  1150. int exit_status;
  1151. {
  1152. InterruptDisabler disabler;
  1153. exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1154. if (process.ppid()) {
  1155. auto* parent = Process::from_pid(process.ppid());
  1156. if (parent) {
  1157. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1158. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1159. }
  1160. }
  1161. dbgprintf("reap: %s(%u) {%s}\n", process.name().characters(), process.pid(), to_string(process.state()));
  1162. ASSERT(process.is_dead());
  1163. g_processes->remove(&process);
  1164. }
  1165. delete &process;
  1166. return exit_status;
  1167. }
  1168. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1169. {
  1170. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1171. // FIXME: Respect options
  1172. (void) options;
  1173. if (wstatus)
  1174. if (!validate_write_typed(wstatus))
  1175. return -EFAULT;
  1176. int dummy_wstatus;
  1177. int& exit_status = wstatus ? *wstatus : dummy_wstatus;
  1178. {
  1179. InterruptDisabler disabler;
  1180. if (waitee != -1 && !Process::from_pid(waitee))
  1181. return -ECHILD;
  1182. }
  1183. if (options & WNOHANG) {
  1184. if (waitee == -1) {
  1185. pid_t reaped_pid = 0;
  1186. InterruptDisabler disabler;
  1187. for_each_child([&reaped_pid, &exit_status] (Process& process) {
  1188. if (process.is_dead()) {
  1189. reaped_pid = process.pid();
  1190. exit_status = reap(process);
  1191. }
  1192. return true;
  1193. });
  1194. return reaped_pid;
  1195. } else {
  1196. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1197. InterruptDisabler disabler;
  1198. auto* waitee_process = Process::from_pid(waitee);
  1199. if (!waitee_process)
  1200. return -ECHILD;
  1201. if (waitee_process->is_dead()) {
  1202. exit_status = reap(*waitee_process);
  1203. return waitee;
  1204. }
  1205. return 0;
  1206. }
  1207. }
  1208. current->m_waitee_pid = waitee;
  1209. current->block(Thread::State::BlockedWait);
  1210. if (current->m_was_interrupted_while_blocked)
  1211. return -EINTR;
  1212. Process* waitee_process;
  1213. {
  1214. InterruptDisabler disabler;
  1215. // NOTE: If waitee was -1, m_waitee will have been filled in by the scheduler.
  1216. waitee_process = Process::from_pid(current->m_waitee_pid);
  1217. }
  1218. ASSERT(waitee_process);
  1219. exit_status = reap(*waitee_process);
  1220. return current->m_waitee_pid;
  1221. }
  1222. enum class KernelMemoryCheckResult {
  1223. NotInsideKernelMemory,
  1224. AccessGranted,
  1225. AccessDenied
  1226. };
  1227. static KernelMemoryCheckResult check_kernel_memory_access(LinearAddress laddr, bool is_write)
  1228. {
  1229. auto* kernel_elf_header = (Elf32_Ehdr*)0xf000;
  1230. auto* kernel_program_headers = (Elf32_Phdr*)(0xf000 + kernel_elf_header->e_phoff);
  1231. for (unsigned i = 0; i < kernel_elf_header->e_phnum; ++i) {
  1232. auto& segment = kernel_program_headers[i];
  1233. if (segment.p_type != PT_LOAD || !segment.p_vaddr || !segment.p_memsz)
  1234. continue;
  1235. if (laddr.get() < segment.p_vaddr || laddr.get() > (segment.p_vaddr + segment.p_memsz))
  1236. continue;
  1237. if (is_write && !(kernel_program_headers[i].p_flags & PF_W))
  1238. return KernelMemoryCheckResult::AccessDenied;
  1239. if (!is_write && !(kernel_program_headers[i].p_flags & PF_R))
  1240. return KernelMemoryCheckResult::AccessDenied;
  1241. return KernelMemoryCheckResult::AccessGranted;
  1242. }
  1243. return KernelMemoryCheckResult::NotInsideKernelMemory;
  1244. }
  1245. bool Process::validate_read_from_kernel(LinearAddress laddr) const
  1246. {
  1247. if (laddr.is_null())
  1248. return false;
  1249. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1250. // This code allows access outside of the known used address ranges to get caught.
  1251. auto kmc_result = check_kernel_memory_access(laddr, false);
  1252. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1253. return true;
  1254. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1255. return false;
  1256. if (is_kmalloc_address(laddr.as_ptr()))
  1257. return true;
  1258. return validate_read(laddr.as_ptr(), 1);
  1259. }
  1260. bool Process::validate_read_str(const char* str)
  1261. {
  1262. if (!validate_read(str, 1))
  1263. return false;
  1264. return validate_read(str, strlen(str) + 1);
  1265. }
  1266. bool Process::validate_read(const void* address, ssize_t size) const
  1267. {
  1268. ASSERT(size >= 0);
  1269. LinearAddress first_address((dword)address);
  1270. LinearAddress last_address = first_address.offset(size - 1);
  1271. if (is_ring0()) {
  1272. auto kmc_result = check_kernel_memory_access(first_address, false);
  1273. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1274. return true;
  1275. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1276. return false;
  1277. if (is_kmalloc_address(address))
  1278. return true;
  1279. }
  1280. ASSERT(size);
  1281. if (!size)
  1282. return false;
  1283. if (first_address.page_base() != last_address.page_base()) {
  1284. if (!MM.validate_user_read(*this, last_address))
  1285. return false;
  1286. }
  1287. return MM.validate_user_read(*this, first_address);
  1288. }
  1289. bool Process::validate_write(void* address, ssize_t size) const
  1290. {
  1291. ASSERT(size >= 0);
  1292. LinearAddress first_address((dword)address);
  1293. LinearAddress last_address = first_address.offset(size - 1);
  1294. if (is_ring0()) {
  1295. if (is_kmalloc_address(address))
  1296. return true;
  1297. auto kmc_result = check_kernel_memory_access(first_address, true);
  1298. if (kmc_result == KernelMemoryCheckResult::AccessGranted)
  1299. return true;
  1300. if (kmc_result == KernelMemoryCheckResult::AccessDenied)
  1301. return false;
  1302. }
  1303. if (!size)
  1304. return false;
  1305. if (first_address.page_base() != last_address.page_base()) {
  1306. if (!MM.validate_user_write(*this, last_address))
  1307. return false;
  1308. }
  1309. return MM.validate_user_write(*this, last_address);
  1310. }
  1311. pid_t Process::sys$getsid(pid_t pid)
  1312. {
  1313. if (pid == 0)
  1314. return m_sid;
  1315. InterruptDisabler disabler;
  1316. auto* process = Process::from_pid(pid);
  1317. if (!process)
  1318. return -ESRCH;
  1319. if (m_sid != process->m_sid)
  1320. return -EPERM;
  1321. return process->m_sid;
  1322. }
  1323. pid_t Process::sys$setsid()
  1324. {
  1325. InterruptDisabler disabler;
  1326. bool found_process_with_same_pgid_as_my_pid = false;
  1327. Process::for_each_in_pgrp(pid(), [&] (auto&) {
  1328. found_process_with_same_pgid_as_my_pid = true;
  1329. return false;
  1330. });
  1331. if (found_process_with_same_pgid_as_my_pid)
  1332. return -EPERM;
  1333. m_sid = m_pid;
  1334. m_pgid = m_pid;
  1335. return m_sid;
  1336. }
  1337. pid_t Process::sys$getpgid(pid_t pid)
  1338. {
  1339. if (pid == 0)
  1340. return m_pgid;
  1341. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1342. auto* process = Process::from_pid(pid);
  1343. if (!process)
  1344. return -ESRCH;
  1345. return process->m_pgid;
  1346. }
  1347. pid_t Process::sys$getpgrp()
  1348. {
  1349. return m_pgid;
  1350. }
  1351. static pid_t get_sid_from_pgid(pid_t pgid)
  1352. {
  1353. InterruptDisabler disabler;
  1354. auto* group_leader = Process::from_pid(pgid);
  1355. if (!group_leader)
  1356. return -1;
  1357. return group_leader->sid();
  1358. }
  1359. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1360. {
  1361. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1362. pid_t pid = specified_pid ? specified_pid : m_pid;
  1363. if (specified_pgid < 0)
  1364. return -EINVAL;
  1365. auto* process = Process::from_pid(pid);
  1366. if (!process)
  1367. return -ESRCH;
  1368. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  1369. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  1370. pid_t new_sid = get_sid_from_pgid(new_pgid);
  1371. if (current_sid != new_sid) {
  1372. // Can't move a process between sessions.
  1373. return -EPERM;
  1374. }
  1375. // FIXME: There are more EPERM conditions to check for here..
  1376. process->m_pgid = new_pgid;
  1377. return 0;
  1378. }
  1379. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  1380. {
  1381. auto* descriptor = file_descriptor(fd);
  1382. if (!descriptor)
  1383. return -EBADF;
  1384. if (!descriptor->is_file())
  1385. return -ENOTTY;
  1386. return descriptor->file()->ioctl(*descriptor, request, arg);
  1387. }
  1388. int Process::sys$getdtablesize()
  1389. {
  1390. return m_max_open_file_descriptors;
  1391. }
  1392. int Process::sys$dup(int old_fd)
  1393. {
  1394. auto* descriptor = file_descriptor(old_fd);
  1395. if (!descriptor)
  1396. return -EBADF;
  1397. int new_fd = alloc_fd(0);
  1398. if (new_fd < 0)
  1399. return new_fd;
  1400. m_fds[new_fd].set(*descriptor);
  1401. return new_fd;
  1402. }
  1403. int Process::sys$dup2(int old_fd, int new_fd)
  1404. {
  1405. auto* descriptor = file_descriptor(old_fd);
  1406. if (!descriptor)
  1407. return -EBADF;
  1408. if (new_fd < 0 || new_fd >= m_max_open_file_descriptors)
  1409. return -EINVAL;
  1410. m_fds[new_fd].set(*descriptor);
  1411. return new_fd;
  1412. }
  1413. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  1414. {
  1415. if (old_set) {
  1416. if (!validate_write_typed(old_set))
  1417. return -EFAULT;
  1418. *old_set = current->m_signal_mask;
  1419. }
  1420. if (set) {
  1421. if (!validate_read_typed(set))
  1422. return -EFAULT;
  1423. switch (how) {
  1424. case SIG_BLOCK:
  1425. current->m_signal_mask &= ~(*set);
  1426. break;
  1427. case SIG_UNBLOCK:
  1428. current->m_signal_mask |= *set;
  1429. break;
  1430. case SIG_SETMASK:
  1431. current->m_signal_mask = *set;
  1432. break;
  1433. default:
  1434. return -EINVAL;
  1435. }
  1436. }
  1437. return 0;
  1438. }
  1439. int Process::sys$sigpending(sigset_t* set)
  1440. {
  1441. if (!validate_write_typed(set))
  1442. return -EFAULT;
  1443. *set = current->m_pending_signals;
  1444. return 0;
  1445. }
  1446. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  1447. {
  1448. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  1449. return -EINVAL;
  1450. if (!validate_read_typed(act))
  1451. return -EFAULT;
  1452. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  1453. auto& action = current->m_signal_action_data[signum];
  1454. if (old_act) {
  1455. if (!validate_write_typed(old_act))
  1456. return -EFAULT;
  1457. old_act->sa_flags = action.flags;
  1458. old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
  1459. }
  1460. action.flags = act->sa_flags;
  1461. action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
  1462. return 0;
  1463. }
  1464. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  1465. {
  1466. if (count < 0)
  1467. return -EINVAL;
  1468. if (!count)
  1469. return m_gids.size();
  1470. if (count != (int)m_gids.size())
  1471. return -EINVAL;
  1472. if (!validate_write_typed(gids, m_gids.size()))
  1473. return -EFAULT;
  1474. size_t i = 0;
  1475. for (auto gid : m_gids)
  1476. gids[i++] = gid;
  1477. return 0;
  1478. }
  1479. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  1480. {
  1481. if (count < 0)
  1482. return -EINVAL;
  1483. if (!is_superuser())
  1484. return -EPERM;
  1485. if (!validate_read(gids, count))
  1486. return -EFAULT;
  1487. m_gids.clear();
  1488. m_gids.set(m_gid);
  1489. for (int i = 0; i < count; ++i)
  1490. m_gids.set(gids[i]);
  1491. return 0;
  1492. }
  1493. int Process::sys$mkdir(const char* pathname, mode_t mode)
  1494. {
  1495. if (!validate_read_str(pathname))
  1496. return -EFAULT;
  1497. size_t pathname_length = strlen(pathname);
  1498. if (pathname_length == 0)
  1499. return -EINVAL;
  1500. if (pathname_length >= 255)
  1501. return -ENAMETOOLONG;
  1502. return VFS::the().mkdir(StringView(pathname, pathname_length), mode & ~umask(), cwd_inode());
  1503. }
  1504. clock_t Process::sys$times(tms* times)
  1505. {
  1506. if (!validate_write_typed(times))
  1507. return -EFAULT;
  1508. times->tms_utime = m_ticks_in_user;
  1509. times->tms_stime = m_ticks_in_kernel;
  1510. times->tms_cutime = m_ticks_in_user_for_dead_children;
  1511. times->tms_cstime = m_ticks_in_kernel_for_dead_children;
  1512. return 0;
  1513. }
  1514. int Process::sys$select(const Syscall::SC_select_params* params)
  1515. {
  1516. if (!validate_read_typed(params))
  1517. return -EFAULT;
  1518. if (params->writefds && !validate_read_typed(params->writefds))
  1519. return -EFAULT;
  1520. if (params->readfds && !validate_read_typed(params->readfds))
  1521. return -EFAULT;
  1522. if (params->exceptfds && !validate_read_typed(params->exceptfds))
  1523. return -EFAULT;
  1524. if (params->timeout && !validate_read_typed(params->timeout))
  1525. return -EFAULT;
  1526. int nfds = params->nfds;
  1527. fd_set* writefds = params->writefds;
  1528. fd_set* readfds = params->readfds;
  1529. fd_set* exceptfds = params->exceptfds;
  1530. auto* timeout = params->timeout;
  1531. // FIXME: Implement exceptfds support.
  1532. (void)exceptfds;
  1533. if (timeout) {
  1534. current->m_select_timeout = *timeout;
  1535. current->m_select_has_timeout = true;
  1536. } else {
  1537. current->m_select_has_timeout = false;
  1538. }
  1539. if (nfds < 0)
  1540. return -EINVAL;
  1541. // FIXME: Return -EINTR if a signal is caught.
  1542. // FIXME: Return -EINVAL if timeout is invalid.
  1543. auto transfer_fds = [this, nfds] (fd_set* set, auto& vector) -> int {
  1544. if (!set)
  1545. return 0;
  1546. vector.clear_with_capacity();
  1547. auto bitmap = Bitmap::wrap((byte*)set, FD_SETSIZE);
  1548. for (int i = 0; i < nfds; ++i) {
  1549. if (bitmap.get(i)) {
  1550. if (!file_descriptor(i))
  1551. return -EBADF;
  1552. vector.append(i);
  1553. }
  1554. }
  1555. return 0;
  1556. };
  1557. int error = 0;
  1558. error = transfer_fds(writefds, current->m_select_write_fds);
  1559. if (error)
  1560. return error;
  1561. error = transfer_fds(readfds, current->m_select_read_fds);
  1562. if (error)
  1563. return error;
  1564. error = transfer_fds(readfds, current->m_select_exceptional_fds);
  1565. if (error)
  1566. return error;
  1567. #ifdef DEBUG_IO
  1568. dbgprintf("%s<%u> selecting on (read:%u, write:%u), timeout=%p\n", name().characters(), pid(), current->m_select_read_fds.size(), current->m_select_write_fds.size(), timeout);
  1569. #endif
  1570. if (!timeout || (timeout->tv_sec || timeout->tv_usec))
  1571. current->block(Thread::State::BlockedSelect);
  1572. int markedfds = 0;
  1573. if (readfds) {
  1574. memset(readfds, 0, sizeof(fd_set));
  1575. auto bitmap = Bitmap::wrap((byte*)readfds, FD_SETSIZE);
  1576. for (int fd : current->m_select_read_fds) {
  1577. auto* descriptor = file_descriptor(fd);
  1578. if (!descriptor)
  1579. continue;
  1580. if (descriptor->can_read()) {
  1581. bitmap.set(fd, true);
  1582. ++markedfds;
  1583. }
  1584. }
  1585. }
  1586. if (writefds) {
  1587. memset(writefds, 0, sizeof(fd_set));
  1588. auto bitmap = Bitmap::wrap((byte*)writefds, FD_SETSIZE);
  1589. for (int fd : current->m_select_write_fds) {
  1590. auto* descriptor = file_descriptor(fd);
  1591. if (!descriptor)
  1592. continue;
  1593. if (descriptor->can_write()) {
  1594. bitmap.set(fd, true);
  1595. ++markedfds;
  1596. }
  1597. }
  1598. }
  1599. // FIXME: Check for exceptional conditions.
  1600. return markedfds;
  1601. }
  1602. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  1603. {
  1604. if (!validate_read_typed(fds))
  1605. return -EFAULT;
  1606. current->m_select_write_fds.clear_with_capacity();
  1607. current->m_select_read_fds.clear_with_capacity();
  1608. for (int i = 0; i < nfds; ++i) {
  1609. if (fds[i].events & POLLIN)
  1610. current->m_select_read_fds.append(fds[i].fd);
  1611. if (fds[i].events & POLLOUT)
  1612. current->m_select_write_fds.append(fds[i].fd);
  1613. }
  1614. if (timeout < 0)
  1615. current->block(Thread::State::BlockedSelect);
  1616. int fds_with_revents = 0;
  1617. for (int i = 0; i < nfds; ++i) {
  1618. auto* descriptor = file_descriptor(fds[i].fd);
  1619. if (!descriptor) {
  1620. fds[i].revents = POLLNVAL;
  1621. continue;
  1622. }
  1623. fds[i].revents = 0;
  1624. if (fds[i].events & POLLIN && descriptor->can_read())
  1625. fds[i].revents |= POLLIN;
  1626. if (fds[i].events & POLLOUT && descriptor->can_write())
  1627. fds[i].revents |= POLLOUT;
  1628. if (fds[i].revents)
  1629. ++fds_with_revents;
  1630. }
  1631. return fds_with_revents;
  1632. }
  1633. Inode& Process::cwd_inode()
  1634. {
  1635. // FIXME: This is retarded factoring.
  1636. if (!m_cwd)
  1637. m_cwd = VFS::the().root_inode();
  1638. return *m_cwd;
  1639. }
  1640. int Process::sys$link(const char* old_path, const char* new_path)
  1641. {
  1642. if (!validate_read_str(old_path))
  1643. return -EFAULT;
  1644. if (!validate_read_str(new_path))
  1645. return -EFAULT;
  1646. return VFS::the().link(StringView(old_path), StringView(new_path), cwd_inode());
  1647. }
  1648. int Process::sys$unlink(const char* pathname)
  1649. {
  1650. if (!validate_read_str(pathname))
  1651. return -EFAULT;
  1652. return VFS::the().unlink(StringView(pathname), cwd_inode());
  1653. }
  1654. int Process::sys$symlink(const char* target, const char* linkpath)
  1655. {
  1656. if (!validate_read_str(target))
  1657. return -EFAULT;
  1658. if (!validate_read_str(linkpath))
  1659. return -EFAULT;
  1660. return VFS::the().symlink(StringView(target), StringView(linkpath), cwd_inode());
  1661. }
  1662. int Process::sys$rmdir(const char* pathname)
  1663. {
  1664. if (!validate_read_str(pathname))
  1665. return -EFAULT;
  1666. return VFS::the().rmdir(StringView(pathname), cwd_inode());
  1667. }
  1668. int Process::sys$read_tsc(dword* lsw, dword* msw)
  1669. {
  1670. if (!validate_write_typed(lsw))
  1671. return -EFAULT;
  1672. if (!validate_write_typed(msw))
  1673. return -EFAULT;
  1674. read_tsc(*lsw, *msw);
  1675. return 0;
  1676. }
  1677. int Process::sys$chmod(const char* pathname, mode_t mode)
  1678. {
  1679. if (!validate_read_str(pathname))
  1680. return -EFAULT;
  1681. return VFS::the().chmod(StringView(pathname), mode, cwd_inode());
  1682. }
  1683. int Process::sys$fchmod(int fd, mode_t mode)
  1684. {
  1685. auto* descriptor = file_descriptor(fd);
  1686. if (!descriptor)
  1687. return -EBADF;
  1688. return descriptor->fchmod(mode);
  1689. }
  1690. int Process::sys$chown(const char* pathname, uid_t uid, gid_t gid)
  1691. {
  1692. if (!validate_read_str(pathname))
  1693. return -EFAULT;
  1694. return VFS::the().chown(StringView(pathname), uid, gid, cwd_inode());
  1695. }
  1696. void Process::finalize()
  1697. {
  1698. ASSERT(current == g_finalizer);
  1699. dbgprintf("Finalizing Process %s(%u)\n", m_name.characters(), m_pid);
  1700. m_fds.clear();
  1701. m_tty = nullptr;
  1702. disown_all_shared_buffers();
  1703. {
  1704. InterruptDisabler disabler;
  1705. if (auto* parent_process = Process::from_pid(m_ppid)) {
  1706. // FIXME(Thread): What should we do here? Should we look at all threads' signal actions?
  1707. if (parent_process->main_thread().m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  1708. // NOTE: If the parent doesn't care about this process, let it go.
  1709. m_ppid = 0;
  1710. } else {
  1711. parent_process->send_signal(SIGCHLD, this);
  1712. }
  1713. }
  1714. }
  1715. m_dead = true;
  1716. }
  1717. void Process::die()
  1718. {
  1719. if (m_tracer)
  1720. m_tracer->set_dead();
  1721. {
  1722. InterruptDisabler disabler;
  1723. for_each_thread([] (Thread& thread) {
  1724. if (thread.state() != Thread::State::Dead)
  1725. thread.set_state(Thread::State::Dying);
  1726. return IterationDecision::Continue;
  1727. });
  1728. }
  1729. if (!Scheduler::is_active())
  1730. Scheduler::pick_next_and_switch_now();
  1731. }
  1732. size_t Process::amount_virtual() const
  1733. {
  1734. size_t amount = 0;
  1735. for (auto& region : m_regions) {
  1736. amount += region->size();
  1737. }
  1738. return amount;
  1739. }
  1740. size_t Process::amount_resident() const
  1741. {
  1742. // FIXME: This will double count if multiple regions use the same physical page.
  1743. size_t amount = 0;
  1744. for (auto& region : m_regions) {
  1745. amount += region->amount_resident();
  1746. }
  1747. return amount;
  1748. }
  1749. size_t Process::amount_shared() const
  1750. {
  1751. // FIXME: This will double count if multiple regions use the same physical page.
  1752. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage retain counts,
  1753. // and each PhysicalPage is only retained by its VMObject. This needs to be refactored
  1754. // so that every Region contributes +1 retain to each of its PhysicalPages.
  1755. size_t amount = 0;
  1756. for (auto& region : m_regions) {
  1757. amount += region->amount_shared();
  1758. }
  1759. return amount;
  1760. }
  1761. int Process::sys$socket(int domain, int type, int protocol)
  1762. {
  1763. int fd = alloc_fd();
  1764. if (fd < 0)
  1765. return fd;
  1766. auto result = Socket::create(domain, type, protocol);
  1767. if (result.is_error())
  1768. return result.error();
  1769. auto descriptor = FileDescriptor::create(*result.value());
  1770. unsigned flags = 0;
  1771. if (type & SOCK_CLOEXEC)
  1772. flags |= FD_CLOEXEC;
  1773. if (type & SOCK_NONBLOCK)
  1774. descriptor->set_blocking(false);
  1775. m_fds[fd].set(move(descriptor), flags);
  1776. return fd;
  1777. }
  1778. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  1779. {
  1780. if (!validate_read(address, address_length))
  1781. return -EFAULT;
  1782. auto* descriptor = file_descriptor(sockfd);
  1783. if (!descriptor)
  1784. return -EBADF;
  1785. if (!descriptor->is_socket())
  1786. return -ENOTSOCK;
  1787. auto& socket = *descriptor->socket();
  1788. return socket.bind(address, address_length);
  1789. }
  1790. int Process::sys$listen(int sockfd, int backlog)
  1791. {
  1792. auto* descriptor = file_descriptor(sockfd);
  1793. if (!descriptor)
  1794. return -EBADF;
  1795. if (!descriptor->is_socket())
  1796. return -ENOTSOCK;
  1797. auto& socket = *descriptor->socket();
  1798. auto result = socket.listen(backlog);
  1799. if (result.is_error())
  1800. return result;
  1801. descriptor->set_socket_role(SocketRole::Listener);
  1802. return 0;
  1803. }
  1804. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  1805. {
  1806. if (!validate_write_typed(address_size))
  1807. return -EFAULT;
  1808. if (!validate_write(address, *address_size))
  1809. return -EFAULT;
  1810. int accepted_socket_fd = alloc_fd();
  1811. if (accepted_socket_fd < 0)
  1812. return accepted_socket_fd;
  1813. auto* accepting_socket_descriptor = file_descriptor(accepting_socket_fd);
  1814. if (!accepting_socket_descriptor)
  1815. return -EBADF;
  1816. if (!accepting_socket_descriptor->is_socket())
  1817. return -ENOTSOCK;
  1818. auto& socket = *accepting_socket_descriptor->socket();
  1819. if (!socket.can_accept()) {
  1820. ASSERT(!accepting_socket_descriptor->is_blocking());
  1821. return -EAGAIN;
  1822. }
  1823. auto accepted_socket = socket.accept();
  1824. ASSERT(accepted_socket);
  1825. bool success = accepted_socket->get_address(address, address_size);
  1826. ASSERT(success);
  1827. auto accepted_socket_descriptor = FileDescriptor::create(move(accepted_socket), SocketRole::Accepted);
  1828. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  1829. // I'm not sure if this matches other systems but it makes sense to me.
  1830. accepted_socket_descriptor->set_blocking(accepting_socket_descriptor->is_blocking());
  1831. m_fds[accepted_socket_fd].set(move(accepted_socket_descriptor), m_fds[accepting_socket_fd].flags);
  1832. return accepted_socket_fd;
  1833. }
  1834. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  1835. {
  1836. if (!validate_read(address, address_size))
  1837. return -EFAULT;
  1838. int fd = alloc_fd();
  1839. if (fd < 0)
  1840. return fd;
  1841. auto* descriptor = file_descriptor(sockfd);
  1842. if (!descriptor)
  1843. return -EBADF;
  1844. if (!descriptor->is_socket())
  1845. return -ENOTSOCK;
  1846. if (descriptor->socket_role() == SocketRole::Connected)
  1847. return -EISCONN;
  1848. auto& socket = *descriptor->socket();
  1849. descriptor->set_socket_role(SocketRole::Connecting);
  1850. auto result = socket.connect(*descriptor, address, address_size, descriptor->is_blocking() ? ShouldBlock::Yes : ShouldBlock::No);
  1851. if (result.is_error()) {
  1852. descriptor->set_socket_role(SocketRole::None);
  1853. return result;
  1854. }
  1855. descriptor->set_socket_role(SocketRole::Connected);
  1856. return 0;
  1857. }
  1858. ssize_t Process::sys$sendto(const Syscall::SC_sendto_params* params)
  1859. {
  1860. if (!validate_read_typed(params))
  1861. return -EFAULT;
  1862. int sockfd = params->sockfd;
  1863. const void* data = params->data;
  1864. size_t data_length = params->data_length;
  1865. int flags = params->flags;
  1866. auto* addr = (const sockaddr*)params->addr;
  1867. auto addr_length = (socklen_t)params->addr_length;
  1868. if (!validate_read(data, data_length))
  1869. return -EFAULT;
  1870. if (addr && !validate_read(addr, addr_length))
  1871. return -EFAULT;
  1872. auto* descriptor = file_descriptor(sockfd);
  1873. if (!descriptor)
  1874. return -EBADF;
  1875. if (!descriptor->is_socket())
  1876. return -ENOTSOCK;
  1877. auto& socket = *descriptor->socket();
  1878. kprintf("sendto %p (%u), flags=%u, addr: %p (%u)\n", data, data_length, flags, addr, addr_length);
  1879. return socket.sendto(*descriptor, data, data_length, flags, addr, addr_length);
  1880. }
  1881. ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* params)
  1882. {
  1883. if (!validate_read_typed(params))
  1884. return -EFAULT;
  1885. int sockfd = params->sockfd;
  1886. void* buffer = params->buffer;
  1887. size_t buffer_length = params->buffer_length;
  1888. int flags = params->flags;
  1889. auto* addr = (sockaddr*)params->addr;
  1890. auto* addr_length = (socklen_t*)params->addr_length;
  1891. if (!validate_write(buffer, buffer_length))
  1892. return -EFAULT;
  1893. if (addr_length) {
  1894. if (!validate_read_typed(addr_length))
  1895. return -EFAULT;
  1896. if (!validate_read(addr, *addr_length))
  1897. return -EFAULT;
  1898. } else if (addr) {
  1899. return -EINVAL;
  1900. }
  1901. auto* descriptor = file_descriptor(sockfd);
  1902. if (!descriptor)
  1903. return -EBADF;
  1904. if (!descriptor->is_socket())
  1905. return -ENOTSOCK;
  1906. auto& socket = *descriptor->socket();
  1907. kprintf("recvfrom %p (%u), flags=%u, addr: %p (%p)\n", buffer, buffer_length, flags, addr, addr_length);
  1908. return socket.recvfrom(*descriptor, buffer, buffer_length, flags, addr, addr_length);
  1909. }
  1910. int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params)
  1911. {
  1912. if (!validate_read_typed(params))
  1913. return -EFAULT;
  1914. int sockfd = params->sockfd;
  1915. int level = params->level;
  1916. int option = params->option;
  1917. auto* value = params->value;
  1918. auto* value_size = (socklen_t*)params->value_size;
  1919. if (!validate_write_typed(value_size))
  1920. return -EFAULT;
  1921. if (!validate_write(value, *value_size))
  1922. return -EFAULT;
  1923. auto* descriptor = file_descriptor(sockfd);
  1924. if (!descriptor)
  1925. return -EBADF;
  1926. if (!descriptor->is_socket())
  1927. return -ENOTSOCK;
  1928. auto& socket = *descriptor->socket();
  1929. return socket.getsockopt(level, option, value, value_size);
  1930. }
  1931. int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params)
  1932. {
  1933. if (!validate_read_typed(params))
  1934. return -EFAULT;
  1935. int sockfd = params->sockfd;
  1936. int level = params->level;
  1937. int option = params->option;
  1938. auto* value = params->value;
  1939. auto value_size = (socklen_t)params->value_size;
  1940. if (!validate_read(value, value_size))
  1941. return -EFAULT;
  1942. auto* descriptor = file_descriptor(sockfd);
  1943. if (!descriptor)
  1944. return -EBADF;
  1945. if (!descriptor->is_socket())
  1946. return -ENOTSOCK;
  1947. auto& socket = *descriptor->socket();
  1948. return socket.setsockopt(level, option, value, value_size);
  1949. }
  1950. struct SharedBuffer {
  1951. SharedBuffer(pid_t pid1, pid_t pid2, int size)
  1952. : m_pid1(pid1)
  1953. , m_pid2(pid2)
  1954. , m_vmo(VMObject::create_anonymous(size))
  1955. {
  1956. ASSERT(pid1 != pid2);
  1957. }
  1958. void* retain(Process& process)
  1959. {
  1960. if (m_pid1 == process.pid()) {
  1961. ++m_pid1_retain_count;
  1962. if (!m_pid1_region) {
  1963. m_pid1_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, m_pid1_writable);
  1964. m_pid1_region->set_shared(true);
  1965. }
  1966. return m_pid1_region->laddr().as_ptr();
  1967. } else if (m_pid2 == process.pid()) {
  1968. ++m_pid2_retain_count;
  1969. if (!m_pid2_region) {
  1970. m_pid2_region = process.allocate_region_with_vmo(LinearAddress(), size(), m_vmo.copy_ref(), 0, "SharedBuffer", true, m_pid2_writable);
  1971. m_pid2_region->set_shared(true);
  1972. }
  1973. return m_pid2_region->laddr().as_ptr();
  1974. }
  1975. return nullptr;
  1976. }
  1977. void release(Process& process)
  1978. {
  1979. if (m_pid1 == process.pid()) {
  1980. ASSERT(m_pid1_retain_count);
  1981. --m_pid1_retain_count;
  1982. if (!m_pid1_retain_count) {
  1983. if (m_pid1_region)
  1984. process.deallocate_region(*m_pid1_region);
  1985. m_pid1_region = nullptr;
  1986. }
  1987. destroy_if_unused();
  1988. } else if (m_pid2 == process.pid()) {
  1989. ASSERT(m_pid2_retain_count);
  1990. --m_pid2_retain_count;
  1991. if (!m_pid2_retain_count) {
  1992. if (m_pid2_region)
  1993. process.deallocate_region(*m_pid2_region);
  1994. m_pid2_region = nullptr;
  1995. }
  1996. destroy_if_unused();
  1997. }
  1998. }
  1999. void disown(pid_t pid)
  2000. {
  2001. if (m_pid1 == pid) {
  2002. m_pid1 = 0;
  2003. m_pid1_retain_count = 0;
  2004. destroy_if_unused();
  2005. } else if (m_pid2 == pid) {
  2006. m_pid2 = 0;
  2007. m_pid2_retain_count = 0;
  2008. destroy_if_unused();
  2009. }
  2010. }
  2011. pid_t pid1() const { return m_pid1; }
  2012. pid_t pid2() const { return m_pid2; }
  2013. unsigned pid1_retain_count() const { return m_pid1_retain_count; }
  2014. unsigned pid2_retain_count() const { return m_pid2_retain_count; }
  2015. size_t size() const { return m_vmo->size(); }
  2016. void destroy_if_unused();
  2017. void seal()
  2018. {
  2019. m_pid1_writable = false;
  2020. m_pid2_writable = false;
  2021. if (m_pid1_region) {
  2022. m_pid1_region->set_writable(false);
  2023. MM.remap_region(*m_pid1_region->page_directory(), *m_pid1_region);
  2024. }
  2025. if (m_pid2_region) {
  2026. m_pid2_region->set_writable(false);
  2027. MM.remap_region(*m_pid2_region->page_directory(), *m_pid2_region);
  2028. }
  2029. }
  2030. int m_shared_buffer_id { -1 };
  2031. pid_t m_pid1;
  2032. pid_t m_pid2;
  2033. unsigned m_pid1_retain_count { 1 };
  2034. unsigned m_pid2_retain_count { 0 };
  2035. Region* m_pid1_region { nullptr };
  2036. Region* m_pid2_region { nullptr };
  2037. bool m_pid1_writable { false };
  2038. bool m_pid2_writable { false };
  2039. Retained<VMObject> m_vmo;
  2040. };
  2041. static int s_next_shared_buffer_id;
  2042. Lockable<HashMap<int, OwnPtr<SharedBuffer>>>& shared_buffers()
  2043. {
  2044. static Lockable<HashMap<int, OwnPtr<SharedBuffer>>>* map;
  2045. if (!map)
  2046. map = new Lockable<HashMap<int, OwnPtr<SharedBuffer>>>;
  2047. return *map;
  2048. }
  2049. void SharedBuffer::destroy_if_unused()
  2050. {
  2051. if (!m_pid1_retain_count && !m_pid2_retain_count) {
  2052. LOCKER(shared_buffers().lock());
  2053. #ifdef SHARED_BUFFER_DEBUG
  2054. kprintf("Destroying unused SharedBuffer{%p} id: %d (pid1: %d, pid2: %d)\n", this, m_shared_buffer_id, m_pid1, m_pid2);
  2055. #endif
  2056. size_t count_before = shared_buffers().resource().size();
  2057. shared_buffers().resource().remove(m_shared_buffer_id);
  2058. ASSERT(count_before != shared_buffers().resource().size());
  2059. }
  2060. }
  2061. void Process::disown_all_shared_buffers()
  2062. {
  2063. LOCKER(shared_buffers().lock());
  2064. Vector<SharedBuffer*, 32> buffers_to_disown;
  2065. for (auto& it : shared_buffers().resource())
  2066. buffers_to_disown.append(it.value.ptr());
  2067. for (auto* shared_buffer : buffers_to_disown)
  2068. shared_buffer->disown(m_pid);
  2069. }
  2070. int Process::sys$create_shared_buffer(pid_t peer_pid, int size, void** buffer)
  2071. {
  2072. if (!size || size < 0)
  2073. return -EINVAL;
  2074. size = PAGE_ROUND_UP(size);
  2075. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2076. return -EINVAL;
  2077. if (!validate_write_typed(buffer))
  2078. return -EFAULT;
  2079. {
  2080. InterruptDisabler disabler;
  2081. auto* peer = Process::from_pid(peer_pid);
  2082. if (!peer)
  2083. return -ESRCH;
  2084. }
  2085. LOCKER(shared_buffers().lock());
  2086. int shared_buffer_id = ++s_next_shared_buffer_id;
  2087. auto shared_buffer = make<SharedBuffer>(m_pid, peer_pid, size);
  2088. shared_buffer->m_shared_buffer_id = shared_buffer_id;
  2089. ASSERT(shared_buffer->size() >= size);
  2090. shared_buffer->m_pid1_region = allocate_region_with_vmo(LinearAddress(), shared_buffer->size(), shared_buffer->m_vmo.copy_ref(), 0, "SharedBuffer", true, true);
  2091. shared_buffer->m_pid1_region->set_shared(true);
  2092. *buffer = shared_buffer->m_pid1_region->laddr().as_ptr();
  2093. #ifdef SHARED_BUFFER_DEBUG
  2094. kprintf("%s(%u): Created shared buffer %d (%u bytes, vmo is %u) for sharing with %d\n", name().characters(), pid(),shared_buffer_id, size, shared_buffer->size(), peer_pid);
  2095. #endif
  2096. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2097. return shared_buffer_id;
  2098. }
  2099. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2100. {
  2101. LOCKER(shared_buffers().lock());
  2102. auto it = shared_buffers().resource().find(shared_buffer_id);
  2103. if (it == shared_buffers().resource().end())
  2104. return -EINVAL;
  2105. auto& shared_buffer = *(*it).value;
  2106. #ifdef SHARED_BUFFER_DEBUG
  2107. kprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2108. #endif
  2109. shared_buffer.release(*this);
  2110. return 0;
  2111. }
  2112. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2113. {
  2114. LOCKER(shared_buffers().lock());
  2115. auto it = shared_buffers().resource().find(shared_buffer_id);
  2116. if (it == shared_buffers().resource().end())
  2117. return (void*)-EINVAL;
  2118. auto& shared_buffer = *(*it).value;
  2119. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2120. return (void*)-EINVAL;
  2121. #ifdef SHARED_BUFFER_DEBUG
  2122. kprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2123. #endif
  2124. return shared_buffer.retain(*this);
  2125. }
  2126. int Process::sys$seal_shared_buffer(int shared_buffer_id)
  2127. {
  2128. LOCKER(shared_buffers().lock());
  2129. auto it = shared_buffers().resource().find(shared_buffer_id);
  2130. if (it == shared_buffers().resource().end())
  2131. return -EINVAL;
  2132. auto& shared_buffer = *(*it).value;
  2133. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2134. return -EINVAL;
  2135. #ifdef SHARED_BUFFER_DEBUG
  2136. kprintf("%s(%u): Sealing shared buffer %d\n", name().characters(), pid(), shared_buffer_id);
  2137. #endif
  2138. shared_buffer.seal();
  2139. return 0;
  2140. }
  2141. int Process::sys$get_shared_buffer_size(int shared_buffer_id)
  2142. {
  2143. LOCKER(shared_buffers().lock());
  2144. auto it = shared_buffers().resource().find(shared_buffer_id);
  2145. if (it == shared_buffers().resource().end())
  2146. return -EINVAL;
  2147. auto& shared_buffer = *(*it).value;
  2148. if (shared_buffer.pid1() != m_pid && shared_buffer.pid2() != m_pid)
  2149. return -EINVAL;
  2150. #ifdef SHARED_BUFFER_DEBUG
  2151. kprintf("%s(%u): Get shared buffer %d size: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2152. #endif
  2153. return shared_buffer.size();
  2154. }
  2155. const char* to_string(Process::Priority priority)
  2156. {
  2157. switch (priority) {
  2158. case Process::IdlePriority: return "Idle";
  2159. case Process::LowPriority: return "Low";
  2160. case Process::NormalPriority: return "Normal";
  2161. case Process::HighPriority: return "High";
  2162. }
  2163. kprintf("to_string(Process::Priority): Invalid priority: %u\n", priority);
  2164. ASSERT_NOT_REACHED();
  2165. return nullptr;
  2166. }
  2167. void Process::terminate_due_to_signal(byte signal)
  2168. {
  2169. ASSERT_INTERRUPTS_DISABLED();
  2170. ASSERT(signal < 32);
  2171. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  2172. m_termination_status = 0;
  2173. m_termination_signal = signal;
  2174. die();
  2175. }
  2176. void Process::send_signal(byte signal, Process* sender)
  2177. {
  2178. // FIXME(Thread): Find the appropriate thread to deliver the signal to.
  2179. main_thread().send_signal(signal, sender);
  2180. }
  2181. int Process::thread_count() const
  2182. {
  2183. int count = 0;
  2184. for_each_thread([&count] (auto&) {
  2185. ++count;
  2186. return IterationDecision::Continue;
  2187. });
  2188. return count;
  2189. }
  2190. int Process::sys$create_thread(int(*entry)(void*), void* argument)
  2191. {
  2192. if (!validate_read((const void*)entry, sizeof(void*)))
  2193. return -EFAULT;
  2194. auto* thread = new Thread(*this);
  2195. auto& tss = thread->tss();
  2196. tss.eip = (dword)entry;
  2197. tss.eflags = 0x0202;
  2198. tss.cr3 = page_directory().cr3();
  2199. thread->make_userspace_stack_for_secondary_thread(argument);
  2200. thread->set_state(Thread::State::Runnable);
  2201. return 0;
  2202. }
  2203. void Process::sys$exit_thread(int code)
  2204. {
  2205. cli();
  2206. if (&current->process().main_thread() == current) {
  2207. sys$exit(code);
  2208. return;
  2209. }
  2210. current->set_state(Thread::State::Dying);
  2211. big_lock().unlock_if_locked();
  2212. Scheduler::pick_next_and_switch_now();
  2213. ASSERT_NOT_REACHED();
  2214. }
  2215. int Process::sys$gettid()
  2216. {
  2217. return current->tid();
  2218. }
  2219. int Process::sys$donate(int tid)
  2220. {
  2221. if (tid < 0)
  2222. return -EINVAL;
  2223. InterruptDisabler disabler;
  2224. Thread* beneficiary = nullptr;
  2225. for_each_thread([&] (Thread& thread) {
  2226. if (thread.tid() == tid) {
  2227. beneficiary = &thread;
  2228. return IterationDecision::Abort;
  2229. }
  2230. return IterationDecision::Continue;
  2231. });
  2232. if (!beneficiary)
  2233. return -ENOTHREAD;
  2234. Scheduler::donate_to(beneficiary, "sys$donate");
  2235. return 0;
  2236. }
  2237. int Process::sys$rename(const char* oldpath, const char* newpath)
  2238. {
  2239. if (!validate_read_str(oldpath))
  2240. return -EFAULT;
  2241. if (!validate_read_str(newpath))
  2242. return -EFAULT;
  2243. return VFS::the().rename(StringView(oldpath), StringView(newpath), cwd_inode());
  2244. }
  2245. int Process::sys$shm_open(const char* name, int flags, mode_t mode)
  2246. {
  2247. if (!validate_read_str(name))
  2248. return -EFAULT;
  2249. int fd = alloc_fd();
  2250. if (fd < 0)
  2251. return fd;
  2252. auto shm_or_error = SharedMemory::open(String(name), flags, mode);
  2253. if (shm_or_error.is_error())
  2254. return shm_or_error.error();
  2255. auto descriptor = FileDescriptor::create(shm_or_error.value().ptr());
  2256. m_fds[fd].set(move(descriptor), FD_CLOEXEC);
  2257. return fd;
  2258. }
  2259. int Process::sys$shm_unlink(const char* name)
  2260. {
  2261. if (!validate_read_str(name))
  2262. return -EFAULT;
  2263. return SharedMemory::unlink(String(name));
  2264. }
  2265. int Process::sys$ftruncate(int fd, off_t length)
  2266. {
  2267. auto* descriptor = file_descriptor(fd);
  2268. if (!descriptor)
  2269. return -EBADF;
  2270. // FIXME: Check that fd is writable, otherwise EINVAL.
  2271. if (!descriptor->is_file() && !descriptor->is_shared_memory())
  2272. return -EINVAL;
  2273. return descriptor->truncate(length);
  2274. }
  2275. int Process::sys$systrace(pid_t pid)
  2276. {
  2277. InterruptDisabler disabler;
  2278. auto* peer = Process::from_pid(pid);
  2279. if (!peer)
  2280. return -ESRCH;
  2281. if (peer->uid() != m_euid)
  2282. return -EACCES;
  2283. int fd = alloc_fd();
  2284. if (fd < 0)
  2285. return fd;
  2286. auto descriptor = FileDescriptor::create(peer->ensure_tracer());
  2287. m_fds[fd].set(move(descriptor), 0);
  2288. return fd;
  2289. }
  2290. ProcessTracer& Process::ensure_tracer()
  2291. {
  2292. if (!m_tracer)
  2293. m_tracer = ProcessTracer::create(m_pid);
  2294. return *m_tracer;
  2295. }
  2296. void Process::FileDescriptorAndFlags::clear()
  2297. {
  2298. descriptor = nullptr;
  2299. flags = 0;
  2300. }
  2301. void Process::FileDescriptorAndFlags::set(Retained<FileDescriptor>&& d, dword f)
  2302. {
  2303. descriptor = move(d);
  2304. flags = f;
  2305. }