Process.cpp 84 KB

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