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