Process.cpp 155 KB

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