Process.cpp 145 KB

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