Process.cpp 91 KB

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