Process.cpp 76 KB

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