Process.cpp 151 KB

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