Process.cpp 84 KB

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