Process.cpp 79 KB

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