Process.cpp 79 KB

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