Process.cpp 153 KB

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