Process.cpp 78 KB

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