Process.cpp 158 KB

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