Process.cpp 142 KB

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