Process.cpp 123 KB

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