Process.cpp 120 KB

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