Process.cpp 95 KB

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