Process.cpp 135 KB

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