Process.cpp 151 KB

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