Process.cpp 148 KB

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