Process.cpp 158 KB

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