Process.cpp 112 KB

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