Process.cpp 124 KB

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