Process.cpp 112 KB

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