Process.cpp 125 KB

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