Process.cpp 88 KB

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