Process.cpp 77 KB

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