Process.cpp 128 KB

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