Process.cpp 104 KB

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