Process.cpp 150 KB

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