Process.cpp 90 KB

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