Process.cpp 99 KB

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