Process.cpp 85 KB

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