Process.cpp 99 KB

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