Process.cpp 75 KB

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