Process.cpp 95 KB

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