Process.cpp 77 KB

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