Process.cpp 88 KB

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