Process.cpp 82 KB

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