Process.cpp 89 KB

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