Process.cpp 120 KB

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