Process.cpp 76 KB

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