Process.cpp 97 KB

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