Process.cpp 77 KB

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