Process.cpp 129 KB

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