Process.cpp 125 KB

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