Process.cpp 118 KB

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