Process.cpp 114 KB

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