Process.cpp 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435
  1. #include <AK/FileSystemPath.h>
  2. #include <AK/StdLibExtras.h>
  3. #include <AK/StringBuilder.h>
  4. #include <AK/Time.h>
  5. #include <AK/Types.h>
  6. #include <Kernel/Arch/i386/CPU.h>
  7. #include <Kernel/Arch/i386/PIT.h>
  8. #include <Kernel/Console.h>
  9. #include <Kernel/Devices/KeyboardDevice.h>
  10. #include <Kernel/Devices/NullDevice.h>
  11. #include <Kernel/Devices/PCSpeaker.h>
  12. #include <Kernel/Devices/RandomDevice.h>
  13. #include <Kernel/FileSystem/Custody.h>
  14. #include <Kernel/FileSystem/DevPtsFS.h>
  15. #include <Kernel/FileSystem/Ext2FileSystem.h>
  16. #include <Kernel/FileSystem/FIFO.h>
  17. #include <Kernel/FileSystem/FileDescription.h>
  18. #include <Kernel/FileSystem/InodeWatcher.h>
  19. #include <Kernel/FileSystem/ProcFS.h>
  20. #include <Kernel/FileSystem/TmpFS.h>
  21. #include <Kernel/FileSystem/VirtualFileSystem.h>
  22. #include <Kernel/Heap/kmalloc.h>
  23. #include <Kernel/IO.h>
  24. #include <Kernel/KBufferBuilder.h>
  25. #include <Kernel/KSyms.h>
  26. #include <Kernel/KernelInfoPage.h>
  27. #include <Kernel/Module.h>
  28. #include <Kernel/Multiboot.h>
  29. #include <Kernel/Net/Socket.h>
  30. #include <Kernel/Process.h>
  31. #include <Kernel/ProcessTracer.h>
  32. #include <Kernel/Profiling.h>
  33. #include <Kernel/RTC.h>
  34. #include <Kernel/Random.h>
  35. #include <Kernel/Scheduler.h>
  36. #include <Kernel/SharedBuffer.h>
  37. #include <Kernel/StdLib.h>
  38. #include <Kernel/Syscall.h>
  39. #include <Kernel/TTY/MasterPTY.h>
  40. #include <Kernel/Thread.h>
  41. #include <Kernel/VM/InodeVMObject.h>
  42. #include <Kernel/VM/PurgeableVMObject.h>
  43. #include <LibC/errno_numbers.h>
  44. #include <LibC/limits.h>
  45. #include <LibC/signal_numbers.h>
  46. #include <LibELF/ELFLoader.h>
  47. //#define DEBUG_POLL_SELECT
  48. //#define DEBUG_IO
  49. //#define TASK_DEBUG
  50. //#define FORK_DEBUG
  51. //#define EXEC_DEBUG
  52. //#define SIGNAL_DEBUG
  53. //#define SHARED_BUFFER_DEBUG
  54. static void create_signal_trampolines();
  55. static void create_kernel_info_page();
  56. static pid_t next_pid;
  57. InlineLinkedList<Process>* g_processes;
  58. static String* s_hostname;
  59. static Lock* s_hostname_lock;
  60. static VirtualAddress s_info_page_address_for_userspace;
  61. static VirtualAddress s_info_page_address_for_kernel;
  62. VirtualAddress g_return_to_ring3_from_signal_trampoline;
  63. HashMap<String, OwnPtr<Module>>* g_modules;
  64. pid_t Process::allocate_pid()
  65. {
  66. InterruptDisabler disabler;
  67. return next_pid++;
  68. }
  69. void Process::initialize()
  70. {
  71. g_modules = new HashMap<String, OwnPtr<Module>>;
  72. next_pid = 0;
  73. g_processes = new InlineLinkedList<Process>;
  74. s_hostname = new String("courage");
  75. s_hostname_lock = new Lock;
  76. create_signal_trampolines();
  77. create_kernel_info_page();
  78. }
  79. void Process::update_info_page_timestamp(const timeval& tv)
  80. {
  81. auto* info_page = (KernelInfoPage*)s_info_page_address_for_kernel.as_ptr();
  82. info_page->serial++;
  83. const_cast<timeval&>(info_page->now) = tv;
  84. }
  85. Vector<pid_t> Process::all_pids()
  86. {
  87. Vector<pid_t> pids;
  88. InterruptDisabler disabler;
  89. pids.ensure_capacity((int)g_processes->size_slow());
  90. for (auto& process : *g_processes)
  91. pids.append(process.pid());
  92. return pids;
  93. }
  94. Vector<Process*> Process::all_processes()
  95. {
  96. Vector<Process*> processes;
  97. InterruptDisabler disabler;
  98. processes.ensure_capacity((int)g_processes->size_slow());
  99. for (auto& process : *g_processes)
  100. processes.append(&process);
  101. return processes;
  102. }
  103. bool Process::in_group(gid_t gid) const
  104. {
  105. return m_gid == gid || m_extra_gids.contains(gid);
  106. }
  107. Range Process::allocate_range(VirtualAddress vaddr, size_t size)
  108. {
  109. vaddr.mask(PAGE_MASK);
  110. size = PAGE_ROUND_UP(size);
  111. if (vaddr.is_null())
  112. return page_directory().range_allocator().allocate_anywhere(size);
  113. return page_directory().range_allocator().allocate_specific(vaddr, size);
  114. }
  115. static unsigned prot_to_region_access_flags(int prot)
  116. {
  117. unsigned access = 0;
  118. if (prot & PROT_READ)
  119. access |= Region::Access::Read;
  120. if (prot & PROT_WRITE)
  121. access |= Region::Access::Write;
  122. if (prot & PROT_EXEC)
  123. access |= Region::Access::Execute;
  124. return access;
  125. }
  126. Region& Process::allocate_split_region(const Region& source_region, const Range& range, size_t offset_in_vmobject)
  127. {
  128. m_regions.append(Region::create_user_accessible(range, source_region.vmobject(), offset_in_vmobject, source_region.name(), source_region.access()));
  129. return m_regions.last();
  130. }
  131. Region* Process::allocate_region(VirtualAddress vaddr, size_t size, const String& name, int prot, bool commit)
  132. {
  133. auto range = allocate_range(vaddr, size);
  134. if (!range.is_valid())
  135. return nullptr;
  136. m_regions.append(Region::create_user_accessible(range, name, prot_to_region_access_flags(prot)));
  137. m_regions.last().map(page_directory());
  138. if (commit)
  139. m_regions.last().commit();
  140. return &m_regions.last();
  141. }
  142. Region* Process::allocate_file_backed_region(VirtualAddress vaddr, size_t size, NonnullRefPtr<Inode> inode, const String& name, int prot)
  143. {
  144. auto range = allocate_range(vaddr, size);
  145. if (!range.is_valid())
  146. return nullptr;
  147. m_regions.append(Region::create_user_accessible(range, inode, name, prot_to_region_access_flags(prot)));
  148. m_regions.last().map(page_directory());
  149. return &m_regions.last();
  150. }
  151. Region* Process::allocate_region_with_vmobject(VirtualAddress vaddr, size_t size, NonnullRefPtr<VMObject> vmobject, size_t offset_in_vmobject, const String& name, int prot, bool user_accessible)
  152. {
  153. auto range = allocate_range(vaddr, size);
  154. if (!range.is_valid())
  155. return nullptr;
  156. offset_in_vmobject &= PAGE_MASK;
  157. if (user_accessible)
  158. m_regions.append(Region::create_user_accessible(range, move(vmobject), offset_in_vmobject, name, prot_to_region_access_flags(prot)));
  159. else
  160. m_regions.append(Region::create_kernel_only(range, move(vmobject), offset_in_vmobject, name, prot_to_region_access_flags(prot)));
  161. m_regions.last().map(page_directory());
  162. return &m_regions.last();
  163. }
  164. bool Process::deallocate_region(Region& region)
  165. {
  166. InterruptDisabler disabler;
  167. for (int i = 0; i < m_regions.size(); ++i) {
  168. if (&m_regions[i] == &region) {
  169. m_regions.remove(i);
  170. return true;
  171. }
  172. }
  173. return false;
  174. }
  175. Region* Process::region_from_range(const Range& range)
  176. {
  177. size_t size = PAGE_ROUND_UP(range.size());
  178. for (auto& region : m_regions) {
  179. if (region.vaddr() == range.base() && region.size() == size)
  180. return &region;
  181. }
  182. return nullptr;
  183. }
  184. Region* Process::region_containing(const Range& range)
  185. {
  186. for (auto& region : m_regions) {
  187. if (region.contains(range))
  188. return &region;
  189. }
  190. return nullptr;
  191. }
  192. int Process::sys$set_mmap_name(const Syscall::SC_set_mmap_name_params* user_params)
  193. {
  194. REQUIRE_PROMISE(stdio);
  195. if (!validate_read_typed(user_params))
  196. return -EFAULT;
  197. Syscall::SC_set_mmap_name_params params;
  198. copy_from_user(&params, user_params, sizeof(params));
  199. auto name = validate_and_copy_string_from_user(params.name);
  200. if (name.is_null())
  201. return -EFAULT;
  202. auto* region = region_from_range({ VirtualAddress((u32)params.addr), params.size });
  203. if (!region)
  204. return -EINVAL;
  205. if (!region->is_mmap())
  206. return -EPERM;
  207. region->set_name(name);
  208. return 0;
  209. }
  210. static bool validate_mmap_prot(int prot, bool map_stack)
  211. {
  212. bool readable = prot & PROT_READ;
  213. bool writable = prot & PROT_WRITE;
  214. bool executable = prot & PROT_EXEC;
  215. if (writable && executable)
  216. return false;
  217. if (map_stack) {
  218. if (executable)
  219. return false;
  220. if (!readable || !writable)
  221. return false;
  222. }
  223. return true;
  224. }
  225. static bool validate_inode_mmap_prot(const Process& process, int prot, const Inode& inode)
  226. {
  227. auto metadata = inode.metadata();
  228. if ((prot & PROT_WRITE) && !metadata.may_write(process))
  229. return false;
  230. if ((prot & PROT_READ) && !metadata.may_read(process))
  231. return false;
  232. return true;
  233. }
  234. // Carve out a virtual address range from a region and return the two regions on either side
  235. Vector<Region*, 2> Process::split_region_around_range(const Region& source_region, const Range& desired_range)
  236. {
  237. Range old_region_range = source_region.range();
  238. auto remaining_ranges_after_unmap = old_region_range.carve(desired_range);
  239. ASSERT(!remaining_ranges_after_unmap.is_empty());
  240. auto make_replacement_region = [&](const Range& new_range) -> Region& {
  241. ASSERT(new_range.base() >= old_region_range.base());
  242. ASSERT(new_range.end() <= old_region_range.end());
  243. size_t new_range_offset_in_vmobject = source_region.offset_in_vmobject() + (new_range.base().get() - old_region_range.base().get());
  244. return allocate_split_region(source_region, new_range, new_range_offset_in_vmobject);
  245. };
  246. Vector<Region*, 2> new_regions;
  247. for (auto& new_range : remaining_ranges_after_unmap) {
  248. new_regions.unchecked_append(&make_replacement_region(new_range));
  249. }
  250. return new_regions;
  251. }
  252. void* Process::sys$mmap(const Syscall::SC_mmap_params* user_params)
  253. {
  254. REQUIRE_PROMISE(stdio);
  255. if (!validate_read_typed(user_params))
  256. return (void*)-EFAULT;
  257. Syscall::SC_mmap_params params;
  258. copy_from_user(&params, user_params, sizeof(params));
  259. void* addr = (void*)params.addr;
  260. size_t size = params.size;
  261. int prot = params.prot;
  262. int flags = params.flags;
  263. int fd = params.fd;
  264. int offset = params.offset;
  265. String name;
  266. if (params.name.characters) {
  267. name = validate_and_copy_string_from_user(params.name);
  268. if (name.is_null())
  269. return (void*)-EFAULT;
  270. }
  271. if (size == 0)
  272. return (void*)-EINVAL;
  273. if ((u32)addr & ~PAGE_MASK)
  274. return (void*)-EINVAL;
  275. bool map_shared = flags & MAP_SHARED;
  276. bool map_anonymous = flags & MAP_ANONYMOUS;
  277. bool map_purgeable = flags & MAP_PURGEABLE;
  278. bool map_private = flags & MAP_PRIVATE;
  279. bool map_stack = flags & MAP_STACK;
  280. bool map_fixed = flags & MAP_FIXED;
  281. if (map_shared && map_private)
  282. return (void*)-EINVAL;
  283. if (!map_shared && !map_private)
  284. return (void*)-EINVAL;
  285. if (!validate_mmap_prot(prot, map_stack))
  286. return (void*)-EINVAL;
  287. if (map_stack && (!map_private || !map_anonymous))
  288. return (void*)-EINVAL;
  289. Region* region = nullptr;
  290. if (map_purgeable) {
  291. auto vmobject = PurgeableVMObject::create_with_size(size);
  292. region = allocate_region_with_vmobject(VirtualAddress((u32)addr), size, vmobject, 0, !name.is_null() ? name : "mmap (purgeable)", prot);
  293. if (!region && (!map_fixed && addr != 0))
  294. region = allocate_region_with_vmobject({}, size, vmobject, 0, !name.is_null() ? name : "mmap (purgeable)", prot);
  295. } else if (map_anonymous) {
  296. region = allocate_region(VirtualAddress((u32)addr), size, !name.is_null() ? name : "mmap", prot, false);
  297. if (!region && (!map_fixed && addr != 0))
  298. region = allocate_region({}, size, !name.is_null() ? name : "mmap", prot, false);
  299. } else {
  300. if (offset < 0)
  301. return (void*)-EINVAL;
  302. if (static_cast<size_t>(offset) & ~PAGE_MASK)
  303. return (void*)-EINVAL;
  304. // FIXME: Implement MAP_PRIVATE for FileDescription-backed mmap
  305. if (map_private)
  306. return (void*)-ENOTSUP;
  307. auto description = file_description(fd);
  308. if (!description)
  309. return (void*)-EBADF;
  310. if (description->is_directory())
  311. return (void*)-ENODEV;
  312. if ((prot & PROT_READ) && !description->is_readable())
  313. return (void*)-EACCES;
  314. if ((prot & PROT_WRITE) && !description->is_writable())
  315. return (void*)-EACCES;
  316. if (description->inode()) {
  317. if (!validate_inode_mmap_prot(*this, prot, *description->inode()))
  318. return (void*)-EACCES;
  319. }
  320. auto region_or_error = description->mmap(*this, VirtualAddress((u32)addr), static_cast<size_t>(offset), size, prot);
  321. if (region_or_error.is_error()) {
  322. // Fail if MAP_FIXED or address is 0, retry otherwise
  323. if (map_fixed || addr == 0)
  324. return (void*)(int)region_or_error.error();
  325. region_or_error = description->mmap(*this, {}, static_cast<size_t>(offset), size, prot);
  326. }
  327. if (region_or_error.is_error())
  328. return (void*)(int)region_or_error.error();
  329. region = region_or_error.value();
  330. }
  331. if (!region)
  332. return (void*)-ENOMEM;
  333. region->set_mmap(true);
  334. if (map_shared)
  335. region->set_shared(true);
  336. if (map_stack)
  337. region->set_stack(true);
  338. if (!name.is_null())
  339. region->set_name(name);
  340. return region->vaddr().as_ptr();
  341. }
  342. int Process::sys$munmap(void* addr, size_t size)
  343. {
  344. REQUIRE_PROMISE(stdio);
  345. Range range_to_unmap { VirtualAddress((u32)addr), size };
  346. if (auto* whole_region = region_from_range(range_to_unmap)) {
  347. if (!whole_region->is_mmap())
  348. return -EPERM;
  349. bool success = deallocate_region(*whole_region);
  350. ASSERT(success);
  351. return 0;
  352. }
  353. if (auto* old_region = region_containing(range_to_unmap)) {
  354. if (!old_region->is_mmap())
  355. return -EPERM;
  356. auto new_regions = split_region_around_range(*old_region, range_to_unmap);
  357. // We manually unmap the old region here, specifying that we *don't* want the VM deallocated.
  358. old_region->unmap(Region::ShouldDeallocateVirtualMemoryRange::No);
  359. deallocate_region(*old_region);
  360. // Instead we give back the unwanted VM manually.
  361. page_directory().range_allocator().deallocate(range_to_unmap);
  362. // And finally we map the new region(s) using our page directory (they were just allocated and don't have one).
  363. for (auto* new_region : new_regions) {
  364. new_region->map(page_directory());
  365. }
  366. return 0;
  367. }
  368. // FIXME: We should also support munmap() across multiple regions. (#175)
  369. return -EINVAL;
  370. }
  371. int Process::sys$mprotect(void* addr, size_t size, int prot)
  372. {
  373. REQUIRE_PROMISE(stdio);
  374. Range range_to_mprotect = { VirtualAddress((u32)addr), size };
  375. if (auto* whole_region = region_from_range(range_to_mprotect)) {
  376. if (!whole_region->is_mmap())
  377. return -EPERM;
  378. if (!validate_mmap_prot(prot, whole_region->is_stack()))
  379. return -EINVAL;
  380. if (whole_region->access() == prot_to_region_access_flags(prot))
  381. return 0;
  382. if (whole_region->vmobject().is_inode()
  383. && !validate_inode_mmap_prot(*this, prot, static_cast<const InodeVMObject&>(whole_region->vmobject()).inode())) {
  384. return -EACCES;
  385. }
  386. whole_region->set_readable(prot & PROT_READ);
  387. whole_region->set_writable(prot & PROT_WRITE);
  388. whole_region->set_executable(prot & PROT_EXEC);
  389. whole_region->remap();
  390. return 0;
  391. }
  392. // Check if we can carve out the desired range from an existing region
  393. if (auto* old_region = region_containing(range_to_mprotect)) {
  394. if (!old_region->is_mmap())
  395. return -EPERM;
  396. if (!validate_mmap_prot(prot, old_region->is_stack()))
  397. return -EINVAL;
  398. if (old_region->access() == prot_to_region_access_flags(prot))
  399. return 0;
  400. if (old_region->vmobject().is_inode()
  401. && !validate_inode_mmap_prot(*this, prot, static_cast<const InodeVMObject&>(old_region->vmobject()).inode())) {
  402. return -EACCES;
  403. }
  404. // This vector is the region(s) adjacent to our range.
  405. // We need to allocate a new region for the range we wanted to change permission bits on.
  406. auto adjacent_regions = split_region_around_range(*old_region, range_to_mprotect);
  407. size_t new_range_offset_in_vmobject = old_region->offset_in_vmobject() + (range_to_mprotect.base().get() - old_region->range().base().get());
  408. auto& new_region = allocate_split_region(*old_region, range_to_mprotect, new_range_offset_in_vmobject);
  409. new_region.set_readable(prot & PROT_READ);
  410. new_region.set_writable(prot & PROT_WRITE);
  411. new_region.set_executable(prot & PROT_EXEC);
  412. // Unmap the old region here, specifying that we *don't* want the VM deallocated.
  413. old_region->unmap(Region::ShouldDeallocateVirtualMemoryRange::No);
  414. deallocate_region(*old_region);
  415. // Map the new regions using our page directory (they were just allocated and don't have one).
  416. for (auto* adjacent_region : adjacent_regions) {
  417. adjacent_region->map(page_directory());
  418. }
  419. new_region.map(page_directory());
  420. return 0;
  421. }
  422. // FIXME: We should also support mprotect() across multiple regions. (#175) (#964)
  423. return -EINVAL;
  424. }
  425. int Process::sys$madvise(void* address, size_t size, int advice)
  426. {
  427. REQUIRE_PROMISE(stdio);
  428. auto* region = region_from_range({ VirtualAddress((u32)address), size });
  429. if (!region)
  430. return -EINVAL;
  431. if (!region->is_mmap())
  432. return -EPERM;
  433. if ((advice & MADV_SET_VOLATILE) && (advice & MADV_SET_NONVOLATILE))
  434. return -EINVAL;
  435. if (advice & MADV_SET_VOLATILE) {
  436. if (!region->vmobject().is_purgeable())
  437. return -EPERM;
  438. auto& vmobject = static_cast<PurgeableVMObject&>(region->vmobject());
  439. vmobject.set_volatile(true);
  440. return 0;
  441. }
  442. if (advice & MADV_SET_NONVOLATILE) {
  443. if (!region->vmobject().is_purgeable())
  444. return -EPERM;
  445. auto& vmobject = static_cast<PurgeableVMObject&>(region->vmobject());
  446. if (!vmobject.is_volatile())
  447. return 0;
  448. vmobject.set_volatile(false);
  449. bool was_purged = vmobject.was_purged();
  450. vmobject.set_was_purged(false);
  451. return was_purged ? 1 : 0;
  452. }
  453. if (advice & MADV_GET_VOLATILE) {
  454. if (!region->vmobject().is_purgeable())
  455. return -EPERM;
  456. auto& vmobject = static_cast<PurgeableVMObject&>(region->vmobject());
  457. return vmobject.is_volatile() ? 0 : 1;
  458. }
  459. return -EINVAL;
  460. }
  461. int Process::sys$purge(int mode)
  462. {
  463. REQUIRE_NO_PROMISES;
  464. if (!is_superuser())
  465. return -EPERM;
  466. int purged_page_count = 0;
  467. if (mode & PURGE_ALL_VOLATILE) {
  468. NonnullRefPtrVector<PurgeableVMObject> vmobjects;
  469. {
  470. InterruptDisabler disabler;
  471. MM.for_each_vmobject([&](auto& vmobject) {
  472. if (vmobject.is_purgeable())
  473. vmobjects.append(static_cast<PurgeableVMObject&>(vmobject));
  474. return IterationDecision::Continue;
  475. });
  476. }
  477. for (auto& vmobject : vmobjects) {
  478. purged_page_count += vmobject.purge();
  479. }
  480. }
  481. if (mode & PURGE_ALL_CLEAN_INODE) {
  482. NonnullRefPtrVector<InodeVMObject> vmobjects;
  483. {
  484. InterruptDisabler disabler;
  485. MM.for_each_vmobject([&](auto& vmobject) {
  486. if (vmobject.is_inode())
  487. vmobjects.append(static_cast<InodeVMObject&>(vmobject));
  488. return IterationDecision::Continue;
  489. });
  490. }
  491. for (auto& vmobject : vmobjects) {
  492. purged_page_count += vmobject.release_all_clean_pages();
  493. }
  494. }
  495. return purged_page_count;
  496. }
  497. int Process::sys$gethostname(char* buffer, ssize_t size)
  498. {
  499. REQUIRE_PROMISE(stdio);
  500. if (size < 0)
  501. return -EINVAL;
  502. if (!validate_write(buffer, size))
  503. return -EFAULT;
  504. LOCKER(*s_hostname_lock);
  505. if ((size_t)size < (s_hostname->length() + 1))
  506. return -ENAMETOOLONG;
  507. copy_to_user(buffer, s_hostname->characters(), s_hostname->length() + 1);
  508. return 0;
  509. }
  510. pid_t Process::sys$fork(RegisterDump& regs)
  511. {
  512. REQUIRE_PROMISE(proc);
  513. Thread* child_first_thread = nullptr;
  514. auto* child = new Process(child_first_thread, m_name, m_uid, m_gid, m_pid, m_ring, m_cwd, m_executable, m_tty, this);
  515. child->m_root_directory = m_root_directory;
  516. child->m_promises = m_promises;
  517. child->m_execpromises = m_execpromises;
  518. #ifdef FORK_DEBUG
  519. dbgprintf("fork: child=%p\n", child);
  520. #endif
  521. for (auto& region : m_regions) {
  522. #ifdef FORK_DEBUG
  523. dbg() << "fork: cloning Region{" << &region << "} '" << region.name() << "' @ " << region.vaddr();
  524. #endif
  525. child->m_regions.append(region.clone());
  526. child->m_regions.last().map(child->page_directory());
  527. if (&region == m_master_tls_region)
  528. child->m_master_tls_region = &child->m_regions.last();
  529. }
  530. child->m_extra_gids = m_extra_gids;
  531. auto& child_tss = child_first_thread->m_tss;
  532. child_tss.eax = 0; // fork() returns 0 in the child :^)
  533. child_tss.ebx = regs.ebx;
  534. child_tss.ecx = regs.ecx;
  535. child_tss.edx = regs.edx;
  536. child_tss.ebp = regs.ebp;
  537. child_tss.esp = regs.userspace_esp;
  538. child_tss.esi = regs.esi;
  539. child_tss.edi = regs.edi;
  540. child_tss.eflags = regs.eflags;
  541. child_tss.eip = regs.eip;
  542. child_tss.cs = regs.cs;
  543. child_tss.ds = regs.ds;
  544. child_tss.es = regs.es;
  545. child_tss.fs = regs.fs;
  546. child_tss.gs = regs.gs;
  547. child_tss.ss = regs.userspace_ss;
  548. #ifdef FORK_DEBUG
  549. 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);
  550. #endif
  551. {
  552. InterruptDisabler disabler;
  553. g_processes->prepend(child);
  554. }
  555. #ifdef TASK_DEBUG
  556. kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child_tss.eip);
  557. #endif
  558. child_first_thread->set_state(Thread::State::Skip1SchedulerPass);
  559. return child->pid();
  560. }
  561. int Process::do_exec(String path, Vector<String> arguments, Vector<String> environment)
  562. {
  563. ASSERT(is_ring3());
  564. dbgprintf("%s(%d) do_exec(%s): thread_count() = %d\n", m_name.characters(), m_pid, path.characters(), thread_count());
  565. // FIXME(Thread): Kill any threads the moment we commit to the exec().
  566. if (thread_count() != 1) {
  567. dbgprintf("Gonna die because I have many threads! These are the threads:\n");
  568. for_each_thread([](Thread& thread) {
  569. dbgprintf("Thread{%p}: TID=%d, PID=%d\n", &thread, thread.tid(), thread.pid());
  570. return IterationDecision::Continue;
  571. });
  572. ASSERT(thread_count() == 1);
  573. ASSERT_NOT_REACHED();
  574. }
  575. size_t total_blob_size = 0;
  576. for (auto& a : arguments)
  577. total_blob_size += a.length() + 1;
  578. for (auto& e : environment)
  579. total_blob_size += e.length() + 1;
  580. size_t total_meta_size = sizeof(char*) * (arguments.size() + 1) + sizeof(char*) * (environment.size() + 1);
  581. // FIXME: How much stack space does process startup need?
  582. if ((total_blob_size + total_meta_size) >= Thread::default_userspace_stack_size)
  583. return -E2BIG;
  584. auto parts = path.split('/');
  585. if (parts.is_empty())
  586. return -ENOENT;
  587. auto result = VFS::the().open(path, O_EXEC, 0, current_directory());
  588. if (result.is_error())
  589. return result.error();
  590. auto description = result.value();
  591. auto metadata = description->metadata();
  592. if (!metadata.size)
  593. return -ENOTIMPL;
  594. u32 entry_eip = 0;
  595. // FIXME: Is there a race here?
  596. auto old_page_directory = move(m_page_directory);
  597. m_page_directory = PageDirectory::create_for_userspace(*this);
  598. #ifdef MM_DEBUG
  599. dbgprintf("Process %u exec: PD=%x created\n", pid(), m_page_directory.ptr());
  600. #endif
  601. ProcessPagingScope paging_scope(*this);
  602. ASSERT(description->inode());
  603. auto vmobject = InodeVMObject::create_with_inode(*description->inode());
  604. auto* region = allocate_region_with_vmobject(VirtualAddress(), metadata.size, vmobject, 0, description->absolute_path(), PROT_READ, false);
  605. ASSERT(region);
  606. // NOTE: We yank this out of 'm_regions' since we're about to manipulate the vector
  607. // and we don't want it getting lost.
  608. auto executable_region = m_regions.take_last();
  609. Region* master_tls_region { nullptr };
  610. size_t master_tls_size = 0;
  611. size_t master_tls_alignment = 0;
  612. OwnPtr<ELFLoader> loader;
  613. {
  614. // Okay, here comes the sleight of hand, pay close attention..
  615. auto old_regions = move(m_regions);
  616. m_regions.append(move(executable_region));
  617. loader = make<ELFLoader>(region->vaddr().as_ptr(), metadata.size);
  618. 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) -> u8* {
  619. ASSERT(size);
  620. ASSERT(alignment == PAGE_SIZE);
  621. int prot = 0;
  622. if (is_readable)
  623. prot |= PROT_READ;
  624. if (is_writable)
  625. prot |= PROT_WRITE;
  626. if (is_executable)
  627. prot |= PROT_EXEC;
  628. if (!allocate_region_with_vmobject(vaddr, size, vmobject, offset_in_image, String(name), prot))
  629. return nullptr;
  630. return vaddr.as_ptr();
  631. };
  632. loader->alloc_section_hook = [&](VirtualAddress vaddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) -> u8* {
  633. ASSERT(size);
  634. ASSERT(alignment == PAGE_SIZE);
  635. int prot = 0;
  636. if (is_readable)
  637. prot |= PROT_READ;
  638. if (is_writable)
  639. prot |= PROT_WRITE;
  640. if (!allocate_region(vaddr, size, String(name), prot))
  641. return nullptr;
  642. return vaddr.as_ptr();
  643. };
  644. loader->tls_section_hook = [&](size_t size, size_t alignment) {
  645. ASSERT(size);
  646. master_tls_region = allocate_region({}, size, String(), PROT_READ | PROT_WRITE);
  647. master_tls_size = size;
  648. master_tls_alignment = alignment;
  649. return master_tls_region->vaddr().as_ptr();
  650. };
  651. bool success = loader->load();
  652. if (!success || !loader->entry().get()) {
  653. m_page_directory = move(old_page_directory);
  654. // FIXME: RAII this somehow instead.
  655. ASSERT(&current->process() == this);
  656. MM.enter_process_paging_scope(*this);
  657. executable_region = m_regions.take_first();
  658. m_regions = move(old_regions);
  659. kprintf("do_exec: Failure loading %s\n", path.characters());
  660. return -ENOEXEC;
  661. }
  662. // NOTE: At this point, we've committed to the new executable.
  663. entry_eip = loader->entry().get();
  664. #ifdef EXEC_DEBUG
  665. kprintf("Memory layout after ELF load:");
  666. dump_regions();
  667. #endif
  668. }
  669. m_elf_loader = move(loader);
  670. m_executable = description->custody();
  671. m_promises = m_execpromises;
  672. // Copy of the master TLS region that we will clone for new threads
  673. m_master_tls_region = master_tls_region;
  674. if (!(description->custody()->mount_flags() & MS_NOSUID)) {
  675. if (metadata.is_setuid())
  676. m_euid = metadata.uid;
  677. if (metadata.is_setgid())
  678. m_egid = metadata.gid;
  679. }
  680. current->set_default_signal_dispositions();
  681. current->m_signal_mask = 0;
  682. current->m_pending_signals = 0;
  683. for (int i = 0; i < m_fds.size(); ++i) {
  684. auto& daf = m_fds[i];
  685. if (daf.description && daf.flags & FD_CLOEXEC) {
  686. daf.description->close();
  687. daf = {};
  688. }
  689. }
  690. // FIXME: Should we just make a new Thread here instead?
  691. Thread* new_main_thread = nullptr;
  692. if (&current->process() == this) {
  693. new_main_thread = current;
  694. } else {
  695. for_each_thread([&](auto& thread) {
  696. new_main_thread = &thread;
  697. return IterationDecision::Break;
  698. });
  699. }
  700. ASSERT(new_main_thread);
  701. // NOTE: We create the new stack before disabling interrupts since it will zero-fault
  702. // and we don't want to deal with faults after this point.
  703. u32 new_userspace_esp = new_main_thread->make_userspace_stack_for_main_thread(move(arguments), move(environment));
  704. // We cli() manually here because we don't want to get interrupted between do_exec() and Schedule::yield().
  705. // The reason is that the task redirection we've set up above will be clobbered by the timer IRQ.
  706. // If we used an InterruptDisabler that sti()'d on exit, we might timer tick'd too soon in exec().
  707. if (&current->process() == this)
  708. cli();
  709. // NOTE: Be careful to not trigger any page faults below!
  710. Scheduler::prepare_to_modify_tss(*new_main_thread);
  711. m_name = parts.take_last();
  712. new_main_thread->set_name(m_name);
  713. auto& tss = new_main_thread->m_tss;
  714. u32 old_esp0 = tss.esp0;
  715. m_master_tls_size = master_tls_size;
  716. m_master_tls_alignment = master_tls_alignment;
  717. new_main_thread->make_thread_specific_region({});
  718. memset(&tss, 0, sizeof(TSS32));
  719. tss.iomapbase = sizeof(TSS32);
  720. tss.eflags = 0x0202;
  721. tss.eip = entry_eip;
  722. tss.cs = 0x1b;
  723. tss.ds = 0x23;
  724. tss.es = 0x23;
  725. tss.fs = 0x23;
  726. tss.gs = thread_specific_selector() | 3;
  727. tss.ss = 0x23;
  728. tss.cr3 = page_directory().cr3();
  729. tss.esp = new_userspace_esp;
  730. tss.ss0 = 0x10;
  731. tss.esp0 = old_esp0;
  732. tss.ss2 = m_pid;
  733. #ifdef TASK_DEBUG
  734. kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), path.characters(), tss.eip);
  735. #endif
  736. new_main_thread->set_state(Thread::State::Skip1SchedulerPass);
  737. big_lock().unlock_if_locked();
  738. return 0;
  739. }
  740. KResultOr<Vector<String>> Process::find_shebang_interpreter_for_executable(const String& executable_path)
  741. {
  742. // FIXME: It's a bit sad that we'll open the executable twice (in case there's no shebang)
  743. // Maybe we can find a way to plumb this opened FileDescription to the rest of the
  744. // exec implementation..
  745. auto result = VFS::the().open(executable_path, 0, 0, current_directory());
  746. if (result.is_error())
  747. return result.error();
  748. auto description = result.value();
  749. auto metadata = description->metadata();
  750. if (!metadata.may_execute(*this))
  751. return KResult(-EACCES);
  752. if (metadata.size < 3)
  753. return KResult(-ENOEXEC);
  754. char first_page[PAGE_SIZE];
  755. int nread = description->read((u8*)&first_page, sizeof(first_page));
  756. int word_start = 2;
  757. int word_length = 0;
  758. if (nread > 2 && first_page[0] == '#' && first_page[1] == '!') {
  759. Vector<String> interpreter_words;
  760. for (int i = 2; i < nread; ++i) {
  761. if (first_page[i] == '\n') {
  762. break;
  763. }
  764. if (first_page[i] != ' ') {
  765. ++word_length;
  766. }
  767. if (first_page[i] == ' ') {
  768. if (word_length > 0) {
  769. interpreter_words.append(String(&first_page[word_start], word_length));
  770. }
  771. word_length = 0;
  772. word_start = i + 1;
  773. }
  774. }
  775. if (word_length > 0)
  776. interpreter_words.append(String(&first_page[word_start], word_length));
  777. if (!interpreter_words.is_empty())
  778. return interpreter_words;
  779. }
  780. return KResult(-ENOEXEC);
  781. }
  782. int Process::exec(String path, Vector<String> arguments, Vector<String> environment)
  783. {
  784. auto result = find_shebang_interpreter_for_executable(path);
  785. if (!result.is_error()) {
  786. Vector<String> new_arguments(result.value());
  787. new_arguments.append(path);
  788. arguments.remove(0);
  789. new_arguments.append(move(arguments));
  790. return exec(result.value().first(), move(new_arguments), move(environment));
  791. }
  792. // The bulk of exec() is done by do_exec(), which ensures that all locals
  793. // are cleaned up by the time we yield-teleport below.
  794. int rc = do_exec(move(path), move(arguments), move(environment));
  795. if (rc < 0)
  796. return rc;
  797. if (&current->process() == this) {
  798. Scheduler::yield();
  799. ASSERT_NOT_REACHED();
  800. }
  801. return 0;
  802. }
  803. int Process::sys$execve(const Syscall::SC_execve_params* user_params)
  804. {
  805. REQUIRE_PROMISE(exec);
  806. // NOTE: Be extremely careful with allocating any kernel memory in exec().
  807. // On success, the kernel stack will be lost.
  808. Syscall::SC_execve_params params;
  809. if (!validate_read_typed(user_params))
  810. return -EFAULT;
  811. copy_from_user(&params, user_params, sizeof(params));
  812. if (params.arguments.length > ARG_MAX || params.environment.length > ARG_MAX)
  813. return -E2BIG;
  814. auto path = validate_and_copy_string_from_user(params.path);
  815. if (path.is_null())
  816. return -EFAULT;
  817. if (path.is_empty())
  818. return -ENOENT;
  819. auto copy_user_strings = [&](const auto& list, auto& output) {
  820. if (!list.length)
  821. return true;
  822. if (!validate_read_typed(list.strings, list.length))
  823. return false;
  824. Vector<Syscall::StringArgument, 32> strings;
  825. strings.resize(list.length);
  826. copy_from_user(strings.data(), list.strings, list.length * sizeof(Syscall::StringArgument));
  827. for (size_t i = 0; i < list.length; ++i) {
  828. if (!validate_read(strings[i].characters, strings[i].length))
  829. return false;
  830. output.append(copy_string_from_user(strings[i].characters, strings[i].length));
  831. }
  832. return true;
  833. };
  834. Vector<String> arguments;
  835. if (!copy_user_strings(params.arguments, arguments))
  836. return -EFAULT;
  837. Vector<String> environment;
  838. if (!copy_user_strings(params.environment, environment))
  839. return -EFAULT;
  840. int rc = exec(move(path), move(arguments), move(environment));
  841. ASSERT(rc < 0); // We should never continue after a successful exec!
  842. return rc;
  843. }
  844. Process* Process::create_user_process(Thread*& first_thread, const String& path, uid_t uid, gid_t gid, pid_t parent_pid, int& error, Vector<String>&& arguments, Vector<String>&& environment, TTY* tty)
  845. {
  846. // FIXME: Don't split() the path twice (sys$spawn also does it...)
  847. auto parts = path.split('/');
  848. if (arguments.is_empty()) {
  849. arguments.append(parts.last());
  850. }
  851. RefPtr<Custody> cwd;
  852. RefPtr<Custody> root;
  853. {
  854. InterruptDisabler disabler;
  855. if (auto* parent = Process::from_pid(parent_pid)) {
  856. cwd = parent->m_cwd;
  857. root = parent->m_root_directory;
  858. }
  859. }
  860. if (!cwd)
  861. cwd = VFS::the().root_custody();
  862. if (!root)
  863. root = VFS::the().root_custody();
  864. auto* process = new Process(first_thread, parts.take_last(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
  865. error = process->exec(path, move(arguments), move(environment));
  866. if (error != 0) {
  867. delete process;
  868. return nullptr;
  869. }
  870. {
  871. InterruptDisabler disabler;
  872. g_processes->prepend(process);
  873. }
  874. #ifdef TASK_DEBUG
  875. kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), first_thread->tss().eip);
  876. #endif
  877. error = 0;
  878. return process;
  879. }
  880. Process* Process::create_kernel_process(Thread*& first_thread, String&& name, void (*e)())
  881. {
  882. auto* process = new Process(first_thread, move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
  883. first_thread->tss().eip = (u32)e;
  884. if (process->pid() != 0) {
  885. InterruptDisabler disabler;
  886. g_processes->prepend(process);
  887. #ifdef TASK_DEBUG
  888. kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), first_thread->tss().eip);
  889. #endif
  890. }
  891. first_thread->set_state(Thread::State::Runnable);
  892. return process;
  893. }
  894. Process::Process(Thread*& first_thread, const String& name, uid_t uid, gid_t gid, pid_t ppid, RingLevel ring, RefPtr<Custody> cwd, RefPtr<Custody> executable, TTY* tty, Process* fork_parent)
  895. : m_name(move(name))
  896. , m_pid(allocate_pid())
  897. , m_uid(uid)
  898. , m_gid(gid)
  899. , m_euid(uid)
  900. , m_egid(gid)
  901. , m_ring(ring)
  902. , m_executable(move(executable))
  903. , m_cwd(move(cwd))
  904. , m_tty(tty)
  905. , m_ppid(ppid)
  906. {
  907. dbgprintf("Process: New process PID=%u with name=%s\n", m_pid, m_name.characters());
  908. m_page_directory = PageDirectory::create_for_userspace(*this, fork_parent ? &fork_parent->page_directory().range_allocator() : nullptr);
  909. #ifdef MM_DEBUG
  910. dbgprintf("Process %u ctor: PD=%x created\n", pid(), m_page_directory.ptr());
  911. #endif
  912. // NOTE: fork() doesn't clone all threads; the thread that called fork() becomes the main thread in the new process.
  913. if (fork_parent)
  914. first_thread = current->clone(*this);
  915. else
  916. first_thread = new Thread(*this);
  917. //m_gids.set(m_gid);
  918. if (fork_parent) {
  919. m_sid = fork_parent->m_sid;
  920. m_pgid = fork_parent->m_pgid;
  921. } else {
  922. // FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
  923. InterruptDisabler disabler;
  924. if (auto* parent = Process::from_pid(m_ppid)) {
  925. m_sid = parent->m_sid;
  926. m_pgid = parent->m_pgid;
  927. }
  928. }
  929. if (fork_parent) {
  930. m_fds.resize(fork_parent->m_fds.size());
  931. for (int i = 0; i < fork_parent->m_fds.size(); ++i) {
  932. if (!fork_parent->m_fds[i].description)
  933. continue;
  934. #ifdef FORK_DEBUG
  935. 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());
  936. #endif
  937. m_fds[i] = fork_parent->m_fds[i];
  938. }
  939. } else {
  940. m_fds.resize(m_max_open_file_descriptors);
  941. auto& device_to_use_as_tty = tty ? (CharacterDevice&)*tty : NullDevice::the();
  942. m_fds[0].set(*device_to_use_as_tty.open(O_RDONLY).value());
  943. m_fds[1].set(*device_to_use_as_tty.open(O_WRONLY).value());
  944. m_fds[2].set(*device_to_use_as_tty.open(O_WRONLY).value());
  945. }
  946. if (fork_parent) {
  947. m_sid = fork_parent->m_sid;
  948. m_pgid = fork_parent->m_pgid;
  949. m_umask = fork_parent->m_umask;
  950. }
  951. }
  952. Process::~Process()
  953. {
  954. dbgprintf("~Process{%p} name=%s pid=%d, m_fds=%d, m_thread_count=%u\n", this, m_name.characters(), pid(), m_fds.size(), m_thread_count);
  955. ASSERT(thread_count() == 0);
  956. }
  957. void Process::dump_regions()
  958. {
  959. kprintf("Process %s(%u) regions:\n", name().characters(), pid());
  960. kprintf("BEGIN END SIZE ACCESS NAME\n");
  961. for (auto& region : m_regions) {
  962. kprintf("%08x -- %08x %08x %c%c%c%c%c%c %s\n",
  963. region.vaddr().get(),
  964. region.vaddr().offset(region.size() - 1).get(),
  965. region.size(),
  966. region.is_readable() ? 'R' : ' ',
  967. region.is_writable() ? 'W' : ' ',
  968. region.is_executable() ? 'X' : ' ',
  969. region.is_shared() ? 'S' : ' ',
  970. region.is_stack() ? 'T' : ' ',
  971. region.vmobject().is_purgeable() ? 'P' : ' ',
  972. region.name().characters());
  973. }
  974. }
  975. void Process::sys$exit(int status)
  976. {
  977. cli();
  978. #ifdef TASK_DEBUG
  979. kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
  980. #endif
  981. dump_backtrace();
  982. m_termination_status = status;
  983. m_termination_signal = 0;
  984. die();
  985. current->die_if_needed();
  986. ASSERT_NOT_REACHED();
  987. }
  988. void signal_trampoline_dummy(void)
  989. {
  990. // The trampoline preserves the current eax, pushes the signal code and
  991. // then calls the signal handler. We do this because, when interrupting a
  992. // blocking syscall, that syscall may return some special error code in eax;
  993. // This error code would likely be overwritten by the signal handler, so it's
  994. // neccessary to preserve it here.
  995. asm(
  996. ".intel_syntax noprefix\n"
  997. "asm_signal_trampoline:\n"
  998. "push ebp\n"
  999. "mov ebp, esp\n"
  1000. "push eax\n" // we have to store eax 'cause it might be the return value from a syscall
  1001. "sub esp, 4\n" // align the stack to 16 bytes
  1002. "mov eax, [ebp+12]\n" // push the signal code
  1003. "push eax\n"
  1004. "call [ebp+8]\n" // call the signal handler
  1005. "add esp, 8\n"
  1006. "mov eax, %P0\n"
  1007. "int 0x82\n" // sigreturn syscall
  1008. "asm_signal_trampoline_end:\n"
  1009. ".att_syntax" ::"i"(Syscall::SC_sigreturn));
  1010. }
  1011. extern "C" void asm_signal_trampoline(void);
  1012. extern "C" void asm_signal_trampoline_end(void);
  1013. void create_signal_trampolines()
  1014. {
  1015. InterruptDisabler disabler;
  1016. // NOTE: We leak this region.
  1017. auto* trampoline_region = MM.allocate_user_accessible_kernel_region(PAGE_SIZE, "Signal trampolines", Region::Access::Read | Region::Access::Write | Region::Access::Execute).leak_ptr();
  1018. g_return_to_ring3_from_signal_trampoline = trampoline_region->vaddr();
  1019. u8* trampoline = (u8*)asm_signal_trampoline;
  1020. u8* trampoline_end = (u8*)asm_signal_trampoline_end;
  1021. size_t trampoline_size = trampoline_end - trampoline;
  1022. u8* code_ptr = (u8*)trampoline_region->vaddr().as_ptr();
  1023. copy_to_user(code_ptr, trampoline, trampoline_size);
  1024. trampoline_region->set_writable(false);
  1025. trampoline_region->remap();
  1026. }
  1027. void create_kernel_info_page()
  1028. {
  1029. auto* info_page_region_for_userspace = MM.allocate_user_accessible_kernel_region(PAGE_SIZE, "Kernel info page", Region::Access::Read).leak_ptr();
  1030. auto* info_page_region_for_kernel = MM.allocate_kernel_region_with_vmobject(info_page_region_for_userspace->vmobject(), PAGE_SIZE, "Kernel info page", Region::Access::Read | Region::Access::Write).leak_ptr();
  1031. s_info_page_address_for_userspace = info_page_region_for_userspace->vaddr();
  1032. s_info_page_address_for_kernel = info_page_region_for_kernel->vaddr();
  1033. memset(s_info_page_address_for_kernel.as_ptr(), 0, PAGE_SIZE);
  1034. }
  1035. int Process::sys$sigreturn(RegisterDump& registers)
  1036. {
  1037. REQUIRE_PROMISE(stdio);
  1038. SmapDisabler disabler;
  1039. //Here, we restore the state pushed by dispatch signal and asm_signal_trampoline.
  1040. u32* stack_ptr = (u32*)registers.userspace_esp;
  1041. u32 smuggled_eax = *stack_ptr;
  1042. //pop the stored eax, ebp, return address, handler and signal code
  1043. stack_ptr += 5;
  1044. current->m_signal_mask = *stack_ptr;
  1045. stack_ptr++;
  1046. //pop edi, esi, ebp, esp, ebx, edx, ecx and eax
  1047. memcpy(&registers.edi, stack_ptr, 8 * sizeof(u32));
  1048. stack_ptr += 8;
  1049. registers.eip = *stack_ptr;
  1050. stack_ptr++;
  1051. registers.eflags = *stack_ptr;
  1052. stack_ptr++;
  1053. registers.userspace_esp = registers.esp;
  1054. return smuggled_eax;
  1055. }
  1056. void Process::crash(int signal, u32 eip)
  1057. {
  1058. ASSERT_INTERRUPTS_DISABLED();
  1059. ASSERT(!is_dead());
  1060. ASSERT(&current->process() == this);
  1061. if (m_elf_loader && ksyms_ready)
  1062. dbgprintf("\033[31;1m%p %s\033[0m\n", eip, m_elf_loader->symbolicate(eip).characters());
  1063. dump_backtrace();
  1064. m_termination_signal = signal;
  1065. dump_regions();
  1066. ASSERT(is_ring3());
  1067. die();
  1068. // We can not return from here, as there is nowhere
  1069. // to unwind to, so die right away.
  1070. current->die_if_needed();
  1071. ASSERT_NOT_REACHED();
  1072. }
  1073. Process* Process::from_pid(pid_t pid)
  1074. {
  1075. ASSERT_INTERRUPTS_DISABLED();
  1076. for (auto& process : *g_processes) {
  1077. if (process.pid() == pid)
  1078. return &process;
  1079. }
  1080. return nullptr;
  1081. }
  1082. RefPtr<FileDescription> Process::file_description(int fd) const
  1083. {
  1084. if (fd < 0)
  1085. return nullptr;
  1086. if (fd < m_fds.size())
  1087. return m_fds[fd].description.ptr();
  1088. return nullptr;
  1089. }
  1090. int Process::fd_flags(int fd) const
  1091. {
  1092. if (fd < 0)
  1093. return -1;
  1094. if (fd < m_fds.size())
  1095. return m_fds[fd].flags;
  1096. return -1;
  1097. }
  1098. ssize_t Process::sys$get_dir_entries(int fd, void* buffer, ssize_t size)
  1099. {
  1100. REQUIRE_PROMISE(stdio);
  1101. if (size < 0)
  1102. return -EINVAL;
  1103. if (!validate_write(buffer, size))
  1104. return -EFAULT;
  1105. auto description = file_description(fd);
  1106. if (!description)
  1107. return -EBADF;
  1108. return description->get_dir_entries((u8*)buffer, size);
  1109. }
  1110. int Process::sys$lseek(int fd, off_t offset, int whence)
  1111. {
  1112. REQUIRE_PROMISE(stdio);
  1113. auto description = file_description(fd);
  1114. if (!description)
  1115. return -EBADF;
  1116. return description->seek(offset, whence);
  1117. }
  1118. int Process::sys$ttyname_r(int fd, char* buffer, ssize_t size)
  1119. {
  1120. REQUIRE_PROMISE(tty);
  1121. if (size < 0)
  1122. return -EINVAL;
  1123. if (!validate_write(buffer, size))
  1124. return -EFAULT;
  1125. auto description = file_description(fd);
  1126. if (!description)
  1127. return -EBADF;
  1128. if (!description->is_tty())
  1129. return -ENOTTY;
  1130. String tty_name = description->tty()->tty_name();
  1131. if ((size_t)size < tty_name.length() + 1)
  1132. return -ERANGE;
  1133. copy_to_user(buffer, tty_name.characters(), tty_name.length() + 1);
  1134. return 0;
  1135. }
  1136. int Process::sys$ptsname_r(int fd, char* buffer, ssize_t size)
  1137. {
  1138. REQUIRE_PROMISE(tty);
  1139. if (size < 0)
  1140. return -EINVAL;
  1141. if (!validate_write(buffer, size))
  1142. return -EFAULT;
  1143. auto description = file_description(fd);
  1144. if (!description)
  1145. return -EBADF;
  1146. auto* master_pty = description->master_pty();
  1147. if (!master_pty)
  1148. return -ENOTTY;
  1149. auto pts_name = master_pty->pts_name();
  1150. if ((size_t)size < pts_name.length() + 1)
  1151. return -ERANGE;
  1152. copy_to_user(buffer, pts_name.characters(), pts_name.length() + 1);
  1153. return 0;
  1154. }
  1155. ssize_t Process::sys$writev(int fd, const struct iovec* iov, int iov_count)
  1156. {
  1157. REQUIRE_PROMISE(stdio);
  1158. if (iov_count < 0)
  1159. return -EINVAL;
  1160. if (!validate_read_typed(iov, iov_count))
  1161. return -EFAULT;
  1162. u64 total_length = 0;
  1163. Vector<iovec, 32> vecs;
  1164. vecs.ensure_capacity(iov_count);
  1165. copy_from_user(vecs.data(), iov, iov_count * sizeof(iovec));
  1166. for (auto& vec : vecs) {
  1167. if (!validate_read(vec.iov_base, vec.iov_len))
  1168. return -EFAULT;
  1169. total_length += vec.iov_len;
  1170. if (total_length > INT32_MAX)
  1171. return -EINVAL;
  1172. }
  1173. auto description = file_description(fd);
  1174. if (!description)
  1175. return -EBADF;
  1176. if (!description->is_writable())
  1177. return -EBADF;
  1178. int nwritten = 0;
  1179. for (auto& vec : vecs) {
  1180. int rc = do_write(*description, (const u8*)vec.iov_base, vec.iov_len);
  1181. if (rc < 0) {
  1182. if (nwritten == 0)
  1183. return rc;
  1184. return nwritten;
  1185. }
  1186. nwritten += rc;
  1187. }
  1188. return nwritten;
  1189. }
  1190. ssize_t Process::do_write(FileDescription& description, const u8* data, int data_size)
  1191. {
  1192. ssize_t nwritten = 0;
  1193. if (!description.is_blocking()) {
  1194. if (!description.can_write())
  1195. return -EAGAIN;
  1196. }
  1197. if (description.should_append()) {
  1198. #ifdef IO_DEBUG
  1199. dbgprintf("seeking to end (O_APPEND)\n");
  1200. #endif
  1201. description.seek(0, SEEK_END);
  1202. }
  1203. while (nwritten < data_size) {
  1204. #ifdef IO_DEBUG
  1205. dbgprintf("while %u < %u\n", nwritten, size);
  1206. #endif
  1207. if (!description.can_write()) {
  1208. #ifdef IO_DEBUG
  1209. dbgprintf("block write on %d\n", fd);
  1210. #endif
  1211. if (current->block<Thread::WriteBlocker>(description) != Thread::BlockResult::WokeNormally) {
  1212. if (nwritten == 0)
  1213. return -EINTR;
  1214. }
  1215. }
  1216. ssize_t rc = description.write(data + nwritten, data_size - nwritten);
  1217. #ifdef IO_DEBUG
  1218. dbgprintf(" -> write returned %d\n", rc);
  1219. #endif
  1220. if (rc < 0) {
  1221. // FIXME: Support returning partial nwritten with errno.
  1222. ASSERT(nwritten == 0);
  1223. return rc;
  1224. }
  1225. if (rc == 0)
  1226. break;
  1227. nwritten += rc;
  1228. }
  1229. return nwritten;
  1230. }
  1231. ssize_t Process::sys$write(int fd, const u8* data, ssize_t size)
  1232. {
  1233. REQUIRE_PROMISE(stdio);
  1234. if (size < 0)
  1235. return -EINVAL;
  1236. if (size == 0)
  1237. return 0;
  1238. if (!validate_read(data, size))
  1239. return -EFAULT;
  1240. #ifdef DEBUG_IO
  1241. dbgprintf("%s(%u): sys$write(%d, %p, %u)\n", name().characters(), pid(), fd, data, size);
  1242. #endif
  1243. auto description = file_description(fd);
  1244. if (!description)
  1245. return -EBADF;
  1246. if (!description->is_writable())
  1247. return -EBADF;
  1248. return do_write(*description, data, size);
  1249. }
  1250. ssize_t Process::sys$read(int fd, u8* buffer, ssize_t size)
  1251. {
  1252. REQUIRE_PROMISE(stdio);
  1253. if (size < 0)
  1254. return -EINVAL;
  1255. if (size == 0)
  1256. return 0;
  1257. if (!validate_write(buffer, size))
  1258. return -EFAULT;
  1259. #ifdef DEBUG_IO
  1260. dbgprintf("%s(%u) sys$read(%d, %p, %u)\n", name().characters(), pid(), fd, buffer, size);
  1261. #endif
  1262. auto description = file_description(fd);
  1263. if (!description)
  1264. return -EBADF;
  1265. if (!description->is_readable())
  1266. return -EBADF;
  1267. if (description->is_directory())
  1268. return -EISDIR;
  1269. if (description->is_blocking()) {
  1270. if (!description->can_read()) {
  1271. if (current->block<Thread::ReadBlocker>(*description) != Thread::BlockResult::WokeNormally)
  1272. return -EINTR;
  1273. }
  1274. }
  1275. return description->read(buffer, size);
  1276. }
  1277. int Process::sys$close(int fd)
  1278. {
  1279. REQUIRE_PROMISE(stdio);
  1280. auto description = file_description(fd);
  1281. #ifdef DEBUG_IO
  1282. dbgprintf("%s(%u) sys$close(%d) %p\n", name().characters(), pid(), fd, description.ptr());
  1283. #endif
  1284. if (!description)
  1285. return -EBADF;
  1286. int rc = description->close();
  1287. m_fds[fd] = {};
  1288. return rc;
  1289. }
  1290. int Process::sys$utime(const char* user_path, size_t path_length, const utimbuf* user_buf)
  1291. {
  1292. REQUIRE_PROMISE(fattr);
  1293. if (user_buf && !validate_read_typed(user_buf))
  1294. return -EFAULT;
  1295. auto path = get_syscall_path_argument(user_path, path_length);
  1296. if (path.is_error())
  1297. return path.error();
  1298. utimbuf buf;
  1299. if (user_buf) {
  1300. copy_from_user(&buf, user_buf, sizeof(buf));
  1301. } else {
  1302. auto now = kgettimeofday();
  1303. buf = { now.tv_sec, now.tv_sec };
  1304. }
  1305. return VFS::the().utime(path.value(), current_directory(), buf.actime, buf.modtime);
  1306. }
  1307. int Process::sys$access(const char* user_path, size_t path_length, int mode)
  1308. {
  1309. REQUIRE_PROMISE(rpath);
  1310. auto path = get_syscall_path_argument(user_path, path_length);
  1311. if (path.is_error())
  1312. return path.error();
  1313. return VFS::the().access(path.value(), mode, current_directory());
  1314. }
  1315. int Process::sys$fcntl(int fd, int cmd, u32 arg)
  1316. {
  1317. REQUIRE_PROMISE(stdio);
  1318. (void)cmd;
  1319. (void)arg;
  1320. #ifdef DEBUG_IO
  1321. dbgprintf("sys$fcntl: fd=%d, cmd=%d, arg=%u\n", fd, cmd, arg);
  1322. #endif
  1323. auto description = file_description(fd);
  1324. if (!description)
  1325. return -EBADF;
  1326. // NOTE: The FD flags are not shared between FileDescription objects.
  1327. // This means that dup() doesn't copy the FD_CLOEXEC flag!
  1328. switch (cmd) {
  1329. case F_DUPFD: {
  1330. int arg_fd = (int)arg;
  1331. if (arg_fd < 0)
  1332. return -EINVAL;
  1333. int new_fd = alloc_fd(arg_fd);
  1334. if (new_fd < 0)
  1335. return new_fd;
  1336. m_fds[new_fd].set(*description);
  1337. break;
  1338. }
  1339. case F_GETFD:
  1340. return m_fds[fd].flags;
  1341. case F_SETFD:
  1342. m_fds[fd].flags = arg;
  1343. break;
  1344. case F_GETFL:
  1345. return description->file_flags();
  1346. case F_SETFL:
  1347. description->set_file_flags(arg);
  1348. break;
  1349. default:
  1350. ASSERT_NOT_REACHED();
  1351. }
  1352. return 0;
  1353. }
  1354. int Process::sys$fstat(int fd, stat* statbuf)
  1355. {
  1356. REQUIRE_PROMISE(stdio);
  1357. if (!validate_write_typed(statbuf))
  1358. return -EFAULT;
  1359. auto description = file_description(fd);
  1360. if (!description)
  1361. return -EBADF;
  1362. return description->fstat(*statbuf);
  1363. }
  1364. int Process::sys$lstat(const char* user_path, size_t path_length, stat* user_statbuf)
  1365. {
  1366. REQUIRE_PROMISE(rpath);
  1367. if (!validate_write_typed(user_statbuf))
  1368. return -EFAULT;
  1369. auto path = get_syscall_path_argument(user_path, path_length);
  1370. if (path.is_error())
  1371. return path.error();
  1372. auto metadata_or_error = VFS::the().lookup_metadata(path.value(), current_directory(), O_NOFOLLOW_NOERROR);
  1373. if (metadata_or_error.is_error())
  1374. return metadata_or_error.error();
  1375. stat statbuf;
  1376. auto result = metadata_or_error.value().stat(statbuf);
  1377. if (result.is_error())
  1378. return result;
  1379. copy_to_user(user_statbuf, &statbuf, sizeof(statbuf));
  1380. return 0;
  1381. }
  1382. int Process::sys$stat(const char* user_path, size_t path_length, stat* user_statbuf)
  1383. {
  1384. REQUIRE_PROMISE(rpath);
  1385. if (!validate_write_typed(user_statbuf))
  1386. return -EFAULT;
  1387. auto path = get_syscall_path_argument(user_path, path_length);
  1388. if (path.is_error())
  1389. return path.error();
  1390. auto metadata_or_error = VFS::the().lookup_metadata(path.value(), current_directory());
  1391. if (metadata_or_error.is_error())
  1392. return metadata_or_error.error();
  1393. stat statbuf;
  1394. auto result = metadata_or_error.value().stat(statbuf);
  1395. if (result.is_error())
  1396. return result;
  1397. copy_to_user(user_statbuf, &statbuf, sizeof(statbuf));
  1398. return 0;
  1399. }
  1400. template<typename DataType, typename SizeType>
  1401. bool Process::validate(const Syscall::MutableBufferArgument<DataType, SizeType>& buffer)
  1402. {
  1403. return validate_write(buffer.data, buffer.size);
  1404. }
  1405. template<typename DataType, typename SizeType>
  1406. bool Process::validate(const Syscall::ImmutableBufferArgument<DataType, SizeType>& buffer)
  1407. {
  1408. return validate_read(buffer.data, buffer.size);
  1409. }
  1410. String Process::validate_and_copy_string_from_user(const char* user_characters, size_t user_length) const
  1411. {
  1412. if (!validate_read(user_characters, user_length))
  1413. return {};
  1414. SmapDisabler disabler;
  1415. size_t measured_length = strnlen(user_characters, user_length);
  1416. return String(user_characters, measured_length);
  1417. }
  1418. String Process::validate_and_copy_string_from_user(const Syscall::StringArgument& string) const
  1419. {
  1420. return validate_and_copy_string_from_user(string.characters, string.length);
  1421. }
  1422. int Process::sys$readlink(const Syscall::SC_readlink_params* user_params)
  1423. {
  1424. REQUIRE_PROMISE(rpath);
  1425. if (!validate_read_typed(user_params))
  1426. return -EFAULT;
  1427. Syscall::SC_readlink_params params;
  1428. copy_from_user(&params, user_params, sizeof(params));
  1429. if (!validate(params.buffer))
  1430. return -EFAULT;
  1431. auto path = get_syscall_path_argument(params.path);
  1432. if (path.is_error())
  1433. return path.error();
  1434. auto result = VFS::the().open(path.value(), O_RDONLY | O_NOFOLLOW_NOERROR, 0, current_directory());
  1435. if (result.is_error())
  1436. return result.error();
  1437. auto description = result.value();
  1438. if (!description->metadata().is_symlink())
  1439. return -EINVAL;
  1440. auto contents = description->read_entire_file();
  1441. if (!contents)
  1442. return -EIO; // FIXME: Get a more detailed error from VFS.
  1443. auto link_target = String::copy(contents);
  1444. if (link_target.length() + 1 > params.buffer.size)
  1445. return -ENAMETOOLONG;
  1446. copy_to_user(params.buffer.data, link_target.characters(), link_target.length() + 1);
  1447. return 0;
  1448. }
  1449. int Process::sys$chdir(const char* user_path, size_t path_length)
  1450. {
  1451. REQUIRE_PROMISE(rpath);
  1452. auto path = get_syscall_path_argument(user_path, path_length);
  1453. if (path.is_error())
  1454. return path.error();
  1455. auto directory_or_error = VFS::the().open_directory(path.value(), current_directory());
  1456. if (directory_or_error.is_error())
  1457. return directory_or_error.error();
  1458. m_cwd = *directory_or_error.value();
  1459. return 0;
  1460. }
  1461. int Process::sys$fchdir(int fd)
  1462. {
  1463. REQUIRE_PROMISE(stdio);
  1464. auto description = file_description(fd);
  1465. if (!description)
  1466. return -EBADF;
  1467. if (!description->is_directory())
  1468. return -ENOTDIR;
  1469. if (!description->metadata().may_execute(*this))
  1470. return -EACCES;
  1471. m_cwd = description->custody();
  1472. return 0;
  1473. }
  1474. int Process::sys$getcwd(char* buffer, ssize_t size)
  1475. {
  1476. REQUIRE_PROMISE(rpath);
  1477. if (size < 0)
  1478. return -EINVAL;
  1479. if (!validate_write(buffer, size))
  1480. return -EFAULT;
  1481. auto path = current_directory().absolute_path();
  1482. if ((size_t)size < path.length() + 1)
  1483. return -ERANGE;
  1484. copy_to_user(buffer, path.characters(), path.length() + 1);
  1485. return 0;
  1486. }
  1487. int Process::number_of_open_file_descriptors() const
  1488. {
  1489. int count = 0;
  1490. for (auto& description : m_fds) {
  1491. if (description)
  1492. ++count;
  1493. }
  1494. return count;
  1495. }
  1496. int Process::sys$open(const Syscall::SC_open_params* user_params)
  1497. {
  1498. if (!validate_read_typed(user_params))
  1499. return -EFAULT;
  1500. Syscall::SC_open_params params;
  1501. copy_from_user(&params, user_params, sizeof(params));
  1502. auto options = params.options;
  1503. auto mode = params.mode;
  1504. if ((options & O_RDWR) || (options & O_WRONLY))
  1505. REQUIRE_PROMISE(wpath);
  1506. else
  1507. REQUIRE_PROMISE(rpath);
  1508. if (options & O_CREAT)
  1509. REQUIRE_PROMISE(cpath);
  1510. auto path = get_syscall_path_argument(params.path);
  1511. if (path.is_error())
  1512. return path.error();
  1513. // Ignore everything except permission bits.
  1514. mode &= 04777;
  1515. int fd = alloc_fd();
  1516. #ifdef DEBUG_IO
  1517. dbgprintf("%s(%u) sys$open(\"%s\") -> %d\n", name().characters(), pid(), path.value().characters(), fd);
  1518. #endif
  1519. if (fd < 0)
  1520. return fd;
  1521. auto result = VFS::the().open(path.value(), options, mode & ~umask(), current_directory());
  1522. if (result.is_error())
  1523. return result.error();
  1524. auto description = result.value();
  1525. description->set_rw_mode(options);
  1526. description->set_file_flags(options);
  1527. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1528. m_fds[fd].set(move(description), fd_flags);
  1529. return fd;
  1530. }
  1531. int Process::sys$openat(const Syscall::SC_openat_params* user_params)
  1532. {
  1533. if (!validate_read_typed(user_params))
  1534. return -EFAULT;
  1535. Syscall::SC_openat_params params;
  1536. copy_from_user(&params, user_params, sizeof(params));
  1537. int dirfd = params.dirfd;
  1538. int options = params.options;
  1539. u16 mode = params.mode;
  1540. if ((options & O_RDWR) || (options & O_WRONLY))
  1541. REQUIRE_PROMISE(wpath);
  1542. else
  1543. REQUIRE_PROMISE(rpath);
  1544. if (options & O_CREAT)
  1545. REQUIRE_PROMISE(cpath);
  1546. // Ignore everything except permission bits.
  1547. mode &= 04777;
  1548. auto path = get_syscall_path_argument(params.path);
  1549. if (path.is_error())
  1550. return path.error();
  1551. #ifdef DEBUG_IO
  1552. dbgprintf("%s(%u) sys$openat(%d, \"%s\")\n", dirfd, name().characters(), pid(), path.value().characters());
  1553. #endif
  1554. int fd = alloc_fd();
  1555. if (fd < 0)
  1556. return fd;
  1557. RefPtr<Custody> base;
  1558. if (dirfd == AT_FDCWD) {
  1559. base = current_directory();
  1560. } else {
  1561. auto base_description = file_description(dirfd);
  1562. if (!base_description)
  1563. return -EBADF;
  1564. if (!base_description->is_directory())
  1565. return -ENOTDIR;
  1566. if (!base_description->custody())
  1567. return -EINVAL;
  1568. base = base_description->custody();
  1569. }
  1570. auto result = VFS::the().open(path.value(), options, mode & ~umask(), *base);
  1571. if (result.is_error())
  1572. return result.error();
  1573. auto description = result.value();
  1574. description->set_rw_mode(options);
  1575. description->set_file_flags(options);
  1576. u32 fd_flags = (options & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1577. m_fds[fd].set(move(description), fd_flags);
  1578. return fd;
  1579. }
  1580. int Process::alloc_fd(int first_candidate_fd)
  1581. {
  1582. int fd = -EMFILE;
  1583. for (int i = first_candidate_fd; i < (int)m_max_open_file_descriptors; ++i) {
  1584. if (!m_fds[i]) {
  1585. fd = i;
  1586. break;
  1587. }
  1588. }
  1589. return fd;
  1590. }
  1591. int Process::sys$pipe(int pipefd[2], int flags)
  1592. {
  1593. REQUIRE_PROMISE(stdio);
  1594. if (!validate_write_typed(pipefd))
  1595. return -EFAULT;
  1596. if (number_of_open_file_descriptors() + 2 > max_open_file_descriptors())
  1597. return -EMFILE;
  1598. // Reject flags other than O_CLOEXEC.
  1599. if ((flags & O_CLOEXEC) != flags)
  1600. return -EINVAL;
  1601. u32 fd_flags = (flags & O_CLOEXEC) ? FD_CLOEXEC : 0;
  1602. auto fifo = FIFO::create(m_uid);
  1603. int reader_fd = alloc_fd();
  1604. m_fds[reader_fd].set(fifo->open_direction(FIFO::Direction::Reader), fd_flags);
  1605. m_fds[reader_fd].description->set_readable(true);
  1606. copy_to_user(&pipefd[0], &reader_fd, sizeof(reader_fd));
  1607. int writer_fd = alloc_fd();
  1608. m_fds[writer_fd].set(fifo->open_direction(FIFO::Direction::Writer), fd_flags);
  1609. m_fds[writer_fd].description->set_writable(true);
  1610. copy_to_user(&pipefd[1], &writer_fd, sizeof(writer_fd));
  1611. return 0;
  1612. }
  1613. int Process::sys$killpg(int pgrp, int signum)
  1614. {
  1615. REQUIRE_PROMISE(proc);
  1616. if (signum < 1 || signum >= 32)
  1617. return -EINVAL;
  1618. if (pgrp < 0)
  1619. return -EINVAL;
  1620. InterruptDisabler disabler;
  1621. return do_killpg(pgrp, signum);
  1622. }
  1623. int Process::sys$setuid(uid_t uid)
  1624. {
  1625. REQUIRE_PROMISE(id);
  1626. if (uid != m_uid && !is_superuser())
  1627. return -EPERM;
  1628. m_uid = uid;
  1629. m_euid = uid;
  1630. return 0;
  1631. }
  1632. int Process::sys$setgid(gid_t gid)
  1633. {
  1634. REQUIRE_PROMISE(id);
  1635. if (gid != m_gid && !is_superuser())
  1636. return -EPERM;
  1637. m_gid = gid;
  1638. m_egid = gid;
  1639. return 0;
  1640. }
  1641. unsigned Process::sys$alarm(unsigned seconds)
  1642. {
  1643. REQUIRE_PROMISE(stdio);
  1644. unsigned previous_alarm_remaining = 0;
  1645. if (m_alarm_deadline && m_alarm_deadline > g_uptime) {
  1646. previous_alarm_remaining = (m_alarm_deadline - g_uptime) / TICKS_PER_SECOND;
  1647. }
  1648. if (!seconds) {
  1649. m_alarm_deadline = 0;
  1650. return previous_alarm_remaining;
  1651. }
  1652. m_alarm_deadline = g_uptime + seconds * TICKS_PER_SECOND;
  1653. return previous_alarm_remaining;
  1654. }
  1655. int Process::sys$uname(utsname* buf)
  1656. {
  1657. REQUIRE_PROMISE(stdio);
  1658. if (!validate_write_typed(buf))
  1659. return -EFAULT;
  1660. LOCKER(*s_hostname_lock);
  1661. if (s_hostname->length() + 1 > sizeof(utsname::nodename))
  1662. return -ENAMETOOLONG;
  1663. copy_to_user(buf->sysname, "SerenityOS", 11);
  1664. copy_to_user(buf->release, "1.0-dev", 8);
  1665. copy_to_user(buf->version, "FIXME", 6);
  1666. copy_to_user(buf->machine, "i686", 5);
  1667. copy_to_user(buf->nodename, s_hostname->characters(), s_hostname->length() + 1);
  1668. return 0;
  1669. }
  1670. KResult Process::do_kill(Process& process, int signal)
  1671. {
  1672. // FIXME: Allow sending SIGCONT to everyone in the process group.
  1673. // FIXME: Should setuid processes have some special treatment here?
  1674. if (!is_superuser() && m_euid != process.m_uid && m_uid != process.m_uid)
  1675. return KResult(-EPERM);
  1676. if (process.is_ring0() && signal == SIGKILL) {
  1677. kprintf("%s(%u) attempted to send SIGKILL to ring 0 process %s(%u)\n", name().characters(), m_pid, process.name().characters(), process.pid());
  1678. return KResult(-EPERM);
  1679. }
  1680. if (signal != 0)
  1681. process.send_signal(signal, this);
  1682. return KSuccess;
  1683. }
  1684. KResult Process::do_killpg(pid_t pgrp, int signal)
  1685. {
  1686. ASSERT(pgrp >= 0);
  1687. // Send the signal to all processes in the given group.
  1688. if (pgrp == 0) {
  1689. // Send the signal to our own pgrp.
  1690. pgrp = pgid();
  1691. }
  1692. bool group_was_empty = true;
  1693. bool any_succeeded = false;
  1694. KResult error = KSuccess;
  1695. Process::for_each_in_pgrp(pgrp, [&](auto& process) {
  1696. group_was_empty = false;
  1697. KResult res = do_kill(process, signal);
  1698. if (res.is_success())
  1699. any_succeeded = true;
  1700. else
  1701. error = res;
  1702. return IterationDecision::Continue;
  1703. });
  1704. if (group_was_empty)
  1705. return KResult(-ESRCH);
  1706. if (any_succeeded)
  1707. return KSuccess;
  1708. return error;
  1709. }
  1710. int Process::sys$kill(pid_t pid, int signal)
  1711. {
  1712. REQUIRE_PROMISE(proc);
  1713. if (signal < 0 || signal >= 32)
  1714. return -EINVAL;
  1715. if (pid <= 0)
  1716. return do_killpg(-pid, signal);
  1717. if (pid == -1) {
  1718. // FIXME: Send to all processes.
  1719. return -ENOTIMPL;
  1720. }
  1721. if (pid == m_pid) {
  1722. if (signal == 0)
  1723. return 0;
  1724. if (!current->should_ignore_signal(signal)) {
  1725. current->send_signal(signal, this);
  1726. (void)current->block<Thread::SemiPermanentBlocker>(Thread::SemiPermanentBlocker::Reason::Signal);
  1727. }
  1728. return 0;
  1729. }
  1730. InterruptDisabler disabler;
  1731. auto* peer = Process::from_pid(pid);
  1732. if (!peer)
  1733. return -ESRCH;
  1734. return do_kill(*peer, signal);
  1735. }
  1736. int Process::sys$usleep(useconds_t usec)
  1737. {
  1738. REQUIRE_PROMISE(stdio);
  1739. if (!usec)
  1740. return 0;
  1741. u64 wakeup_time = current->sleep(usec / 1000);
  1742. if (wakeup_time > g_uptime)
  1743. return -EINTR;
  1744. return 0;
  1745. }
  1746. int Process::sys$sleep(unsigned seconds)
  1747. {
  1748. REQUIRE_PROMISE(stdio);
  1749. if (!seconds)
  1750. return 0;
  1751. u64 wakeup_time = current->sleep(seconds * TICKS_PER_SECOND);
  1752. if (wakeup_time > g_uptime) {
  1753. u32 ticks_left_until_original_wakeup_time = wakeup_time - g_uptime;
  1754. return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
  1755. }
  1756. return 0;
  1757. }
  1758. timeval kgettimeofday()
  1759. {
  1760. return const_cast<const timeval&>(((KernelInfoPage*)s_info_page_address_for_kernel.as_ptr())->now);
  1761. }
  1762. void kgettimeofday(timeval& tv)
  1763. {
  1764. tv = kgettimeofday();
  1765. }
  1766. int Process::sys$gettimeofday(timeval* tv)
  1767. {
  1768. REQUIRE_PROMISE(stdio);
  1769. if (!validate_write_typed(tv))
  1770. return -EFAULT;
  1771. *tv = kgettimeofday();
  1772. return 0;
  1773. }
  1774. uid_t Process::sys$getuid()
  1775. {
  1776. REQUIRE_PROMISE(stdio);
  1777. return m_uid;
  1778. }
  1779. gid_t Process::sys$getgid()
  1780. {
  1781. REQUIRE_PROMISE(stdio);
  1782. return m_gid;
  1783. }
  1784. uid_t Process::sys$geteuid()
  1785. {
  1786. REQUIRE_PROMISE(stdio);
  1787. return m_euid;
  1788. }
  1789. gid_t Process::sys$getegid()
  1790. {
  1791. REQUIRE_PROMISE(stdio);
  1792. return m_egid;
  1793. }
  1794. pid_t Process::sys$getpid()
  1795. {
  1796. REQUIRE_PROMISE(stdio);
  1797. return m_pid;
  1798. }
  1799. pid_t Process::sys$getppid()
  1800. {
  1801. REQUIRE_PROMISE(stdio);
  1802. return m_ppid;
  1803. }
  1804. mode_t Process::sys$umask(mode_t mask)
  1805. {
  1806. REQUIRE_PROMISE(stdio);
  1807. auto old_mask = m_umask;
  1808. m_umask = mask & 0777;
  1809. return old_mask;
  1810. }
  1811. int Process::reap(Process& process)
  1812. {
  1813. int exit_status;
  1814. {
  1815. InterruptDisabler disabler;
  1816. exit_status = (process.m_termination_status << 8) | process.m_termination_signal;
  1817. if (process.ppid()) {
  1818. auto* parent = Process::from_pid(process.ppid());
  1819. if (parent) {
  1820. parent->m_ticks_in_user_for_dead_children += process.m_ticks_in_user + process.m_ticks_in_user_for_dead_children;
  1821. parent->m_ticks_in_kernel_for_dead_children += process.m_ticks_in_kernel + process.m_ticks_in_kernel_for_dead_children;
  1822. }
  1823. }
  1824. dbgprintf("reap: %s(%u)\n", process.name().characters(), process.pid());
  1825. ASSERT(process.is_dead());
  1826. g_processes->remove(&process);
  1827. }
  1828. delete &process;
  1829. return exit_status;
  1830. }
  1831. pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
  1832. {
  1833. REQUIRE_PROMISE(stdio);
  1834. dbgprintf("sys$waitpid(%d, %p, %d)\n", waitee, wstatus, options);
  1835. if (!options) {
  1836. // FIXME: This can't be right.. can it? Figure out how this should actually work.
  1837. options = WEXITED;
  1838. }
  1839. if (wstatus && !validate_write_typed(wstatus))
  1840. return -EFAULT;
  1841. int exit_status = 0;
  1842. {
  1843. InterruptDisabler disabler;
  1844. if (waitee != -1 && !Process::from_pid(waitee))
  1845. return -ECHILD;
  1846. }
  1847. if (options & WNOHANG) {
  1848. // FIXME: Figure out what WNOHANG should do with stopped children.
  1849. if (waitee == -1) {
  1850. pid_t reaped_pid = 0;
  1851. InterruptDisabler disabler;
  1852. for_each_child([&reaped_pid, &exit_status](Process& process) {
  1853. if (process.is_dead()) {
  1854. reaped_pid = process.pid();
  1855. exit_status = reap(process);
  1856. }
  1857. return IterationDecision::Continue;
  1858. });
  1859. return reaped_pid;
  1860. } else {
  1861. ASSERT(waitee > 0); // FIXME: Implement other PID specs.
  1862. InterruptDisabler disabler;
  1863. auto* waitee_process = Process::from_pid(waitee);
  1864. if (!waitee_process)
  1865. return -ECHILD;
  1866. if (waitee_process->is_dead()) {
  1867. exit_status = reap(*waitee_process);
  1868. return waitee;
  1869. }
  1870. return 0;
  1871. }
  1872. }
  1873. pid_t waitee_pid = waitee;
  1874. if (current->block<Thread::WaitBlocker>(options, waitee_pid) != Thread::BlockResult::WokeNormally)
  1875. return -EINTR;
  1876. InterruptDisabler disabler;
  1877. // NOTE: If waitee was -1, m_waitee_pid will have been filled in by the scheduler.
  1878. Process* waitee_process = Process::from_pid(waitee_pid);
  1879. if (!waitee_process)
  1880. return -ECHILD;
  1881. ASSERT(waitee_process);
  1882. if (waitee_process->is_dead()) {
  1883. exit_status = reap(*waitee_process);
  1884. } else {
  1885. ASSERT(waitee_process->any_thread().state() == Thread::State::Stopped);
  1886. exit_status = 0x7f;
  1887. }
  1888. if (wstatus)
  1889. copy_to_user(wstatus, &exit_status, sizeof(exit_status));
  1890. return waitee_pid;
  1891. }
  1892. bool Process::validate_read_from_kernel(VirtualAddress vaddr, ssize_t size) const
  1893. {
  1894. if (vaddr.is_null())
  1895. return false;
  1896. // We check extra carefully here since the first 4MB of the address space is identity-mapped.
  1897. // This code allows access outside of the known used address ranges to get caught.
  1898. if (is_kmalloc_address(vaddr.as_ptr()))
  1899. return true;
  1900. return MM.validate_kernel_read(*this, vaddr, size);
  1901. }
  1902. bool Process::validate_read(const void* address, ssize_t size) const
  1903. {
  1904. ASSERT(size >= 0);
  1905. VirtualAddress first_address((u32)address);
  1906. if (is_ring0()) {
  1907. if (is_kmalloc_address(address))
  1908. return true;
  1909. }
  1910. if (!size)
  1911. return false;
  1912. return MM.validate_user_read(*this, first_address, size);
  1913. }
  1914. bool Process::validate_write(void* address, ssize_t size) const
  1915. {
  1916. ASSERT(size >= 0);
  1917. VirtualAddress first_address((u32)address);
  1918. if (is_ring0()) {
  1919. if (is_kmalloc_address(address))
  1920. return true;
  1921. }
  1922. if (!size)
  1923. return false;
  1924. return MM.validate_user_write(*this, first_address, size);
  1925. }
  1926. pid_t Process::sys$getsid(pid_t pid)
  1927. {
  1928. REQUIRE_PROMISE(stdio);
  1929. if (pid == 0)
  1930. return m_sid;
  1931. InterruptDisabler disabler;
  1932. auto* process = Process::from_pid(pid);
  1933. if (!process)
  1934. return -ESRCH;
  1935. if (m_sid != process->m_sid)
  1936. return -EPERM;
  1937. return process->m_sid;
  1938. }
  1939. pid_t Process::sys$setsid()
  1940. {
  1941. REQUIRE_PROMISE(proc);
  1942. InterruptDisabler disabler;
  1943. bool found_process_with_same_pgid_as_my_pid = false;
  1944. Process::for_each_in_pgrp(pid(), [&](auto&) {
  1945. found_process_with_same_pgid_as_my_pid = true;
  1946. return IterationDecision::Break;
  1947. });
  1948. if (found_process_with_same_pgid_as_my_pid)
  1949. return -EPERM;
  1950. m_sid = m_pid;
  1951. m_pgid = m_pid;
  1952. return m_sid;
  1953. }
  1954. pid_t Process::sys$getpgid(pid_t pid)
  1955. {
  1956. REQUIRE_PROMISE(stdio);
  1957. if (pid == 0)
  1958. return m_pgid;
  1959. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1960. auto* process = Process::from_pid(pid);
  1961. if (!process)
  1962. return -ESRCH;
  1963. return process->m_pgid;
  1964. }
  1965. pid_t Process::sys$getpgrp()
  1966. {
  1967. REQUIRE_PROMISE(stdio);
  1968. return m_pgid;
  1969. }
  1970. static pid_t get_sid_from_pgid(pid_t pgid)
  1971. {
  1972. InterruptDisabler disabler;
  1973. auto* group_leader = Process::from_pid(pgid);
  1974. if (!group_leader)
  1975. return -1;
  1976. return group_leader->sid();
  1977. }
  1978. int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
  1979. {
  1980. REQUIRE_PROMISE(proc);
  1981. InterruptDisabler disabler; // FIXME: Use a ProcessHandle
  1982. pid_t pid = specified_pid ? specified_pid : m_pid;
  1983. if (specified_pgid < 0) {
  1984. // The value of the pgid argument is less than 0, or is not a value supported by the implementation.
  1985. return -EINVAL;
  1986. }
  1987. auto* process = Process::from_pid(pid);
  1988. if (!process)
  1989. return -ESRCH;
  1990. if (process != this && process->ppid() != m_pid) {
  1991. // The value of the pid argument does not match the process ID
  1992. // of the calling process or of a child process of the calling process.
  1993. return -ESRCH;
  1994. }
  1995. if (process->pid() == process->sid()) {
  1996. // The process indicated by the pid argument is a session leader.
  1997. return -EPERM;
  1998. }
  1999. if (process->ppid() == m_pid && process->sid() != sid()) {
  2000. // The value of the pid argument matches the process ID of a child
  2001. // process of the calling process and the child process is not in
  2002. // the same session as the calling process.
  2003. return -EPERM;
  2004. }
  2005. pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
  2006. pid_t current_sid = get_sid_from_pgid(process->m_pgid);
  2007. pid_t new_sid = get_sid_from_pgid(new_pgid);
  2008. if (current_sid != new_sid) {
  2009. // Can't move a process between sessions.
  2010. return -EPERM;
  2011. }
  2012. // FIXME: There are more EPERM conditions to check for here..
  2013. process->m_pgid = new_pgid;
  2014. return 0;
  2015. }
  2016. int Process::sys$ioctl(int fd, unsigned request, unsigned arg)
  2017. {
  2018. auto description = file_description(fd);
  2019. if (!description)
  2020. return -EBADF;
  2021. SmapDisabler disabler;
  2022. return description->file().ioctl(*description, request, arg);
  2023. }
  2024. int Process::sys$getdtablesize()
  2025. {
  2026. REQUIRE_PROMISE(stdio);
  2027. return m_max_open_file_descriptors;
  2028. }
  2029. int Process::sys$dup(int old_fd)
  2030. {
  2031. REQUIRE_PROMISE(stdio);
  2032. auto description = file_description(old_fd);
  2033. if (!description)
  2034. return -EBADF;
  2035. int new_fd = alloc_fd(0);
  2036. if (new_fd < 0)
  2037. return new_fd;
  2038. m_fds[new_fd].set(*description);
  2039. return new_fd;
  2040. }
  2041. int Process::sys$dup2(int old_fd, int new_fd)
  2042. {
  2043. REQUIRE_PROMISE(stdio);
  2044. auto description = file_description(old_fd);
  2045. if (!description)
  2046. return -EBADF;
  2047. if (new_fd < 0 || new_fd >= m_max_open_file_descriptors)
  2048. return -EINVAL;
  2049. m_fds[new_fd].set(*description);
  2050. return new_fd;
  2051. }
  2052. int Process::sys$sigprocmask(int how, const sigset_t* set, sigset_t* old_set)
  2053. {
  2054. REQUIRE_PROMISE(stdio);
  2055. if (old_set) {
  2056. if (!validate_write_typed(old_set))
  2057. return -EFAULT;
  2058. copy_to_user(old_set, &current->m_signal_mask, sizeof(current->m_signal_mask));
  2059. }
  2060. if (set) {
  2061. if (!validate_read_typed(set))
  2062. return -EFAULT;
  2063. sigset_t set_value;
  2064. copy_from_user(&set_value, set, sizeof(set_value));
  2065. switch (how) {
  2066. case SIG_BLOCK:
  2067. current->m_signal_mask &= ~set_value;
  2068. break;
  2069. case SIG_UNBLOCK:
  2070. current->m_signal_mask |= set_value;
  2071. break;
  2072. case SIG_SETMASK:
  2073. current->m_signal_mask = set_value;
  2074. break;
  2075. default:
  2076. return -EINVAL;
  2077. }
  2078. }
  2079. return 0;
  2080. }
  2081. int Process::sys$sigpending(sigset_t* set)
  2082. {
  2083. REQUIRE_PROMISE(stdio);
  2084. if (!validate_write_typed(set))
  2085. return -EFAULT;
  2086. copy_to_user(set, &current->m_pending_signals, sizeof(current->m_pending_signals));
  2087. return 0;
  2088. }
  2089. int Process::sys$sigaction(int signum, const sigaction* act, sigaction* old_act)
  2090. {
  2091. REQUIRE_PROMISE(stdio);
  2092. if (signum < 1 || signum >= 32 || signum == SIGKILL || signum == SIGSTOP)
  2093. return -EINVAL;
  2094. if (!validate_read_typed(act))
  2095. return -EFAULT;
  2096. InterruptDisabler disabler; // FIXME: This should use a narrower lock. Maybe a way to ignore signals temporarily?
  2097. auto& action = current->m_signal_action_data[signum];
  2098. if (old_act) {
  2099. if (!validate_write_typed(old_act))
  2100. return -EFAULT;
  2101. copy_to_user(&old_act->sa_flags, &action.flags, sizeof(action.flags));
  2102. copy_to_user(&old_act->sa_sigaction, &action.handler_or_sigaction, sizeof(action.handler_or_sigaction));
  2103. }
  2104. copy_from_user(&action.flags, &act->sa_flags, sizeof(action.flags));
  2105. copy_from_user(&action.handler_or_sigaction, &act->sa_sigaction, sizeof(action.flags));
  2106. return 0;
  2107. }
  2108. int Process::sys$getgroups(ssize_t count, gid_t* gids)
  2109. {
  2110. REQUIRE_PROMISE(stdio);
  2111. if (count < 0)
  2112. return -EINVAL;
  2113. if (!count)
  2114. return m_extra_gids.size();
  2115. if (count != (int)m_extra_gids.size())
  2116. return -EINVAL;
  2117. if (!validate_write_typed(gids, m_extra_gids.size()))
  2118. return -EFAULT;
  2119. size_t i = 0;
  2120. SmapDisabler disabler;
  2121. for (auto gid : m_extra_gids)
  2122. gids[i++] = gid;
  2123. return 0;
  2124. }
  2125. int Process::sys$setgroups(ssize_t count, const gid_t* gids)
  2126. {
  2127. REQUIRE_PROMISE(id);
  2128. if (count < 0)
  2129. return -EINVAL;
  2130. if (!is_superuser())
  2131. return -EPERM;
  2132. if (count && !validate_read(gids, count))
  2133. return -EFAULT;
  2134. m_extra_gids.clear();
  2135. SmapDisabler disabler;
  2136. for (int i = 0; i < count; ++i) {
  2137. if (gids[i] == m_gid)
  2138. continue;
  2139. m_extra_gids.set(gids[i]);
  2140. }
  2141. return 0;
  2142. }
  2143. int Process::sys$mkdir(const char* user_path, size_t path_length, mode_t mode)
  2144. {
  2145. REQUIRE_PROMISE(cpath);
  2146. auto path = get_syscall_path_argument(user_path, path_length);
  2147. if (path.is_error())
  2148. return path.error();
  2149. return VFS::the().mkdir(path.value(), mode & ~umask(), current_directory());
  2150. }
  2151. int Process::sys$realpath(const Syscall::SC_realpath_params* user_params)
  2152. {
  2153. REQUIRE_PROMISE(rpath);
  2154. if (!validate_read_typed(user_params))
  2155. return -EFAULT;
  2156. Syscall::SC_realpath_params params;
  2157. copy_from_user(&params, user_params, sizeof(params));
  2158. if (!validate_write(params.buffer.data, params.buffer.size))
  2159. return -EFAULT;
  2160. auto path = get_syscall_path_argument(params.path);
  2161. if (path.is_error())
  2162. return path.error();
  2163. auto custody_or_error = VFS::the().resolve_path(path.value(), current_directory());
  2164. if (custody_or_error.is_error())
  2165. return custody_or_error.error();
  2166. auto& custody = custody_or_error.value();
  2167. // FIXME: Once resolve_path is fixed to deal with .. and . , remove the use of FileSystemPath::canonical_path.
  2168. FileSystemPath canonical_path(custody->absolute_path());
  2169. if (!canonical_path.is_valid()) {
  2170. dbg() << "FileSystemPath failed to canonicalize " << custody->absolute_path();
  2171. ASSERT_NOT_REACHED();
  2172. }
  2173. if (canonical_path.string().length() + 1 > params.buffer.size)
  2174. return -ENAMETOOLONG;
  2175. copy_to_user(params.buffer.data, canonical_path.string().characters(), canonical_path.string().length() + 1);
  2176. return 0;
  2177. };
  2178. clock_t Process::sys$times(tms* times)
  2179. {
  2180. REQUIRE_PROMISE(stdio);
  2181. if (!validate_write_typed(times))
  2182. return -EFAULT;
  2183. copy_to_user(&times->tms_utime, &m_ticks_in_user, sizeof(m_ticks_in_user));
  2184. copy_to_user(&times->tms_stime, &m_ticks_in_kernel, sizeof(m_ticks_in_kernel));
  2185. copy_to_user(&times->tms_cutime, &m_ticks_in_user_for_dead_children, sizeof(m_ticks_in_user_for_dead_children));
  2186. copy_to_user(&times->tms_cstime, &m_ticks_in_kernel_for_dead_children, sizeof(m_ticks_in_kernel_for_dead_children));
  2187. return g_uptime & 0x7fffffff;
  2188. }
  2189. int Process::sys$select(const Syscall::SC_select_params* params)
  2190. {
  2191. REQUIRE_PROMISE(stdio);
  2192. // FIXME: Return -EINVAL if timeout is invalid.
  2193. if (!validate_read_typed(params))
  2194. return -EFAULT;
  2195. SmapDisabler disabler;
  2196. int nfds = params->nfds;
  2197. fd_set* readfds = params->readfds;
  2198. fd_set* writefds = params->writefds;
  2199. fd_set* exceptfds = params->exceptfds;
  2200. timeval* timeout = params->timeout;
  2201. if (writefds && !validate_write_typed(writefds))
  2202. return -EFAULT;
  2203. if (readfds && !validate_write_typed(readfds))
  2204. return -EFAULT;
  2205. if (exceptfds && !validate_write_typed(exceptfds))
  2206. return -EFAULT;
  2207. if (timeout && !validate_read_typed(timeout))
  2208. return -EFAULT;
  2209. if (nfds < 0)
  2210. return -EINVAL;
  2211. timeval computed_timeout;
  2212. bool select_has_timeout = false;
  2213. if (timeout && (timeout->tv_sec || timeout->tv_usec)) {
  2214. timeval_add(kgettimeofday(), *timeout, computed_timeout);
  2215. select_has_timeout = true;
  2216. }
  2217. Thread::SelectBlocker::FDVector rfds;
  2218. Thread::SelectBlocker::FDVector wfds;
  2219. Thread::SelectBlocker::FDVector efds;
  2220. auto transfer_fds = [&](auto* fds, auto& vector) -> int {
  2221. vector.clear_with_capacity();
  2222. if (!fds)
  2223. return 0;
  2224. for (int fd = 0; fd < nfds; ++fd) {
  2225. if (FD_ISSET(fd, fds)) {
  2226. if (!file_description(fd)) {
  2227. dbg() << *current << " sys$select: Bad fd number " << fd;
  2228. return -EBADF;
  2229. }
  2230. vector.append(fd);
  2231. }
  2232. }
  2233. return 0;
  2234. };
  2235. if (int error = transfer_fds(writefds, wfds))
  2236. return error;
  2237. if (int error = transfer_fds(readfds, rfds))
  2238. return error;
  2239. if (int error = transfer_fds(exceptfds, efds))
  2240. return error;
  2241. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  2242. dbgprintf("%s<%u> selecting on (read:%u, write:%u), timeout=%p\n", name().characters(), pid(), rfds.size(), wfds.size(), timeout);
  2243. #endif
  2244. if (!timeout || select_has_timeout) {
  2245. if (current->block<Thread::SelectBlocker>(computed_timeout, select_has_timeout, rfds, wfds, efds) != Thread::BlockResult::WokeNormally)
  2246. return -EINTR;
  2247. }
  2248. int marked_fd_count = 0;
  2249. auto mark_fds = [&](auto* fds, auto& vector, auto should_mark) {
  2250. if (!fds)
  2251. return;
  2252. FD_ZERO(fds);
  2253. for (int fd : vector) {
  2254. if (auto description = file_description(fd); description && should_mark(*description)) {
  2255. FD_SET(fd, fds);
  2256. ++marked_fd_count;
  2257. }
  2258. }
  2259. };
  2260. mark_fds(readfds, rfds, [](auto& description) { return description.can_read(); });
  2261. mark_fds(writefds, wfds, [](auto& description) { return description.can_write(); });
  2262. // FIXME: We should also mark exceptfds as appropriate.
  2263. return marked_fd_count;
  2264. }
  2265. int Process::sys$poll(pollfd* fds, int nfds, int timeout)
  2266. {
  2267. REQUIRE_PROMISE(stdio);
  2268. if (!validate_read_typed(fds))
  2269. return -EFAULT;
  2270. SmapDisabler disabler;
  2271. Thread::SelectBlocker::FDVector rfds;
  2272. Thread::SelectBlocker::FDVector wfds;
  2273. for (int i = 0; i < nfds; ++i) {
  2274. if (fds[i].events & POLLIN)
  2275. rfds.append(fds[i].fd);
  2276. if (fds[i].events & POLLOUT)
  2277. wfds.append(fds[i].fd);
  2278. }
  2279. timeval actual_timeout;
  2280. bool has_timeout = false;
  2281. if (timeout >= 0) {
  2282. // poll is in ms, we want s/us.
  2283. struct timeval tvtimeout;
  2284. tvtimeout.tv_sec = 0;
  2285. while (timeout >= 1000) {
  2286. tvtimeout.tv_sec += 1;
  2287. timeout -= 1000;
  2288. }
  2289. tvtimeout.tv_usec = timeout * 1000;
  2290. timeval_add(kgettimeofday(), tvtimeout, actual_timeout);
  2291. has_timeout = true;
  2292. }
  2293. #if defined(DEBUG_IO) || defined(DEBUG_POLL_SELECT)
  2294. dbgprintf("%s<%u> polling on (read:%u, write:%u), timeout=%d\n", name().characters(), pid(), rfds.size(), wfds.size(), timeout);
  2295. #endif
  2296. if (has_timeout || timeout < 0) {
  2297. if (current->block<Thread::SelectBlocker>(actual_timeout, has_timeout, rfds, wfds, Thread::SelectBlocker::FDVector()) != Thread::BlockResult::WokeNormally)
  2298. return -EINTR;
  2299. }
  2300. int fds_with_revents = 0;
  2301. for (int i = 0; i < nfds; ++i) {
  2302. auto description = file_description(fds[i].fd);
  2303. if (!description) {
  2304. fds[i].revents = POLLNVAL;
  2305. continue;
  2306. }
  2307. fds[i].revents = 0;
  2308. if (fds[i].events & POLLIN && description->can_read())
  2309. fds[i].revents |= POLLIN;
  2310. if (fds[i].events & POLLOUT && description->can_write())
  2311. fds[i].revents |= POLLOUT;
  2312. if (fds[i].revents)
  2313. ++fds_with_revents;
  2314. }
  2315. return fds_with_revents;
  2316. }
  2317. Custody& Process::current_directory()
  2318. {
  2319. if (!m_cwd)
  2320. m_cwd = VFS::the().root_custody();
  2321. return *m_cwd;
  2322. }
  2323. int Process::sys$link(const Syscall::SC_link_params* user_params)
  2324. {
  2325. REQUIRE_PROMISE(cpath);
  2326. if (!validate_read_typed(user_params))
  2327. return -EFAULT;
  2328. Syscall::SC_link_params params;
  2329. copy_from_user(&params, user_params, sizeof(params));
  2330. auto old_path = validate_and_copy_string_from_user(params.old_path);
  2331. auto new_path = validate_and_copy_string_from_user(params.new_path);
  2332. if (old_path.is_null() || new_path.is_null())
  2333. return -EFAULT;
  2334. return VFS::the().link(old_path, new_path, current_directory());
  2335. }
  2336. int Process::sys$unlink(const char* user_path, size_t path_length)
  2337. {
  2338. REQUIRE_PROMISE(cpath);
  2339. if (!validate_read(user_path, path_length))
  2340. return -EFAULT;
  2341. auto path = get_syscall_path_argument(user_path, path_length);
  2342. if (path.is_error())
  2343. return path.error();
  2344. return VFS::the().unlink(path.value(), current_directory());
  2345. }
  2346. int Process::sys$symlink(const Syscall::SC_symlink_params* user_params)
  2347. {
  2348. REQUIRE_PROMISE(cpath);
  2349. if (!validate_read_typed(user_params))
  2350. return -EFAULT;
  2351. Syscall::SC_symlink_params params;
  2352. copy_from_user(&params, user_params);
  2353. auto target = get_syscall_path_argument(params.target);
  2354. if (target.is_error())
  2355. return target.error();
  2356. auto linkpath = get_syscall_path_argument(params.linkpath);
  2357. if (linkpath.is_error())
  2358. return linkpath.error();
  2359. return VFS::the().symlink(target.value(), linkpath.value(), current_directory());
  2360. }
  2361. KResultOr<String> Process::get_syscall_path_argument(const char* user_path, size_t path_length) const
  2362. {
  2363. if (path_length == 0)
  2364. return KResult(-EINVAL);
  2365. if (path_length > PATH_MAX)
  2366. return KResult(-ENAMETOOLONG);
  2367. if (!validate_read(user_path, path_length))
  2368. return KResult(-EFAULT);
  2369. return copy_string_from_user(user_path, path_length);
  2370. }
  2371. KResultOr<String> Process::get_syscall_path_argument(const Syscall::StringArgument& path) const
  2372. {
  2373. return get_syscall_path_argument(path.characters, path.length);
  2374. }
  2375. int Process::sys$rmdir(const char* user_path, size_t path_length)
  2376. {
  2377. REQUIRE_PROMISE(cpath);
  2378. auto path = get_syscall_path_argument(user_path, path_length);
  2379. if (path.is_error())
  2380. return path.error();
  2381. return VFS::the().rmdir(path.value(), current_directory());
  2382. }
  2383. int Process::sys$chmod(const char* user_path, size_t path_length, mode_t mode)
  2384. {
  2385. REQUIRE_PROMISE(fattr);
  2386. auto path = get_syscall_path_argument(user_path, path_length);
  2387. if (path.is_error())
  2388. return path.error();
  2389. return VFS::the().chmod(path.value(), mode, current_directory());
  2390. }
  2391. int Process::sys$fchmod(int fd, mode_t mode)
  2392. {
  2393. REQUIRE_PROMISE(fattr);
  2394. auto description = file_description(fd);
  2395. if (!description)
  2396. return -EBADF;
  2397. return description->chmod(mode);
  2398. }
  2399. int Process::sys$fchown(int fd, uid_t uid, gid_t gid)
  2400. {
  2401. REQUIRE_PROMISE(chown);
  2402. auto description = file_description(fd);
  2403. if (!description)
  2404. return -EBADF;
  2405. return description->chown(uid, gid);
  2406. }
  2407. int Process::sys$chown(const Syscall::SC_chown_params* user_params)
  2408. {
  2409. REQUIRE_PROMISE(chown);
  2410. if (!validate_read_typed(user_params))
  2411. return -EFAULT;
  2412. Syscall::SC_chown_params params;
  2413. copy_from_user(&params, user_params, sizeof(params));
  2414. auto path = get_syscall_path_argument(params.path);
  2415. if (path.is_error())
  2416. return path.error();
  2417. return VFS::the().chown(path.value(), params.uid, params.gid, current_directory());
  2418. }
  2419. void Process::finalize()
  2420. {
  2421. ASSERT(current == g_finalizer);
  2422. dbgprintf("Finalizing Process %s(%u)\n", m_name.characters(), m_pid);
  2423. m_fds.clear();
  2424. m_tty = nullptr;
  2425. m_executable = nullptr;
  2426. m_cwd = nullptr;
  2427. m_root_directory = nullptr;
  2428. m_elf_loader = nullptr;
  2429. disown_all_shared_buffers();
  2430. {
  2431. InterruptDisabler disabler;
  2432. if (auto* parent_thread = Thread::from_tid(m_ppid)) {
  2433. if (parent_thread->m_signal_action_data[SIGCHLD].flags & SA_NOCLDWAIT) {
  2434. // NOTE: If the parent doesn't care about this process, let it go.
  2435. m_ppid = 0;
  2436. } else {
  2437. parent_thread->send_signal(SIGCHLD, this);
  2438. }
  2439. }
  2440. }
  2441. m_dead = true;
  2442. }
  2443. void Process::die()
  2444. {
  2445. // Let go of the TTY, otherwise a slave PTY may keep the master PTY from
  2446. // getting an EOF when the last process using the slave PTY dies.
  2447. // If the master PTY owner relies on an EOF to know when to wait() on a
  2448. // slave owner, we have to allow the PTY pair to be torn down.
  2449. m_tty = nullptr;
  2450. if (m_tracer)
  2451. m_tracer->set_dead();
  2452. {
  2453. // Tell the threads to unwind and die.
  2454. InterruptDisabler disabler;
  2455. for_each_thread([](Thread& thread) {
  2456. thread.set_should_die();
  2457. return IterationDecision::Continue;
  2458. });
  2459. }
  2460. }
  2461. size_t Process::amount_dirty_private() const
  2462. {
  2463. // FIXME: This gets a bit more complicated for Regions sharing the same underlying VMObject.
  2464. // The main issue I'm thinking of is when the VMObject has physical pages that none of the Regions are mapping.
  2465. // That's probably a situation that needs to be looked at in general.
  2466. size_t amount = 0;
  2467. for (auto& region : m_regions) {
  2468. if (!region.is_shared())
  2469. amount += region.amount_dirty();
  2470. }
  2471. return amount;
  2472. }
  2473. size_t Process::amount_clean_inode() const
  2474. {
  2475. HashTable<const InodeVMObject*> vmobjects;
  2476. for (auto& region : m_regions) {
  2477. if (region.vmobject().is_inode())
  2478. vmobjects.set(&static_cast<const InodeVMObject&>(region.vmobject()));
  2479. }
  2480. size_t amount = 0;
  2481. for (auto& vmobject : vmobjects)
  2482. amount += vmobject->amount_clean();
  2483. return amount;
  2484. }
  2485. size_t Process::amount_virtual() const
  2486. {
  2487. size_t amount = 0;
  2488. for (auto& region : m_regions) {
  2489. amount += region.size();
  2490. }
  2491. return amount;
  2492. }
  2493. size_t Process::amount_resident() const
  2494. {
  2495. // FIXME: This will double count if multiple regions use the same physical page.
  2496. size_t amount = 0;
  2497. for (auto& region : m_regions) {
  2498. amount += region.amount_resident();
  2499. }
  2500. return amount;
  2501. }
  2502. size_t Process::amount_shared() const
  2503. {
  2504. // FIXME: This will double count if multiple regions use the same physical page.
  2505. // FIXME: It doesn't work at the moment, since it relies on PhysicalPage ref counts,
  2506. // and each PhysicalPage is only reffed by its VMObject. This needs to be refactored
  2507. // so that every Region contributes +1 ref to each of its PhysicalPages.
  2508. size_t amount = 0;
  2509. for (auto& region : m_regions) {
  2510. amount += region.amount_shared();
  2511. }
  2512. return amount;
  2513. }
  2514. size_t Process::amount_purgeable_volatile() const
  2515. {
  2516. size_t amount = 0;
  2517. for (auto& region : m_regions) {
  2518. if (region.vmobject().is_purgeable() && static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  2519. amount += region.amount_resident();
  2520. }
  2521. return amount;
  2522. }
  2523. size_t Process::amount_purgeable_nonvolatile() const
  2524. {
  2525. size_t amount = 0;
  2526. for (auto& region : m_regions) {
  2527. if (region.vmobject().is_purgeable() && !static_cast<const PurgeableVMObject&>(region.vmobject()).is_volatile())
  2528. amount += region.amount_resident();
  2529. }
  2530. return amount;
  2531. }
  2532. #define REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(domain) \
  2533. do { \
  2534. if (domain == AF_INET) \
  2535. REQUIRE_PROMISE(inet); \
  2536. else if (domain == AF_LOCAL) \
  2537. REQUIRE_PROMISE(unix); \
  2538. } while (0)
  2539. int Process::sys$socket(int domain, int type, int protocol)
  2540. {
  2541. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(domain);
  2542. if ((type & SOCK_TYPE_MASK) == SOCK_RAW && !is_superuser())
  2543. return -EACCES;
  2544. int fd = alloc_fd();
  2545. if (fd < 0)
  2546. return fd;
  2547. auto result = Socket::create(domain, type, protocol);
  2548. if (result.is_error())
  2549. return result.error();
  2550. auto description = FileDescription::create(*result.value());
  2551. description->set_readable(true);
  2552. description->set_writable(true);
  2553. unsigned flags = 0;
  2554. if (type & SOCK_CLOEXEC)
  2555. flags |= FD_CLOEXEC;
  2556. if (type & SOCK_NONBLOCK)
  2557. description->set_blocking(false);
  2558. m_fds[fd].set(move(description), flags);
  2559. return fd;
  2560. }
  2561. int Process::sys$bind(int sockfd, const sockaddr* address, socklen_t address_length)
  2562. {
  2563. if (!validate_read(address, address_length))
  2564. return -EFAULT;
  2565. auto description = file_description(sockfd);
  2566. if (!description)
  2567. return -EBADF;
  2568. if (!description->is_socket())
  2569. return -ENOTSOCK;
  2570. auto& socket = *description->socket();
  2571. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2572. return socket.bind(address, address_length);
  2573. }
  2574. int Process::sys$listen(int sockfd, int backlog)
  2575. {
  2576. auto description = file_description(sockfd);
  2577. if (!description)
  2578. return -EBADF;
  2579. if (!description->is_socket())
  2580. return -ENOTSOCK;
  2581. auto& socket = *description->socket();
  2582. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2583. if (socket.is_connected())
  2584. return -EINVAL;
  2585. return socket.listen(backlog);
  2586. }
  2587. int Process::sys$accept(int accepting_socket_fd, sockaddr* address, socklen_t* address_size)
  2588. {
  2589. if (!validate_write_typed(address_size))
  2590. return -EFAULT;
  2591. SmapDisabler disabler;
  2592. if (!validate_write(address, *address_size))
  2593. return -EFAULT;
  2594. int accepted_socket_fd = alloc_fd();
  2595. if (accepted_socket_fd < 0)
  2596. return accepted_socket_fd;
  2597. auto accepting_socket_description = file_description(accepting_socket_fd);
  2598. if (!accepting_socket_description)
  2599. return -EBADF;
  2600. if (!accepting_socket_description->is_socket())
  2601. return -ENOTSOCK;
  2602. auto& socket = *accepting_socket_description->socket();
  2603. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2604. if (!socket.can_accept()) {
  2605. if (accepting_socket_description->is_blocking()) {
  2606. if (current->block<Thread::AcceptBlocker>(*accepting_socket_description) != Thread::BlockResult::WokeNormally)
  2607. return -EINTR;
  2608. } else {
  2609. return -EAGAIN;
  2610. }
  2611. }
  2612. auto accepted_socket = socket.accept();
  2613. ASSERT(accepted_socket);
  2614. bool success = accepted_socket->get_peer_address(address, address_size);
  2615. ASSERT(success);
  2616. auto accepted_socket_description = FileDescription::create(*accepted_socket);
  2617. accepted_socket_description->set_readable(true);
  2618. accepted_socket_description->set_writable(true);
  2619. // NOTE: The accepted socket inherits fd flags from the accepting socket.
  2620. // I'm not sure if this matches other systems but it makes sense to me.
  2621. accepted_socket_description->set_blocking(accepting_socket_description->is_blocking());
  2622. m_fds[accepted_socket_fd].set(move(accepted_socket_description), m_fds[accepting_socket_fd].flags);
  2623. // NOTE: Moving this state to Completed is what causes connect() to unblock on the client side.
  2624. accepted_socket->set_setup_state(Socket::SetupState::Completed);
  2625. return accepted_socket_fd;
  2626. }
  2627. int Process::sys$connect(int sockfd, const sockaddr* address, socklen_t address_size)
  2628. {
  2629. if (!validate_read(address, address_size))
  2630. return -EFAULT;
  2631. int fd = alloc_fd();
  2632. if (fd < 0)
  2633. return fd;
  2634. auto description = file_description(sockfd);
  2635. if (!description)
  2636. return -EBADF;
  2637. if (!description->is_socket())
  2638. return -ENOTSOCK;
  2639. auto& socket = *description->socket();
  2640. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2641. SmapDisabler disabler;
  2642. return socket.connect(*description, address, address_size, description->is_blocking() ? ShouldBlock::Yes : ShouldBlock::No);
  2643. }
  2644. ssize_t Process::sys$sendto(const Syscall::SC_sendto_params* user_params)
  2645. {
  2646. if (!validate_read_typed(user_params))
  2647. return -EFAULT;
  2648. Syscall::SC_sendto_params params;
  2649. copy_from_user(&params, user_params);
  2650. int flags = params.flags;
  2651. const sockaddr* addr = params.addr;
  2652. socklen_t addr_length = params.addr_length;
  2653. if (!validate(params.data))
  2654. return -EFAULT;
  2655. if (addr && !validate_read(addr, addr_length))
  2656. return -EFAULT;
  2657. auto description = file_description(params.sockfd);
  2658. if (!description)
  2659. return -EBADF;
  2660. if (!description->is_socket())
  2661. return -ENOTSOCK;
  2662. SmapDisabler disabler;
  2663. auto& socket = *description->socket();
  2664. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2665. return socket.sendto(*description, params.data.data, params.data.size, flags, addr, addr_length);
  2666. }
  2667. ssize_t Process::sys$recvfrom(const Syscall::SC_recvfrom_params* user_params)
  2668. {
  2669. if (!validate_read_typed(user_params))
  2670. return -EFAULT;
  2671. Syscall::SC_recvfrom_params params;
  2672. copy_from_user(&params, user_params);
  2673. int flags = params.flags;
  2674. sockaddr* addr = params.addr;
  2675. socklen_t* addr_length = params.addr_length;
  2676. SmapDisabler disabler;
  2677. if (!validate(params.buffer))
  2678. return -EFAULT;
  2679. if (addr_length) {
  2680. if (!validate_write_typed(addr_length))
  2681. return -EFAULT;
  2682. if (!validate_write(addr, *addr_length))
  2683. return -EFAULT;
  2684. } else if (addr) {
  2685. return -EINVAL;
  2686. }
  2687. auto description = file_description(params.sockfd);
  2688. if (!description)
  2689. return -EBADF;
  2690. if (!description->is_socket())
  2691. return -ENOTSOCK;
  2692. auto& socket = *description->socket();
  2693. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2694. bool original_blocking = description->is_blocking();
  2695. if (flags & MSG_DONTWAIT)
  2696. description->set_blocking(false);
  2697. auto nrecv = socket.recvfrom(*description, params.buffer.data, params.buffer.size, flags, addr, addr_length);
  2698. if (flags & MSG_DONTWAIT)
  2699. description->set_blocking(original_blocking);
  2700. return nrecv;
  2701. }
  2702. int Process::sys$getsockname(int sockfd, sockaddr* addr, socklen_t* addrlen)
  2703. {
  2704. if (!validate_read_typed(addrlen))
  2705. return -EFAULT;
  2706. SmapDisabler disabler;
  2707. if (*addrlen <= 0)
  2708. return -EINVAL;
  2709. if (!validate_write(addr, *addrlen))
  2710. return -EFAULT;
  2711. auto description = file_description(sockfd);
  2712. if (!description)
  2713. return -EBADF;
  2714. if (!description->is_socket())
  2715. return -ENOTSOCK;
  2716. auto& socket = *description->socket();
  2717. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2718. if (!socket.get_local_address(addr, addrlen))
  2719. return -EINVAL; // FIXME: Should this be another error? I'm not sure.
  2720. return 0;
  2721. }
  2722. int Process::sys$getpeername(int sockfd, sockaddr* addr, socklen_t* addrlen)
  2723. {
  2724. if (!validate_read_typed(addrlen))
  2725. return -EFAULT;
  2726. SmapDisabler disabler;
  2727. if (*addrlen <= 0)
  2728. return -EINVAL;
  2729. if (!validate_write(addr, *addrlen))
  2730. return -EFAULT;
  2731. auto description = file_description(sockfd);
  2732. if (!description)
  2733. return -EBADF;
  2734. if (!description->is_socket())
  2735. return -ENOTSOCK;
  2736. auto& socket = *description->socket();
  2737. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2738. if (socket.setup_state() != Socket::SetupState::Completed)
  2739. return -ENOTCONN;
  2740. if (!socket.get_peer_address(addr, addrlen))
  2741. return -EINVAL; // FIXME: Should this be another error? I'm not sure.
  2742. return 0;
  2743. }
  2744. int Process::sys$sched_setparam(pid_t pid, const struct sched_param* param)
  2745. {
  2746. REQUIRE_PROMISE(proc);
  2747. if (!validate_read_typed(param))
  2748. return -EFAULT;
  2749. int desired_priority;
  2750. copy_from_user(&desired_priority, &param->sched_priority, sizeof(desired_priority));
  2751. InterruptDisabler disabler;
  2752. auto* peer = this;
  2753. if (pid != 0)
  2754. peer = Process::from_pid(pid);
  2755. if (!peer)
  2756. return -ESRCH;
  2757. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  2758. return -EPERM;
  2759. if (desired_priority < THREAD_PRIORITY_MIN || desired_priority > THREAD_PRIORITY_MAX)
  2760. return -EINVAL;
  2761. peer->any_thread().set_priority((u32)desired_priority);
  2762. return 0;
  2763. }
  2764. int Process::sys$sched_getparam(pid_t pid, struct sched_param* param)
  2765. {
  2766. REQUIRE_PROMISE(proc);
  2767. if (!validate_write_typed(param))
  2768. return -EFAULT;
  2769. InterruptDisabler disabler;
  2770. auto* peer = this;
  2771. if (pid != 0)
  2772. peer = Process::from_pid(pid);
  2773. if (!peer)
  2774. return -ESRCH;
  2775. if (!is_superuser() && m_euid != peer->m_uid && m_uid != peer->m_uid)
  2776. return -EPERM;
  2777. // FIXME: This doesn't seem like the way to get the right thread!
  2778. int priority = peer->any_thread().priority();
  2779. copy_to_user(&param->sched_priority, &priority, sizeof(priority));
  2780. return 0;
  2781. }
  2782. int Process::sys$getsockopt(const Syscall::SC_getsockopt_params* params)
  2783. {
  2784. if (!validate_read_typed(params))
  2785. return -EFAULT;
  2786. SmapDisabler disabler;
  2787. int sockfd = params->sockfd;
  2788. int level = params->level;
  2789. int option = params->option;
  2790. void* value = params->value;
  2791. socklen_t* value_size = params->value_size;
  2792. if (!validate_write_typed(value_size))
  2793. return -EFAULT;
  2794. if (!validate_write(value, *value_size))
  2795. return -EFAULT;
  2796. auto description = file_description(sockfd);
  2797. if (!description)
  2798. return -EBADF;
  2799. if (!description->is_socket())
  2800. return -ENOTSOCK;
  2801. auto& socket = *description->socket();
  2802. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2803. return socket.getsockopt(*description, level, option, value, value_size);
  2804. }
  2805. int Process::sys$setsockopt(const Syscall::SC_setsockopt_params* params)
  2806. {
  2807. if (!validate_read_typed(params))
  2808. return -EFAULT;
  2809. SmapDisabler disabler;
  2810. int sockfd = params->sockfd;
  2811. int level = params->level;
  2812. int option = params->option;
  2813. const void* value = params->value;
  2814. socklen_t value_size = params->value_size;
  2815. if (!validate_read(value, value_size))
  2816. return -EFAULT;
  2817. auto description = file_description(sockfd);
  2818. if (!description)
  2819. return -EBADF;
  2820. if (!description->is_socket())
  2821. return -ENOTSOCK;
  2822. auto& socket = *description->socket();
  2823. REQUIRE_PROMISE_FOR_SOCKET_DOMAIN(socket.domain());
  2824. return socket.setsockopt(level, option, value, value_size);
  2825. }
  2826. void Process::disown_all_shared_buffers()
  2827. {
  2828. LOCKER(shared_buffers().lock());
  2829. Vector<SharedBuffer*, 32> buffers_to_disown;
  2830. for (auto& it : shared_buffers().resource())
  2831. buffers_to_disown.append(it.value.ptr());
  2832. for (auto* shared_buffer : buffers_to_disown)
  2833. shared_buffer->disown(m_pid);
  2834. }
  2835. int Process::sys$create_shared_buffer(int size, void** buffer)
  2836. {
  2837. REQUIRE_PROMISE(shared_buffer);
  2838. if (!size || size < 0)
  2839. return -EINVAL;
  2840. size = PAGE_ROUND_UP(size);
  2841. if (!validate_write_typed(buffer))
  2842. return -EFAULT;
  2843. LOCKER(shared_buffers().lock());
  2844. static int s_next_shared_buffer_id;
  2845. int shared_buffer_id = ++s_next_shared_buffer_id;
  2846. auto shared_buffer = make<SharedBuffer>(shared_buffer_id, size);
  2847. shared_buffer->share_with(m_pid);
  2848. void* address = shared_buffer->ref_for_process_and_get_address(*this);
  2849. {
  2850. SmapDisabler disabler;
  2851. *buffer = address;
  2852. }
  2853. ASSERT((int)shared_buffer->size() >= size);
  2854. #ifdef SHARED_BUFFER_DEBUG
  2855. kprintf("%s(%u): Created shared buffer %d @ %p (%u bytes, vmobject is %u)\n", name().characters(), pid(), shared_buffer_id, *buffer, size, shared_buffer->size());
  2856. #endif
  2857. shared_buffers().resource().set(shared_buffer_id, move(shared_buffer));
  2858. return shared_buffer_id;
  2859. }
  2860. int Process::sys$share_buffer_with(int shared_buffer_id, pid_t peer_pid)
  2861. {
  2862. REQUIRE_PROMISE(shared_buffer);
  2863. if (!peer_pid || peer_pid < 0 || peer_pid == m_pid)
  2864. return -EINVAL;
  2865. LOCKER(shared_buffers().lock());
  2866. auto it = shared_buffers().resource().find(shared_buffer_id);
  2867. if (it == shared_buffers().resource().end())
  2868. return -EINVAL;
  2869. auto& shared_buffer = *(*it).value;
  2870. if (!shared_buffer.is_shared_with(m_pid))
  2871. return -EPERM;
  2872. {
  2873. InterruptDisabler disabler;
  2874. auto* peer = Process::from_pid(peer_pid);
  2875. if (!peer)
  2876. return -ESRCH;
  2877. }
  2878. shared_buffer.share_with(peer_pid);
  2879. return 0;
  2880. }
  2881. int Process::sys$share_buffer_globally(int shared_buffer_id)
  2882. {
  2883. REQUIRE_PROMISE(shared_buffer);
  2884. LOCKER(shared_buffers().lock());
  2885. auto it = shared_buffers().resource().find(shared_buffer_id);
  2886. if (it == shared_buffers().resource().end())
  2887. return -EINVAL;
  2888. auto& shared_buffer = *(*it).value;
  2889. if (!shared_buffer.is_shared_with(m_pid))
  2890. return -EPERM;
  2891. shared_buffer.share_globally();
  2892. return 0;
  2893. }
  2894. int Process::sys$release_shared_buffer(int shared_buffer_id)
  2895. {
  2896. REQUIRE_PROMISE(shared_buffer);
  2897. LOCKER(shared_buffers().lock());
  2898. auto it = shared_buffers().resource().find(shared_buffer_id);
  2899. if (it == shared_buffers().resource().end())
  2900. return -EINVAL;
  2901. auto& shared_buffer = *(*it).value;
  2902. if (!shared_buffer.is_shared_with(m_pid))
  2903. return -EPERM;
  2904. #ifdef SHARED_BUFFER_DEBUG
  2905. kprintf("%s(%u): Releasing shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2906. #endif
  2907. shared_buffer.deref_for_process(*this);
  2908. return 0;
  2909. }
  2910. void* Process::sys$get_shared_buffer(int shared_buffer_id)
  2911. {
  2912. REQUIRE_PROMISE(shared_buffer);
  2913. LOCKER(shared_buffers().lock());
  2914. auto it = shared_buffers().resource().find(shared_buffer_id);
  2915. if (it == shared_buffers().resource().end())
  2916. return (void*)-EINVAL;
  2917. auto& shared_buffer = *(*it).value;
  2918. if (!shared_buffer.is_shared_with(m_pid))
  2919. return (void*)-EPERM;
  2920. #ifdef SHARED_BUFFER_DEBUG
  2921. kprintf("%s(%u): Retaining shared buffer %d, buffer count: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2922. #endif
  2923. return shared_buffer.ref_for_process_and_get_address(*this);
  2924. }
  2925. int Process::sys$seal_shared_buffer(int shared_buffer_id)
  2926. {
  2927. REQUIRE_PROMISE(shared_buffer);
  2928. LOCKER(shared_buffers().lock());
  2929. auto it = shared_buffers().resource().find(shared_buffer_id);
  2930. if (it == shared_buffers().resource().end())
  2931. return -EINVAL;
  2932. auto& shared_buffer = *(*it).value;
  2933. if (!shared_buffer.is_shared_with(m_pid))
  2934. return -EPERM;
  2935. #ifdef SHARED_BUFFER_DEBUG
  2936. kprintf("%s(%u): Sealing shared buffer %d\n", name().characters(), pid(), shared_buffer_id);
  2937. #endif
  2938. shared_buffer.seal();
  2939. return 0;
  2940. }
  2941. int Process::sys$get_shared_buffer_size(int shared_buffer_id)
  2942. {
  2943. REQUIRE_PROMISE(shared_buffer);
  2944. LOCKER(shared_buffers().lock());
  2945. auto it = shared_buffers().resource().find(shared_buffer_id);
  2946. if (it == shared_buffers().resource().end())
  2947. return -EINVAL;
  2948. auto& shared_buffer = *(*it).value;
  2949. if (!shared_buffer.is_shared_with(m_pid))
  2950. return -EPERM;
  2951. #ifdef SHARED_BUFFER_DEBUG
  2952. kprintf("%s(%u): Get shared buffer %d size: %u\n", name().characters(), pid(), shared_buffer_id, shared_buffers().resource().size());
  2953. #endif
  2954. return shared_buffer.size();
  2955. }
  2956. int Process::sys$set_shared_buffer_volatile(int shared_buffer_id, bool state)
  2957. {
  2958. REQUIRE_PROMISE(shared_buffer);
  2959. LOCKER(shared_buffers().lock());
  2960. auto it = shared_buffers().resource().find(shared_buffer_id);
  2961. if (it == shared_buffers().resource().end())
  2962. return -EINVAL;
  2963. auto& shared_buffer = *(*it).value;
  2964. if (!shared_buffer.is_shared_with(m_pid))
  2965. return -EPERM;
  2966. #ifdef SHARED_BUFFER_DEBUG
  2967. kprintf("%s(%u): Set shared buffer %d volatile: %u\n", name().characters(), pid(), shared_buffer_id, state);
  2968. #endif
  2969. if (!state) {
  2970. bool was_purged = shared_buffer.vmobject().was_purged();
  2971. shared_buffer.vmobject().set_volatile(state);
  2972. shared_buffer.vmobject().set_was_purged(false);
  2973. return was_purged ? 1 : 0;
  2974. }
  2975. shared_buffer.vmobject().set_volatile(true);
  2976. return 0;
  2977. }
  2978. void Process::terminate_due_to_signal(u8 signal)
  2979. {
  2980. ASSERT_INTERRUPTS_DISABLED();
  2981. ASSERT(signal < 32);
  2982. dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
  2983. m_termination_status = 0;
  2984. m_termination_signal = signal;
  2985. die();
  2986. }
  2987. void Process::send_signal(u8 signal, Process* sender)
  2988. {
  2989. InterruptDisabler disabler;
  2990. auto* thread = Thread::from_tid(m_pid);
  2991. if (!thread)
  2992. thread = &any_thread();
  2993. thread->send_signal(signal, sender);
  2994. }
  2995. int Process::sys$create_thread(void* (*entry)(void*), void* argument, const Syscall::SC_create_thread_params* user_params)
  2996. {
  2997. REQUIRE_PROMISE(thread);
  2998. if (!validate_read((const void*)entry, sizeof(void*)))
  2999. return -EFAULT;
  3000. if (!validate_read_typed(user_params))
  3001. return -EFAULT;
  3002. Syscall::SC_create_thread_params params;
  3003. copy_from_user(&params, user_params);
  3004. unsigned detach_state = params.m_detach_state;
  3005. int schedule_priority = params.m_schedule_priority;
  3006. void* stack_location = params.m_stack_location;
  3007. unsigned stack_size = params.m_stack_size;
  3008. if (!validate_write(stack_location, stack_size))
  3009. return -EFAULT;
  3010. u32 user_stack_address = reinterpret_cast<u32>(stack_location) + stack_size;
  3011. if (!MM.validate_user_stack(*this, VirtualAddress(user_stack_address - 4)))
  3012. return -EFAULT;
  3013. // FIXME: return EAGAIN if Thread::all_threads().size() is greater than PTHREAD_THREADS_MAX
  3014. int requested_thread_priority = schedule_priority;
  3015. if (requested_thread_priority < THREAD_PRIORITY_MIN || requested_thread_priority > THREAD_PRIORITY_MAX)
  3016. return -EINVAL;
  3017. bool is_thread_joinable = (0 == detach_state);
  3018. // FIXME: Do something with guard pages?
  3019. auto* thread = new Thread(*this);
  3020. // We know this thread is not the main_thread,
  3021. // So give it a unique name until the user calls $set_thread_name on it
  3022. // length + 4 to give space for our extra junk at the end
  3023. StringBuilder builder(m_name.length() + 4);
  3024. builder.append(m_name);
  3025. builder.appendf("[%d]", thread->tid());
  3026. thread->set_name(builder.to_string());
  3027. thread->set_priority(requested_thread_priority);
  3028. thread->set_joinable(is_thread_joinable);
  3029. auto& tss = thread->tss();
  3030. tss.eip = (u32)entry;
  3031. tss.eflags = 0x0202;
  3032. tss.cr3 = page_directory().cr3();
  3033. tss.esp = user_stack_address;
  3034. // NOTE: The stack needs to be 16-byte aligned.
  3035. thread->push_value_on_stack((u32)argument);
  3036. thread->push_value_on_stack(0);
  3037. thread->make_thread_specific_region({});
  3038. thread->set_state(Thread::State::Runnable);
  3039. return thread->tid();
  3040. }
  3041. void Process::sys$exit_thread(void* exit_value)
  3042. {
  3043. REQUIRE_PROMISE(thread);
  3044. cli();
  3045. current->m_exit_value = exit_value;
  3046. current->set_should_die();
  3047. big_lock().unlock_if_locked();
  3048. current->die_if_needed();
  3049. ASSERT_NOT_REACHED();
  3050. }
  3051. int Process::sys$detach_thread(int tid)
  3052. {
  3053. REQUIRE_PROMISE(thread);
  3054. auto* thread = Thread::from_tid(tid);
  3055. if (!thread || thread->pid() != pid())
  3056. return -ESRCH;
  3057. if (!thread->is_joinable())
  3058. return -EINVAL;
  3059. thread->set_joinable(false);
  3060. return 0;
  3061. }
  3062. int Process::sys$join_thread(int tid, void** exit_value)
  3063. {
  3064. REQUIRE_PROMISE(thread);
  3065. if (exit_value && !validate_write_typed(exit_value))
  3066. return -EFAULT;
  3067. auto* thread = Thread::from_tid(tid);
  3068. if (!thread || thread->pid() != pid())
  3069. return -ESRCH;
  3070. if (thread == current)
  3071. return -EDEADLK;
  3072. if (thread->m_joinee == current)
  3073. return -EDEADLK;
  3074. ASSERT(thread->m_joiner != current);
  3075. if (thread->m_joiner)
  3076. return -EINVAL;
  3077. if (!thread->is_joinable())
  3078. return -EINVAL;
  3079. void* joinee_exit_value = nullptr;
  3080. // NOTE: pthread_join() cannot be interrupted by signals. Only by death.
  3081. for (;;) {
  3082. auto result = current->block<Thread::JoinBlocker>(*thread, joinee_exit_value);
  3083. if (result == Thread::BlockResult::InterruptedByDeath) {
  3084. // NOTE: This cleans things up so that Thread::finalize() won't
  3085. // get confused about a missing joiner when finalizing the joinee.
  3086. InterruptDisabler disabler;
  3087. current->m_joinee->m_joiner = nullptr;
  3088. current->m_joinee = nullptr;
  3089. return 0;
  3090. }
  3091. }
  3092. // NOTE: 'thread' is very possibly deleted at this point. Clear it just to be safe.
  3093. thread = nullptr;
  3094. if (exit_value)
  3095. copy_to_user(exit_value, &joinee_exit_value, sizeof(joinee_exit_value));
  3096. return 0;
  3097. }
  3098. int Process::sys$set_thread_name(int tid, const char* user_name, size_t user_name_length)
  3099. {
  3100. REQUIRE_PROMISE(thread);
  3101. auto name = validate_and_copy_string_from_user(user_name, user_name_length);
  3102. if (name.is_null())
  3103. return -EFAULT;
  3104. const size_t max_thread_name_size = 64;
  3105. if (name.length() > max_thread_name_size)
  3106. return -EINVAL;
  3107. auto* thread = Thread::from_tid(tid);
  3108. if (!thread || thread->pid() != pid())
  3109. return -ESRCH;
  3110. thread->set_name(name);
  3111. return 0;
  3112. }
  3113. int Process::sys$get_thread_name(int tid, char* buffer, size_t buffer_size)
  3114. {
  3115. REQUIRE_PROMISE(thread);
  3116. if (buffer_size == 0)
  3117. return -EINVAL;
  3118. if (!validate_write(buffer, buffer_size))
  3119. return -EFAULT;
  3120. auto* thread = Thread::from_tid(tid);
  3121. if (!thread || thread->pid() != pid())
  3122. return -ESRCH;
  3123. if (thread->name().length() + 1 > (size_t)buffer_size)
  3124. return -ENAMETOOLONG;
  3125. copy_to_user(buffer, thread->name().characters(), thread->name().length() + 1);
  3126. return 0;
  3127. }
  3128. int Process::sys$gettid()
  3129. {
  3130. REQUIRE_PROMISE(stdio);
  3131. return current->tid();
  3132. }
  3133. int Process::sys$donate(int tid)
  3134. {
  3135. REQUIRE_PROMISE(stdio);
  3136. if (tid < 0)
  3137. return -EINVAL;
  3138. InterruptDisabler disabler;
  3139. auto* thread = Thread::from_tid(tid);
  3140. if (!thread || thread->pid() != pid())
  3141. return -ESRCH;
  3142. Scheduler::donate_to(thread, "sys$donate");
  3143. return 0;
  3144. }
  3145. int Process::sys$rename(const Syscall::SC_rename_params* user_params)
  3146. {
  3147. REQUIRE_PROMISE(cpath);
  3148. if (!validate_read_typed(user_params))
  3149. return -EFAULT;
  3150. Syscall::SC_rename_params params;
  3151. copy_from_user(&params, user_params);
  3152. auto old_path = get_syscall_path_argument(params.old_path);
  3153. if (old_path.is_error())
  3154. return old_path.error();
  3155. auto new_path = get_syscall_path_argument(params.new_path);
  3156. if (new_path.is_error())
  3157. return new_path.error();
  3158. return VFS::the().rename(old_path.value(), new_path.value(), current_directory());
  3159. }
  3160. int Process::sys$ftruncate(int fd, off_t length)
  3161. {
  3162. REQUIRE_PROMISE(stdio);
  3163. if (length < 0)
  3164. return -EINVAL;
  3165. auto description = file_description(fd);
  3166. if (!description)
  3167. return -EBADF;
  3168. if (!description->is_writable())
  3169. return -EBADF;
  3170. return description->truncate(length);
  3171. }
  3172. int Process::sys$watch_file(const char* user_path, size_t path_length)
  3173. {
  3174. REQUIRE_PROMISE(rpath);
  3175. auto path = get_syscall_path_argument(user_path, path_length);
  3176. if (path.is_error())
  3177. return path.error();
  3178. auto custody_or_error = VFS::the().resolve_path(path.value(), current_directory());
  3179. if (custody_or_error.is_error())
  3180. return custody_or_error.error();
  3181. auto& custody = custody_or_error.value();
  3182. auto& inode = custody->inode();
  3183. if (!inode.fs().supports_watchers())
  3184. return -ENOTSUP;
  3185. int fd = alloc_fd();
  3186. if (fd < 0)
  3187. return fd;
  3188. m_fds[fd].set(FileDescription::create(*InodeWatcher::create(inode)));
  3189. m_fds[fd].description->set_readable(true);
  3190. return fd;
  3191. }
  3192. int Process::sys$systrace(pid_t pid)
  3193. {
  3194. REQUIRE_PROMISE(proc);
  3195. InterruptDisabler disabler;
  3196. auto* peer = Process::from_pid(pid);
  3197. if (!peer)
  3198. return -ESRCH;
  3199. if (peer->uid() != m_euid)
  3200. return -EACCES;
  3201. int fd = alloc_fd();
  3202. if (fd < 0)
  3203. return fd;
  3204. auto description = FileDescription::create(peer->ensure_tracer());
  3205. description->set_readable(true);
  3206. m_fds[fd].set(move(description), 0);
  3207. return fd;
  3208. }
  3209. int Process::sys$halt()
  3210. {
  3211. if (!is_superuser())
  3212. return -EPERM;
  3213. REQUIRE_NO_PROMISES;
  3214. dbgprintf("acquiring FS locks...\n");
  3215. FS::lock_all();
  3216. dbgprintf("syncing mounted filesystems...\n");
  3217. FS::sync();
  3218. dbgprintf("attempting system shutdown...\n");
  3219. IO::out16(0x604, 0x2000);
  3220. return ESUCCESS;
  3221. }
  3222. int Process::sys$reboot()
  3223. {
  3224. if (!is_superuser())
  3225. return -EPERM;
  3226. REQUIRE_NO_PROMISES;
  3227. dbgprintf("acquiring FS locks...\n");
  3228. FS::lock_all();
  3229. dbgprintf("syncing mounted filesystems...\n");
  3230. FS::sync();
  3231. dbgprintf("attempting reboot via KB Controller...\n");
  3232. IO::out8(0x64, 0xFE);
  3233. return ESUCCESS;
  3234. }
  3235. int Process::sys$mount(const Syscall::SC_mount_params* user_params)
  3236. {
  3237. if (!is_superuser())
  3238. return -EPERM;
  3239. REQUIRE_NO_PROMISES;
  3240. if (!validate_read_typed(user_params))
  3241. return -EFAULT;
  3242. Syscall::SC_mount_params params;
  3243. copy_from_user(&params, user_params);
  3244. auto source = validate_and_copy_string_from_user(params.source);
  3245. auto target = validate_and_copy_string_from_user(params.target);
  3246. auto fs_type = validate_and_copy_string_from_user(params.fs_type);
  3247. if (source.is_null() || target.is_null() || fs_type.is_null())
  3248. return -EFAULT;
  3249. dbg() << "mount " << fs_type << ": source " << source << " @ " << target;
  3250. auto custody_or_error = VFS::the().resolve_path(target, current_directory());
  3251. if (custody_or_error.is_error())
  3252. return custody_or_error.error();
  3253. auto& target_custody = custody_or_error.value();
  3254. RefPtr<FS> fs;
  3255. if (params.flags & MS_BIND) {
  3256. // We're doing a bind mount.
  3257. auto source_or_error = VFS::the().resolve_path(source, current_directory());
  3258. if (source_or_error.is_error())
  3259. return source_or_error.error();
  3260. auto& source_custody = source_or_error.value();
  3261. return VFS::the().bind_mount(source_custody, target_custody);
  3262. }
  3263. if (fs_type == "ext2" || fs_type == "Ext2FS") {
  3264. auto metadata_or_error = VFS::the().lookup_metadata(source, current_directory());
  3265. if (metadata_or_error.is_error())
  3266. return metadata_or_error.error();
  3267. auto major = metadata_or_error.value().major_device;
  3268. auto minor = metadata_or_error.value().minor_device;
  3269. auto* device = Device::get_device(major, minor);
  3270. if (!device) {
  3271. dbg() << "mount: device (" << major << "," << minor << ") not found";
  3272. return -ENODEV;
  3273. }
  3274. if (!device->is_disk_device()) {
  3275. dbg() << "mount: device (" << major << "," << minor << ") is not a DiskDevice";
  3276. return -ENODEV;
  3277. }
  3278. auto& disk_device = static_cast<DiskDevice&>(*device);
  3279. dbg() << "mount: attempting to mount device (" << major << "," << minor << ") on " << target;
  3280. fs = Ext2FS::create(disk_device);
  3281. } else if (fs_type == "proc" || fs_type == "ProcFS") {
  3282. fs = ProcFS::create();
  3283. } else if (fs_type == "devpts" || fs_type == "DevPtsFS") {
  3284. fs = DevPtsFS::create();
  3285. } else if (fs_type == "tmp" || fs_type == "TmpFS") {
  3286. fs = TmpFS::create();
  3287. } else {
  3288. return -ENODEV;
  3289. }
  3290. if (!fs->initialize()) {
  3291. dbg() << "mount: failed to initialize " << fs_type << " filesystem on " << source;
  3292. return -ENODEV;
  3293. }
  3294. auto result = VFS::the().mount(fs.release_nonnull(), target_custody, params.flags);
  3295. dbg() << "mount: successfully mounted " << source << " on " << target;
  3296. return result;
  3297. }
  3298. int Process::sys$umount(const char* user_mountpoint, size_t mountpoint_length)
  3299. {
  3300. if (!is_superuser())
  3301. return -EPERM;
  3302. REQUIRE_NO_PROMISES;
  3303. if (!validate_read(user_mountpoint, mountpoint_length))
  3304. return -EFAULT;
  3305. auto mountpoint = get_syscall_path_argument(user_mountpoint, mountpoint_length);
  3306. if (mountpoint.is_error())
  3307. return mountpoint.error();
  3308. auto metadata_or_error = VFS::the().lookup_metadata(mountpoint.value(), current_directory());
  3309. if (metadata_or_error.is_error())
  3310. return metadata_or_error.error();
  3311. auto guest_inode_id = metadata_or_error.value().inode;
  3312. return VFS::the().unmount(guest_inode_id);
  3313. }
  3314. ProcessTracer& Process::ensure_tracer()
  3315. {
  3316. if (!m_tracer)
  3317. m_tracer = ProcessTracer::create(m_pid);
  3318. return *m_tracer;
  3319. }
  3320. void Process::FileDescriptionAndFlags::clear()
  3321. {
  3322. description = nullptr;
  3323. flags = 0;
  3324. }
  3325. void Process::FileDescriptionAndFlags::set(NonnullRefPtr<FileDescription>&& d, u32 f)
  3326. {
  3327. description = move(d);
  3328. flags = f;
  3329. }
  3330. int Process::sys$mknod(const Syscall::SC_mknod_params* user_params)
  3331. {
  3332. REQUIRE_PROMISE(dpath);
  3333. if (!validate_read_typed(user_params))
  3334. return -EFAULT;
  3335. Syscall::SC_mknod_params params;
  3336. copy_from_user(&params, user_params);
  3337. if (!is_superuser() && !is_regular_file(params.mode) && !is_fifo(params.mode) && !is_socket(params.mode))
  3338. return -EPERM;
  3339. auto path = get_syscall_path_argument(params.path);
  3340. if (path.is_error())
  3341. return path.error();
  3342. return VFS::the().mknod(path.value(), params.mode & ~umask(), params.dev, current_directory());
  3343. }
  3344. int Process::sys$dump_backtrace()
  3345. {
  3346. dump_backtrace();
  3347. return 0;
  3348. }
  3349. int Process::sys$dbgputch(u8 ch)
  3350. {
  3351. IO::out8(0xe9, ch);
  3352. return 0;
  3353. }
  3354. int Process::sys$dbgputstr(const u8* characters, int length)
  3355. {
  3356. if (!length)
  3357. return 0;
  3358. if (!validate_read(characters, length))
  3359. return -EFAULT;
  3360. SmapDisabler disabler;
  3361. for (int i = 0; i < length; ++i)
  3362. IO::out8(0xe9, characters[i]);
  3363. return 0;
  3364. }
  3365. KBuffer Process::backtrace(ProcessInspectionHandle& handle) const
  3366. {
  3367. KBufferBuilder builder;
  3368. for_each_thread([&](Thread& thread) {
  3369. builder.appendf("Thread %d (%s):\n", thread.tid(), thread.name().characters());
  3370. builder.append(thread.backtrace(handle));
  3371. return IterationDecision::Continue;
  3372. });
  3373. return builder.build();
  3374. }
  3375. int Process::sys$set_process_icon(int icon_id)
  3376. {
  3377. REQUIRE_PROMISE(shared_buffer);
  3378. LOCKER(shared_buffers().lock());
  3379. auto it = shared_buffers().resource().find(icon_id);
  3380. if (it == shared_buffers().resource().end())
  3381. return -EINVAL;
  3382. auto& shared_buffer = *(*it).value;
  3383. if (!shared_buffer.is_shared_with(m_pid))
  3384. return -EPERM;
  3385. m_icon_id = icon_id;
  3386. return 0;
  3387. }
  3388. int Process::sys$get_process_name(char* buffer, int buffer_size)
  3389. {
  3390. REQUIRE_PROMISE(stdio);
  3391. if (buffer_size <= 0)
  3392. return -EINVAL;
  3393. if (!validate_write(buffer, buffer_size))
  3394. return -EFAULT;
  3395. if (m_name.length() + 1 > (size_t)buffer_size)
  3396. return -ENAMETOOLONG;
  3397. copy_to_user(buffer, m_name.characters(), m_name.length() + 1);
  3398. return 0;
  3399. }
  3400. // We don't use the flag yet, but we could use it for distinguishing
  3401. // random source like Linux, unlike the OpenBSD equivalent. However, if we
  3402. // do, we should be able of the caveats that Linux has dealt with.
  3403. int Process::sys$getrandom(void* buffer, size_t buffer_size, unsigned int flags __attribute__((unused)))
  3404. {
  3405. REQUIRE_PROMISE(stdio);
  3406. if (buffer_size <= 0)
  3407. return -EINVAL;
  3408. if (!validate_write(buffer, buffer_size))
  3409. return -EFAULT;
  3410. get_good_random_bytes((u8*)buffer, buffer_size);
  3411. return 0;
  3412. }
  3413. int Process::sys$setkeymap(const Syscall::SC_setkeymap_params* params)
  3414. {
  3415. if (!is_superuser())
  3416. return -EPERM;
  3417. REQUIRE_NO_PROMISES;
  3418. if (!validate_read_typed(params))
  3419. return -EFAULT;
  3420. const char* map = params->map;
  3421. const char* shift_map = params->shift_map;
  3422. const char* alt_map = params->alt_map;
  3423. const char* altgr_map = params->altgr_map;
  3424. if (!validate_read(map, 0x80))
  3425. return -EFAULT;
  3426. if (!validate_read(shift_map, 0x80))
  3427. return -EFAULT;
  3428. if (!validate_read(alt_map, 0x80))
  3429. return -EFAULT;
  3430. if (!validate_read(altgr_map, 0x80))
  3431. return -EFAULT;
  3432. KeyboardDevice::the().set_maps(map, shift_map, alt_map, altgr_map);
  3433. return 0;
  3434. }
  3435. int Process::sys$clock_gettime(clockid_t clock_id, timespec* ts)
  3436. {
  3437. REQUIRE_PROMISE(stdio);
  3438. if (!validate_write_typed(ts))
  3439. return -EFAULT;
  3440. SmapDisabler disabler;
  3441. switch (clock_id) {
  3442. case CLOCK_MONOTONIC:
  3443. ts->tv_sec = g_uptime / TICKS_PER_SECOND;
  3444. ts->tv_nsec = (g_uptime % TICKS_PER_SECOND) * 1000000;
  3445. break;
  3446. default:
  3447. return -EINVAL;
  3448. }
  3449. return 0;
  3450. }
  3451. int Process::sys$clock_nanosleep(const Syscall::SC_clock_nanosleep_params* user_params)
  3452. {
  3453. REQUIRE_PROMISE(stdio);
  3454. if (!validate_read_typed(user_params))
  3455. return -EFAULT;
  3456. Syscall::SC_clock_nanosleep_params params;
  3457. copy_from_user(&params, user_params);
  3458. if (params.requested_sleep && !validate_read_typed(params.requested_sleep))
  3459. return -EFAULT;
  3460. timespec requested_sleep;
  3461. copy_from_user(&requested_sleep, params.requested_sleep);
  3462. if (params.remaining_sleep && !validate_write_typed(params.remaining_sleep))
  3463. return -EFAULT;
  3464. bool is_absolute = params.flags & TIMER_ABSTIME;
  3465. switch (params.clock_id) {
  3466. case CLOCK_MONOTONIC: {
  3467. u64 wakeup_time;
  3468. if (is_absolute) {
  3469. u64 time_to_wake = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000);
  3470. wakeup_time = current->sleep_until(time_to_wake);
  3471. } else {
  3472. u32 ticks_to_sleep = (requested_sleep.tv_sec * 1000 + requested_sleep.tv_nsec / 1000000);
  3473. if (!ticks_to_sleep)
  3474. return 0;
  3475. wakeup_time = current->sleep(ticks_to_sleep);
  3476. }
  3477. if (wakeup_time > g_uptime) {
  3478. u32 ticks_left = wakeup_time - g_uptime;
  3479. if (!is_absolute && params.remaining_sleep) {
  3480. timespec remaining_sleep;
  3481. memset(&remaining_sleep, 0, sizeof(timespec));
  3482. remaining_sleep.tv_sec = ticks_left / TICKS_PER_SECOND;
  3483. ticks_left -= remaining_sleep.tv_sec * TICKS_PER_SECOND;
  3484. remaining_sleep.tv_nsec = ticks_left * 1000000;
  3485. copy_to_user(params.remaining_sleep, &remaining_sleep);
  3486. }
  3487. return -EINTR;
  3488. }
  3489. return 0;
  3490. }
  3491. default:
  3492. return -EINVAL;
  3493. }
  3494. }
  3495. int Process::sys$sync()
  3496. {
  3497. REQUIRE_PROMISE(stdio);
  3498. VFS::the().sync();
  3499. return 0;
  3500. }
  3501. int Process::sys$yield()
  3502. {
  3503. REQUIRE_PROMISE(stdio);
  3504. current->yield_without_holding_big_lock();
  3505. return 0;
  3506. }
  3507. int Process::sys$beep()
  3508. {
  3509. PCSpeaker::tone_on(440);
  3510. u64 wakeup_time = current->sleep(100);
  3511. PCSpeaker::tone_off();
  3512. if (wakeup_time > g_uptime)
  3513. return -EINTR;
  3514. return 0;
  3515. }
  3516. int Process::sys$module_load(const char* user_path, size_t path_length)
  3517. {
  3518. if (!is_superuser())
  3519. return -EPERM;
  3520. REQUIRE_NO_PROMISES;
  3521. auto path = get_syscall_path_argument(user_path, path_length);
  3522. if (path.is_error())
  3523. return path.error();
  3524. auto description_or_error = VFS::the().open(path.value(), 0, 0, current_directory());
  3525. if (description_or_error.is_error())
  3526. return description_or_error.error();
  3527. auto& description = description_or_error.value();
  3528. auto payload = description->read_entire_file();
  3529. auto storage = KBuffer::create_with_size(payload.size());
  3530. memcpy(storage.data(), payload.data(), payload.size());
  3531. payload.clear();
  3532. auto elf_image = make<ELFImage>(storage.data(), storage.size());
  3533. if (!elf_image->parse())
  3534. return -ENOEXEC;
  3535. HashMap<String, u8*> section_storage_by_name;
  3536. auto module = make<Module>();
  3537. elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELFImage::Section& section) {
  3538. auto section_storage = KBuffer::copy(section.raw_data(), section.size(), Region::Access::Read | Region::Access::Write | Region::Access::Execute);
  3539. section_storage_by_name.set(section.name(), section_storage.data());
  3540. module->sections.append(move(section_storage));
  3541. return IterationDecision::Continue;
  3542. });
  3543. bool missing_symbols = false;
  3544. elf_image->for_each_section_of_type(SHT_PROGBITS, [&](const ELFImage::Section& section) {
  3545. auto* section_storage = section_storage_by_name.get(section.name()).value_or(nullptr);
  3546. ASSERT(section_storage);
  3547. section.relocations().for_each_relocation([&](const ELFImage::Relocation& relocation) {
  3548. auto& patch_ptr = *reinterpret_cast<ptrdiff_t*>(section_storage + relocation.offset());
  3549. switch (relocation.type()) {
  3550. case R_386_PC32: {
  3551. // PC-relative relocation
  3552. dbg() << "PC-relative relocation: " << relocation.symbol().name();
  3553. u32 symbol_address = address_for_kernel_symbol(relocation.symbol().name());
  3554. if (symbol_address == 0)
  3555. missing_symbols = true;
  3556. dbg() << " Symbol address: " << (void*)symbol_address;
  3557. ptrdiff_t relative_offset = (char*)symbol_address - ((char*)&patch_ptr + 4);
  3558. patch_ptr = relative_offset;
  3559. break;
  3560. }
  3561. case R_386_32: // Absolute relocation
  3562. dbg() << "Absolute relocation: '" << relocation.symbol().name() << "' value:" << relocation.symbol().value() << ", index:" << relocation.symbol_index();
  3563. if (relocation.symbol().bind() == STB_LOCAL) {
  3564. auto* section_storage_containing_symbol = section_storage_by_name.get(relocation.symbol().section().name()).value_or(nullptr);
  3565. ASSERT(section_storage_containing_symbol);
  3566. u32 symbol_address = (ptrdiff_t)(section_storage_containing_symbol + relocation.symbol().value());
  3567. if (symbol_address == 0)
  3568. missing_symbols = true;
  3569. dbg() << " Symbol address: " << (void*)symbol_address;
  3570. patch_ptr += symbol_address;
  3571. } else if (relocation.symbol().bind() == STB_GLOBAL) {
  3572. u32 symbol_address = address_for_kernel_symbol(relocation.symbol().name());
  3573. if (symbol_address == 0)
  3574. missing_symbols = true;
  3575. dbg() << " Symbol address: " << (void*)symbol_address;
  3576. patch_ptr += symbol_address;
  3577. } else {
  3578. ASSERT_NOT_REACHED();
  3579. }
  3580. break;
  3581. }
  3582. return IterationDecision::Continue;
  3583. });
  3584. return IterationDecision::Continue;
  3585. });
  3586. if (missing_symbols)
  3587. return -ENOENT;
  3588. auto* text_base = section_storage_by_name.get(".text").value_or(nullptr);
  3589. if (!text_base) {
  3590. dbg() << "No .text section found in module!";
  3591. return -EINVAL;
  3592. }
  3593. elf_image->for_each_symbol([&](const ELFImage::Symbol& symbol) {
  3594. dbg() << " - " << symbol.type() << " '" << symbol.name() << "' @ " << (void*)symbol.value() << ", size=" << symbol.size();
  3595. if (!strcmp(symbol.name(), "module_init")) {
  3596. module->module_init = (ModuleInitPtr)(text_base + symbol.value());
  3597. } else if (!strcmp(symbol.name(), "module_fini")) {
  3598. module->module_fini = (ModuleFiniPtr)(text_base + symbol.value());
  3599. } else if (!strcmp(symbol.name(), "module_name")) {
  3600. const u8* storage = section_storage_by_name.get(symbol.section().name()).value_or(nullptr);
  3601. if (storage)
  3602. module->name = String((const char*)(storage + symbol.value()));
  3603. }
  3604. return IterationDecision::Continue;
  3605. });
  3606. if (!module->module_init)
  3607. return -EINVAL;
  3608. if (g_modules->contains(module->name)) {
  3609. dbg() << "a module with the name " << module->name << " is already loaded; please unload it first";
  3610. return -EEXIST;
  3611. }
  3612. module->module_init();
  3613. auto name = module->name;
  3614. g_modules->set(name, move(module));
  3615. return 0;
  3616. }
  3617. int Process::sys$module_unload(const char* user_name, size_t name_length)
  3618. {
  3619. if (!is_superuser())
  3620. return -EPERM;
  3621. REQUIRE_NO_PROMISES;
  3622. auto module_name = validate_and_copy_string_from_user(user_name, name_length);
  3623. if (module_name.is_null())
  3624. return -EFAULT;
  3625. auto it = g_modules->find(module_name);
  3626. if (it == g_modules->end())
  3627. return -ENOENT;
  3628. if (it->value->module_fini)
  3629. it->value->module_fini();
  3630. g_modules->remove(it);
  3631. return 0;
  3632. }
  3633. int Process::sys$profiling_enable(pid_t pid)
  3634. {
  3635. REQUIRE_NO_PROMISES;
  3636. InterruptDisabler disabler;
  3637. auto* process = Process::from_pid(pid);
  3638. if (!process)
  3639. return -ESRCH;
  3640. if (!is_superuser() && process->uid() != m_uid)
  3641. return -EPERM;
  3642. Profiling::start(*process);
  3643. process->set_profiling(true);
  3644. return 0;
  3645. }
  3646. int Process::sys$profiling_disable(pid_t pid)
  3647. {
  3648. InterruptDisabler disabler;
  3649. auto* process = Process::from_pid(pid);
  3650. if (!process)
  3651. return -ESRCH;
  3652. if (!is_superuser() && process->uid() != m_uid)
  3653. return -EPERM;
  3654. process->set_profiling(false);
  3655. Profiling::stop();
  3656. return 0;
  3657. }
  3658. void* Process::sys$get_kernel_info_page()
  3659. {
  3660. REQUIRE_PROMISE(stdio);
  3661. return s_info_page_address_for_userspace.as_ptr();
  3662. }
  3663. Thread& Process::any_thread()
  3664. {
  3665. Thread* found_thread = nullptr;
  3666. for_each_thread([&](auto& thread) {
  3667. found_thread = &thread;
  3668. return IterationDecision::Break;
  3669. });
  3670. ASSERT(found_thread);
  3671. return *found_thread;
  3672. }
  3673. WaitQueue& Process::futex_queue(i32* userspace_address)
  3674. {
  3675. auto& queue = m_futex_queues.ensure((u32)userspace_address);
  3676. if (!queue)
  3677. queue = make<WaitQueue>();
  3678. return *queue;
  3679. }
  3680. int Process::sys$futex(const Syscall::SC_futex_params* user_params)
  3681. {
  3682. REQUIRE_PROMISE(thread);
  3683. if (!validate_read_typed(user_params))
  3684. return -EFAULT;
  3685. Syscall::SC_futex_params params;
  3686. copy_from_user(&params, user_params, sizeof(params));
  3687. i32* userspace_address = params.userspace_address;
  3688. int futex_op = params.futex_op;
  3689. i32 value = params.val;
  3690. const timespec* user_timeout = params.timeout;
  3691. if (!validate_read_typed(userspace_address))
  3692. return -EFAULT;
  3693. if (user_timeout && !validate_read_typed(user_timeout))
  3694. return -EFAULT;
  3695. timespec timeout { 0, 0 };
  3696. if (user_timeout)
  3697. copy_from_user(&timeout, user_timeout, sizeof(timeout));
  3698. i32 user_value;
  3699. switch (futex_op) {
  3700. case FUTEX_WAIT:
  3701. copy_from_user(&user_value, userspace_address, sizeof(user_value));
  3702. if (user_value != value)
  3703. return -EAGAIN;
  3704. // FIXME: This is supposed to be interruptible by a signal, but right now WaitQueue cannot be interrupted.
  3705. // FIXME: Support timeout!
  3706. current->wait_on(futex_queue(userspace_address));
  3707. break;
  3708. case FUTEX_WAKE:
  3709. if (value == 0)
  3710. return 0;
  3711. if (value == 1) {
  3712. futex_queue(userspace_address).wake_one();
  3713. } else {
  3714. // FIXME: Wake exactly (value) waiters.
  3715. futex_queue(userspace_address).wake_all();
  3716. }
  3717. break;
  3718. }
  3719. return 0;
  3720. }
  3721. int Process::sys$set_thread_boost(int tid, int amount)
  3722. {
  3723. REQUIRE_PROMISE(proc);
  3724. if (amount < 0 || amount > 20)
  3725. return -EINVAL;
  3726. InterruptDisabler disabler;
  3727. auto* thread = Thread::from_tid(tid);
  3728. if (!thread)
  3729. return -ESRCH;
  3730. if (thread->state() == Thread::State::Dead || thread->state() == Thread::State::Dying)
  3731. return -ESRCH;
  3732. if (!is_superuser() && thread->process().uid() != euid())
  3733. return -EPERM;
  3734. thread->set_priority_boost(amount);
  3735. return 0;
  3736. }
  3737. int Process::sys$set_process_boost(pid_t pid, int amount)
  3738. {
  3739. REQUIRE_PROMISE(proc);
  3740. if (amount < 0 || amount > 20)
  3741. return -EINVAL;
  3742. InterruptDisabler disabler;
  3743. auto* process = Process::from_pid(pid);
  3744. if (!process || process->is_dead())
  3745. return -ESRCH;
  3746. if (!is_superuser() && process->uid() != euid())
  3747. return -EPERM;
  3748. process->m_priority_boost = amount;
  3749. return 0;
  3750. }
  3751. int Process::sys$chroot(const char* user_path, size_t path_length)
  3752. {
  3753. if (!is_superuser())
  3754. return -EPERM;
  3755. REQUIRE_PROMISE(chroot);
  3756. auto path = get_syscall_path_argument(user_path, path_length);
  3757. if (path.is_error())
  3758. return path.error();
  3759. auto directory_or_error = VFS::the().open_directory(path.value(), current_directory());
  3760. if (directory_or_error.is_error())
  3761. return directory_or_error.error();
  3762. auto directory = directory_or_error.value();
  3763. m_root_directory_for_procfs = directory;
  3764. set_root_directory(Custody::create(nullptr, "", directory->inode(), directory->mount_flags()));
  3765. return 0;
  3766. }
  3767. Custody& Process::root_directory()
  3768. {
  3769. if (!m_root_directory)
  3770. m_root_directory = VFS::the().root_custody();
  3771. return *m_root_directory;
  3772. }
  3773. Custody& Process::root_directory_for_procfs()
  3774. {
  3775. if (!m_root_directory_for_procfs)
  3776. m_root_directory_for_procfs = root_directory();
  3777. return *m_root_directory_for_procfs;
  3778. }
  3779. void Process::set_root_directory(const Custody& root)
  3780. {
  3781. m_root_directory = root;
  3782. }
  3783. int Process::sys$pledge(const Syscall::SC_pledge_params* user_params)
  3784. {
  3785. if (!validate_read_typed(user_params))
  3786. return -EFAULT;
  3787. Syscall::SC_pledge_params params;
  3788. copy_from_user(&params, user_params);
  3789. if (params.promises.length > 1024 || params.execpromises.length > 1024)
  3790. return -E2BIG;
  3791. String promises;
  3792. if (params.promises.characters) {
  3793. promises = validate_and_copy_string_from_user(params.promises);
  3794. if (promises.is_null())
  3795. return -EFAULT;
  3796. }
  3797. String execpromises;
  3798. if (params.execpromises.characters) {
  3799. execpromises = validate_and_copy_string_from_user(params.execpromises);
  3800. if (execpromises.is_null())
  3801. return -EFAULT;
  3802. }
  3803. auto parse_pledge = [&](auto& pledge_spec, u32& mask) {
  3804. auto parts = pledge_spec.split_view(' ');
  3805. for (auto& part : parts) {
  3806. #define __ENUMERATE_PLEDGE_PROMISE(x) \
  3807. if (part == #x) { \
  3808. mask |= (1u << (u32)Pledge::x); \
  3809. continue; \
  3810. }
  3811. ENUMERATE_PLEDGE_PROMISES
  3812. #undef __ENUMERATE_PLEDGE_PROMISE
  3813. if (part == "dns") {
  3814. // "dns" is an alias for "unix" since DNS queries go via LookupServer
  3815. mask |= (1u << (u32)Pledge::unix);
  3816. continue;
  3817. }
  3818. return false;
  3819. }
  3820. return true;
  3821. };
  3822. if (!promises.is_null()) {
  3823. u32 new_promises = 0;
  3824. if (!parse_pledge(promises, new_promises))
  3825. return -EINVAL;
  3826. if (m_promises && new_promises & ~m_promises)
  3827. return -EPERM;
  3828. m_promises = new_promises;
  3829. }
  3830. if (!execpromises.is_null()) {
  3831. u32 new_execpromises = 0;
  3832. if (!parse_pledge(execpromises, new_execpromises))
  3833. return -EINVAL;
  3834. if (m_execpromises && new_execpromises & ~m_execpromises)
  3835. return -EPERM;
  3836. m_execpromises = new_execpromises;
  3837. }
  3838. return 0;
  3839. }