Process.cpp 107 KB

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