Process.cpp 79 KB

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