Process.cpp 118 KB

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