lwp_syscall.c 400 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321
  1. /*
  2. * Copyright (c) 2006-2025 RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-06-10 Bernard first version
  9. * 2021-02-03 lizhirui add limit condition for network syscall and add 64-bit arch support
  10. * 2021-02-06 lizhirui fix some bugs
  11. * 2021-02-12 lizhirui add 64-bit support for sys_brk
  12. * 2021-02-20 lizhirui fix some warnings
  13. * 2023-03-13 WangXiaoyao Format & fix syscall return value
  14. * 2023-07-06 Shell adapt the signal API, and clone, fork to new implementation of lwp signal
  15. * 2023-07-27 Shell Move tid_put() from lwp_free() to sys_exit()
  16. * 2023-11-16 xqyjlj fix some syscalls (about sched_*, get/setpriority)
  17. * 2023-11-17 xqyjlj add process group and session support
  18. * 2023-11-30 Shell Fix sys_setitimer() and exit(status)
  19. */
  20. #define __RT_IPC_SOURCE__
  21. #define _GNU_SOURCE
  22. /* RT-Thread System call */
  23. #include <rtthread.h>
  24. #include <rthw.h>
  25. #include <board.h>
  26. #include <string.h>
  27. #include <stdint.h>
  28. #define DBG_TAG "lwp.syscall"
  29. #define DBG_LVL DBG_INFO
  30. #include <rtdbg.h>
  31. #include "syscall_generic.h"
  32. #include "libc_musl.h"
  33. #include "lwp_internal.h"
  34. #ifdef ARCH_MM_MMU
  35. #include <mm_aspace.h>
  36. #include <lwp_user_mm.h>
  37. #include <lwp_arch.h>
  38. #endif
  39. #include <fcntl.h>
  40. #include <sys/utsname.h>
  41. #ifdef RT_USING_DFS
  42. #include <eventfd.h>
  43. #include <poll.h>
  44. #include <sys/epoll.h>
  45. #include <sys/select.h>
  46. #include <dfs_file.h>
  47. #ifdef RT_USING_DFS_V2
  48. #include <dfs_dentry.h>
  49. #endif
  50. #include <unistd.h>
  51. #include <stdio.h> /* rename() */
  52. #include <sys/stat.h>
  53. #include <sys/statfs.h> /* statfs() */
  54. #include <sys/timerfd.h>
  55. #include <sys/ioctl.h>
  56. #ifdef RT_USING_MUSLLIBC
  57. #include <sys/signalfd.h>
  58. #endif
  59. #endif
  60. #include "mqueue.h"
  61. #ifdef RT_USING_SAL
  62. #include <netdev_ipaddr.h>
  63. #include <netdev.h>
  64. #include <sal_netdb.h>
  65. #include <sal_socket.h>
  66. #include <sys/socket.h>
  67. #endif /* RT_USING_SAL */
  68. #if (defined(RT_USING_SAL) && defined(SAL_USING_POSIX))
  69. #include <sys/socket.h>
  70. #define SYSCALL_NET(f) f
  71. #else
  72. #define SYSCALL_NET(f) SYSCALL_SIGN(sys_notimpl)
  73. #endif /* (defined(RT_USING_SAL) && defined(SAL_USING_POSIX)) */
  74. #if defined(RT_USING_DFS) && defined(ARCH_MM_MMU)
  75. #define SYSCALL_USPACE(f) f
  76. #else
  77. #define SYSCALL_USPACE(f) SYSCALL_SIGN(sys_notimpl)
  78. #endif /* defined(RT_USING_DFS) && defined(ARCH_MM_MMU) */
  79. #include "lwp_ipc_internal.h"
  80. #include <sched.h>
  81. #include <sys/sysinfo.h>
  82. #ifndef GRND_NONBLOCK
  83. #define GRND_NONBLOCK 0x0001
  84. #endif /* GRND_NONBLOCK */
  85. #ifndef GRND_RANDOM
  86. #define GRND_RANDOM 0x0002
  87. #endif /*GRND_RANDOM */
  88. #ifndef RT_USING_POSIX_TIMER
  89. #error "No definition RT_USING_POSIX_TIMER"
  90. #endif /* RT_USING_POSIX_TIMER */
  91. #ifndef RT_USING_POSIX_CLOCK
  92. #error "No definition RT_USING_POSIX_CLOCK"
  93. #endif /* RT_USING_POSIX_CLOCK */
  94. void lwp_cleanup(struct rt_thread *tid);
  95. #ifdef ARCH_MM_MMU
  96. #define ALLOC_KERNEL_STACK_SIZE 5120
  97. static void *kmem_get(size_t size)
  98. {
  99. return rt_malloc(size);
  100. }
  101. static void kmem_put(void *kptr)
  102. {
  103. rt_free(kptr);
  104. }
  105. #else /* ARCH_MM_MMU */
  106. #define ALLOC_KERNEL_STACK_SIZE 1536
  107. #define ALLOC_KERNEL_STACK_SIZE_MIN 1024
  108. #define ALLOC_KERNEL_STACK_SIZE_MAX 4096
  109. extern void set_user_context(void *stack);
  110. #endif /* ARCH_MM_MMU */
  111. #ifdef RT_USING_SAL
  112. /* The same socket option is defined differently in the user interfaces and the
  113. * implementation. The options should be converted in the kernel. */
  114. #include "lwp_sys_socket.h"
  115. static void convert_sockopt(int *level, int *optname)
  116. {
  117. if (*level == INTF_SOL_SOCKET)
  118. {
  119. *level = IMPL_SOL_SOCKET;
  120. switch (*optname)
  121. {
  122. case INTF_SO_REUSEADDR:
  123. *optname = IMPL_SO_REUSEADDR;
  124. break;
  125. case INTF_SO_KEEPALIVE:
  126. *optname = IMPL_SO_KEEPALIVE;
  127. break;
  128. case INTF_SO_BROADCAST:
  129. *optname = IMPL_SO_BROADCAST;
  130. break;
  131. case INTF_SO_ACCEPTCONN:
  132. *optname = IMPL_SO_ACCEPTCONN;
  133. break;
  134. case INTF_SO_DONTROUTE:
  135. *optname = IMPL_SO_DONTROUTE;
  136. break;
  137. case INTF_SO_LINGER:
  138. *optname = IMPL_SO_LINGER;
  139. break;
  140. case INTF_SO_OOBINLINE:
  141. *optname = IMPL_SO_OOBINLINE;
  142. break;
  143. case INTF_SO_REUSEPORT:
  144. *optname = IMPL_SO_REUSEPORT;
  145. break;
  146. case INTF_SO_SNDBUF:
  147. *optname = IMPL_SO_SNDBUF;
  148. break;
  149. case INTF_SO_RCVBUF:
  150. *optname = IMPL_SO_RCVBUF;
  151. break;
  152. case INTF_SO_SNDLOWAT:
  153. *optname = IMPL_SO_SNDLOWAT;
  154. break;
  155. case INTF_SO_RCVLOWAT:
  156. *optname = IMPL_SO_RCVLOWAT;
  157. break;
  158. case INTF_SO_SNDTIMEO:
  159. *optname = IMPL_SO_SNDTIMEO;
  160. break;
  161. case INTF_SO_RCVTIMEO:
  162. *optname = IMPL_SO_RCVTIMEO;
  163. break;
  164. case INTF_SO_ERROR:
  165. *optname = IMPL_SO_ERROR;
  166. break;
  167. case INTF_SO_TYPE:
  168. *optname = IMPL_SO_TYPE;
  169. break;
  170. case INTF_SO_NO_CHECK:
  171. *optname = IMPL_SO_NO_CHECK;
  172. break;
  173. case INTF_SO_BINDTODEVICE:
  174. *optname = IMPL_SO_BINDTODEVICE;
  175. break;
  176. case INTF_SO_TIMESTAMPNS:
  177. *optname = IMPL_SO_TIMESTAMPNS;
  178. break;
  179. case INTF_SO_TIMESTAMPING:
  180. *optname = IMPL_SO_TIMESTAMPING;
  181. break;
  182. case INTF_SO_SELECT_ERR_QUEUE:
  183. *optname = IMPL_SO_SELECT_ERR_QUEUE;
  184. break;
  185. /*
  186. * SO_DONTLINGER (*level = ((int)(~SO_LINGER))),
  187. * SO_USELOOPBACK (*level = 0x0040) and
  188. * SO_CONTIMEO (*level = 0x1009) are not supported for now.
  189. */
  190. default:
  191. *optname = 0;
  192. break;
  193. }
  194. return;
  195. }
  196. if (*level == INTF_IPPROTO_IP)
  197. {
  198. *level = IMPL_IPPROTO_IP;
  199. switch (*optname)
  200. {
  201. case INTF_IP_TTL:
  202. *optname = IMPL_IP_TTL;
  203. break;
  204. case INTF_IP_TOS:
  205. *optname = IMPL_IP_TOS;
  206. break;
  207. case INTF_IP_MULTICAST_TTL:
  208. *optname = IMPL_IP_MULTICAST_TTL;
  209. break;
  210. case INTF_IP_MULTICAST_IF:
  211. *optname = IMPL_IP_MULTICAST_IF;
  212. break;
  213. case INTF_IP_MULTICAST_LOOP:
  214. *optname = IMPL_IP_MULTICAST_LOOP;
  215. break;
  216. case INTF_IP_ADD_MEMBERSHIP:
  217. *optname = IMPL_IP_ADD_MEMBERSHIP;
  218. break;
  219. case INTF_IP_DROP_MEMBERSHIP:
  220. *optname = IMPL_IP_DROP_MEMBERSHIP;
  221. break;
  222. default:
  223. break;
  224. }
  225. }
  226. if (*level == INTF_IPPROTO_TCP)
  227. {
  228. *level = IMPL_IPPROTO_TCP;
  229. switch (*optname)
  230. {
  231. case INTF_TCP_NODELAY:
  232. *optname = IMPL_TCP_NODELAY;
  233. break;
  234. case INTF_TCP_KEEPALIVE:
  235. *optname = IMPL_TCP_KEEPALIVE;
  236. break;
  237. case INTF_TCP_KEEPIDLE:
  238. *optname = IMPL_TCP_KEEPIDLE;
  239. break;
  240. case INTF_TCP_KEEPINTVL:
  241. *optname = IMPL_TCP_KEEPINTVL;
  242. break;
  243. case INTF_TCP_KEEPCNT:
  244. *optname = IMPL_TCP_KEEPCNT;
  245. break;
  246. default:
  247. break;
  248. }
  249. return;
  250. }
  251. if (*level == INTF_IPPROTO_IPV6)
  252. {
  253. *level = IMPL_IPPROTO_IPV6;
  254. switch (*optname)
  255. {
  256. case INTF_IPV6_V6ONLY:
  257. *optname = IMPL_IPV6_V6ONLY;
  258. break;
  259. default:
  260. break;
  261. }
  262. return;
  263. }
  264. }
  265. #endif /* RT_USING_SAL */
  266. #if defined(RT_USING_LWIP) || defined(SAL_USING_UNET)
  267. static void sockaddr_tolwip(const struct musl_sockaddr *std, struct sockaddr *lwip)
  268. {
  269. if (std && lwip)
  270. {
  271. lwip->sa_len = sizeof(*lwip);
  272. lwip->sa_family = (sa_family_t)std->sa_family;
  273. memcpy(lwip->sa_data, std->sa_data, sizeof(lwip->sa_data));
  274. }
  275. }
  276. static void sockaddr_tomusl(const struct sockaddr *lwip, struct musl_sockaddr *std)
  277. {
  278. if (std && lwip)
  279. {
  280. std->sa_family = (uint16_t)lwip->sa_family;
  281. memcpy(std->sa_data, lwip->sa_data, sizeof(std->sa_data));
  282. }
  283. }
  284. #endif
  285. static void _crt_thread_entry(void *parameter)
  286. {
  287. rt_thread_t tid;
  288. rt_size_t user_stack;
  289. tid = rt_thread_self();
  290. user_stack = (rt_size_t)tid->user_stack + tid->user_stack_size;
  291. user_stack &= ~7; /* align 8 */
  292. #ifdef ARCH_MM_MMU
  293. arch_crt_start_umode(parameter, tid->user_entry, (void *)user_stack, (char *)tid->stack_addr + tid->stack_size);
  294. #else
  295. set_user_context((void *)user_stack);
  296. arch_start_umode(parameter, tid->user_entry, ((struct rt_lwp *)tid->lwp)->data_entry, (void *)user_stack);
  297. #endif /* ARCH_MM_MMU */
  298. }
  299. /**
  300. * @brief Terminates all threads in the current thread group.
  301. *
  302. * This system call ends execution for all threads within the same thread group,
  303. * releasing resources such as memory and file descriptors. It is typically used
  304. * in multithreaded environments to ensure a clean exit for the entire process.
  305. *
  306. * @param value The exit code to be returned to the parent process.
  307. * @return sysret_t: return value of the system call execution.
  308. */
  309. sysret_t sys_exit_group(int value)
  310. {
  311. sysret_t rc = 0;
  312. lwp_status_t lwp_status;
  313. struct rt_lwp *lwp = lwp_self();
  314. if (lwp)
  315. {
  316. lwp_status = LWP_CREATE_STAT_EXIT(value);
  317. lwp_exit(lwp, lwp_status);
  318. }
  319. else
  320. {
  321. LOG_E("Can't find matching process of current thread");
  322. rc = -EINVAL;
  323. }
  324. return rc;
  325. }
  326. /**
  327. * @brief Terminates the calling thread and exits the process.
  328. *
  329. * This system call ends the execution of the calling thread and the process
  330. * it belongs to.
  331. *
  332. * @param status The exit code to be returned to the parent process.
  333. * A value of 0 typically indicates successful execution, while
  334. * non-zero values indicate an error or specific exit condition.
  335. * @return sysret_t: return value of the system call execution.
  336. *
  337. * @note Unlike `sys_exit_group`, which terminates all threads in a thread group,
  338. * `sys_exit` only terminates the calling thread and the process.
  339. */
  340. sysret_t sys_exit(int status)
  341. {
  342. sysret_t rc = 0;
  343. rt_thread_t tid;
  344. tid = rt_thread_self();
  345. if (tid && tid->lwp)
  346. {
  347. lwp_thread_exit(tid, status);
  348. }
  349. else
  350. {
  351. LOG_E("Can't find matching process of current thread");
  352. rc = -EINVAL;
  353. }
  354. return rc;
  355. }
  356. /**
  357. * @brief Reads data from a file descriptor into a buffer.
  358. *
  359. * This system call reads up to `nbyte` bytes of data from the file descriptor
  360. * specified by `fd` into the buffer pointed to by `buf`.
  361. *
  362. * @param fd The file descriptor to read from. This should be a valid file
  363. * descriptor obtained through system calls like `open()` or `socket()`.
  364. * @param buf A pointer to the buffer where the read data will be stored. The buffer
  365. * must have enough space to accommodate up to `nbyte` bytes.
  366. * @param nbyte The maximum number of bytes to read. If the file contains fewer
  367. * bytes than `nbyte`, only the available bytes will be read.
  368. * @return The number of bytes actually read, which may be less than `nbyte` if fewer
  369. * bytes are available or if the end of the file is reached. Returns `0` if
  370. * the end of the file is encountered. On error, returns `errno`.
  371. * @warning Ensure the buffer `buf` has sufficient space to hold the requested number
  372. * of bytes, as failing to do so may result in undefined behavior.
  373. */
  374. ssize_t sys_read(int fd, void *buf, size_t nbyte)
  375. {
  376. #ifdef ARCH_MM_MMU
  377. void *kmem = RT_NULL;
  378. ssize_t ret = -1;
  379. if (!nbyte)
  380. {
  381. return -EINVAL;
  382. }
  383. if (!lwp_user_accessable((void *)buf, nbyte))
  384. {
  385. return -EFAULT;
  386. }
  387. kmem = kmem_get(nbyte);
  388. if (!kmem)
  389. {
  390. return -ENOMEM;
  391. }
  392. ret = read(fd, kmem, nbyte);
  393. if (ret > 0)
  394. {
  395. if (ret != lwp_put_to_user(buf, kmem, ret))
  396. return -EFAULT;
  397. }
  398. if (ret < 0)
  399. {
  400. ret = GET_ERRNO();
  401. }
  402. kmem_put(kmem);
  403. return ret;
  404. #else
  405. if (!lwp_user_accessable((void *)buf, nbyte))
  406. {
  407. return -EFAULT;
  408. }
  409. ssize_t ret = read(fd, buf, nbyte);
  410. return (ret < 0 ? GET_ERRNO() : ret);
  411. #endif
  412. }
  413. /**
  414. * @brief Writes data from a buffer to a file descriptor.
  415. *
  416. * This system call writes up to `nbyte` bytes of data from the buffer pointed
  417. * to by `buf` to the file descriptor specified by `fd`.
  418. *
  419. * @param fd The file descriptor to write to. This should be a valid file
  420. * descriptor obtained through system calls like `open()` or `socket()`.
  421. * @param buf A pointer to the buffer containing the data to be written. The
  422. * buffer must remain valid and accessible for the duration of the
  423. * write operation.
  424. * @param nbyte The number of bytes to write from the buffer. If the file descriptor
  425. * refers to a device or a socket, the actual number of bytes written
  426. * may be less than `nbyte`.
  427. * @return The number of bytes actually written. This may be less than `nbyte` if
  428. * the underlying resource cannot accept more data at the moment. On error,
  429. * returns `errno`.
  430. *
  431. * @warning Ensure the buffer `buf` contains at least `nbyte` valid bytes to
  432. * avoid undefined behavior. Additionally, verify that `fd` is writable
  433. * to prevent errors.
  434. *
  435. * @see sys_read(), write()
  436. */
  437. ssize_t sys_write(int fd, const void *buf, size_t nbyte)
  438. {
  439. #ifdef ARCH_MM_MMU
  440. void *kmem = RT_NULL;
  441. ssize_t ret = -1;
  442. if (nbyte)
  443. {
  444. if (!lwp_user_accessable((void *)buf, nbyte))
  445. {
  446. return -EFAULT;
  447. }
  448. kmem = kmem_get(nbyte);
  449. if (!kmem)
  450. {
  451. return -ENOMEM;
  452. }
  453. lwp_get_from_user(kmem, (void *)buf, nbyte);
  454. }
  455. ret = write(fd, kmem, nbyte);
  456. if (ret < 0)
  457. {
  458. ret = GET_ERRNO();
  459. }
  460. kmem_put(kmem);
  461. return ret;
  462. #else
  463. if (!lwp_user_accessable((void *)buf, nbyte))
  464. {
  465. return -EFAULT;
  466. }
  467. ssize_t ret = write(fd, buf, nbyte);
  468. return (ret < 0 ? GET_ERRNO() : ret);
  469. #endif
  470. }
  471. /**
  472. * @brief Repositions the file offset of the open file descriptor.
  473. *
  474. * This system call sets the file offset for the open file descriptor `fd`
  475. * to a new position based on the `offset` and `whence` parameters. It is used
  476. * for seeking within files, enabling random access to file content.
  477. *
  478. * @param fd The file descriptor whose offset is to be modified. The descriptor
  479. * must refer to a file capable of seeking (e.g., regular files, but
  480. * not pipes or sockets).
  481. * @param offset The new offset value relative to the position specified by `whence`.
  482. * Can be a positive or negative value, depending on the seek direction.
  483. * @param whence The reference point for the new offset. Must be one of the following:
  484. * - `SEEK_SET`: Set the offset to `offset` bytes from the beginning of the file.
  485. * - `SEEK_CUR`: Set the offset to its current position plus `offset`.
  486. * - `SEEK_END`: Set the offset to the size of the file plus `offset`.
  487. * @return On success, returns the resulting offset location as measured in bytes
  488. * from the beginning of the file. On failure, returns `errno`.
  489. *
  490. * @warning Ensure the file descriptor `fd` supports seeking. Using this function
  491. * on non-seekable file descriptors (e.g., pipes or sockets) will result in an error.
  492. *
  493. * @see sys_read(), sys_write(), lseek()
  494. */
  495. size_t sys_lseek(int fd, size_t offset, int whence)
  496. {
  497. ssize_t ret = lseek(fd, offset, whence);
  498. return (ret < 0 ? GET_ERRNO() : ret);
  499. }
  500. /**
  501. * @brief Opens or creates a file, returning a file descriptor.
  502. *
  503. * This system call opens the file specified by `name` with the specified
  504. * access mode and flags. If the file does not exist and the `O_CREAT` flag
  505. * is provided, it will create the file with the specified mode.
  506. *
  507. * @param name The path to the file to be opened. This can be an absolute or
  508. * relative path.
  509. * @param flag Flags controlling how the file is opened. Common values include:
  510. * - `O_RDONLY`: Open the file for read-only access.
  511. * - `O_WRONLY`: Open the file for write-only access.
  512. * - `O_RDWR`: Open the file for both reading and writing.
  513. * - `O_CREAT`: Create the file if it does not exist (requires a mode argument).
  514. * - `O_TRUNC`: Truncate the file to zero length if it exists.
  515. * - `O_APPEND`: Open the file in append mode.
  516. * @param ... Optional. If the `O_CREAT` flag is specified, an additional
  517. * `mode_t` argument must be provided, defining the file permissions
  518. * (e.g., `0644` for user-read/write and group/world-read).
  519. * @return On success, returns the file descriptor.
  520. * On failure, returns `errno`.
  521. *
  522. * @note The file descriptor returned can be used with other system calls like
  523. * `sys_read()`, `sys_write()`, and `sys_close()`.
  524. *
  525. * @warning When using the `O_CREAT` flag, ensure to provide the `mode` argument
  526. * to avoid undefined behavior. Additionally, verify that the process
  527. * has the necessary permissions to access or create the file.
  528. *
  529. * @see sys_close(), sys_read(), sys_write(), open()
  530. */
  531. sysret_t sys_open(const char *name, int flag, ...)
  532. {
  533. #ifdef ARCH_MM_MMU
  534. int ret = -1;
  535. rt_size_t len = 0;
  536. char *kname = RT_NULL;
  537. mode_t mode = 0;
  538. if (!lwp_user_accessable((void *)name, 1))
  539. {
  540. return -EFAULT;
  541. }
  542. len = lwp_user_strlen(name);
  543. if (!len)
  544. {
  545. return -EINVAL;
  546. }
  547. kname = (char *)kmem_get(len + 1);
  548. if (!kname)
  549. {
  550. return -ENOMEM;
  551. }
  552. if ((flag & O_CREAT) || (flag & O_TMPFILE) == O_TMPFILE)
  553. {
  554. va_list ap;
  555. va_start(ap, flag);
  556. mode = va_arg(ap, mode_t);
  557. va_end(ap);
  558. }
  559. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  560. {
  561. kmem_put(kname);
  562. return -EINVAL;
  563. }
  564. ret = open(kname, flag, mode);
  565. if (ret < 0)
  566. {
  567. ret = GET_ERRNO();
  568. }
  569. kmem_put(kname);
  570. return ret;
  571. #else
  572. int ret;
  573. mode_t mode = 0;
  574. if (!lwp_user_accessable((void *)name, 1))
  575. {
  576. return -EFAULT;
  577. }
  578. if ((flag & O_CREAT) || (flag & O_TMPFILE) == O_TMPFILE)
  579. {
  580. va_list ap;
  581. va_start(ap, flag);
  582. mode = va_arg(ap, mode_t);
  583. va_end(ap);
  584. }
  585. ret = open(name, flag, mode);
  586. return (ret < 0 ? GET_ERRNO() : ret);
  587. #endif
  588. }
  589. /**
  590. * @brief Opens or creates a file relative to a directory file descriptor.
  591. *
  592. * This system call opens the file specified by `name`, relative to the directory
  593. * indicated by `dirfd`, with the specified flags and mode. It provides more
  594. * flexibility than `sys_open` for handling files in specific directory contexts.
  595. *
  596. * @param dirfd The file descriptor of the directory relative to which the file is opened.
  597. * Special values include:
  598. * - `AT_FDCWD`: Use the current working directory as the base.
  599. * @param name The path to the file to be opened. If `name` is absolute, `dirfd` is ignored.
  600. * @param flag Flags controlling how the file is opened. Common values include:
  601. * - `O_RDONLY`: Open the file for read-only access.
  602. * - `O_WRONLY`: Open the file for write-only access.
  603. * - `O_RDWR`: Open the file for both reading and writing.
  604. * - `O_CREAT`: Create the file if it does not exist.
  605. * - `O_TRUNC`: Truncate the file to zero length if it exists.
  606. * - `O_APPEND`: Open the file in append mode.
  607. * - `O_EXCL`: Ensure the file is created exclusively (used with `O_CREAT`).
  608. * @param mode The permissions to set if the file is created (e.g., `0644` for user read/write
  609. * and group/world read). This parameter is ignored unless `O_CREAT` is specified.
  610. * @return On success, returns the file descriptor.
  611. * On failure, returns `errno`.
  612. *
  613. * @note The `sys_openat` system call is particularly useful for implementing secure
  614. * directory traversal and operations, as it avoids race conditions when working
  615. * with relative paths.
  616. *
  617. * @warning Ensure that `dirfd` is a valid directory file descriptor if a relative
  618. * `name` is provided. Combining `O_CREAT` and `mode` requires proper handling
  619. * to avoid unintended permission settings.
  620. *
  621. * @see sys_open(), sys_read(), sys_write(), sys_close()
  622. */
  623. sysret_t sys_openat(int dirfd, const char *name, int flag, mode_t mode)
  624. {
  625. #ifdef ARCH_MM_MMU
  626. int ret = -1;
  627. rt_size_t len = 0;
  628. char *kname = RT_NULL;
  629. len = lwp_user_strlen(name);
  630. if (len <= 0)
  631. {
  632. return -EINVAL;
  633. }
  634. kname = (char *)kmem_get(len + 1);
  635. if (!kname)
  636. {
  637. return -ENOMEM;
  638. }
  639. lwp_get_from_user(kname, (void *)name, len + 1);
  640. ret = openat(dirfd, kname, flag, mode);
  641. if (ret < 0)
  642. {
  643. ret = GET_ERRNO();
  644. }
  645. kmem_put(kname);
  646. return ret;
  647. #else
  648. if (!lwp_user_accessable((void *)name, 1))
  649. {
  650. return -EFAULT;
  651. }
  652. int ret = openat(dirfd, name, flag, mode);
  653. return (ret < 0 ? GET_ERRNO() : ret);
  654. #endif
  655. }
  656. /**
  657. * @brief Closes a file descriptor.
  658. *
  659. * This system call closes the file descriptor specified by `fd`, releasing any
  660. * resources associated with it. Once closed, the file descriptor can no longer
  661. * be used for operations such as reading or writing, and it may be reassigned
  662. * by subsequent calls to functions like `sys_open()`.
  663. *
  664. * @param fd The file descriptor to be closed. This must be a valid open file descriptor.
  665. * @return On success, returns 0. On failure, returns `errno`.
  666. *
  667. * @note Closing a file descriptor that is already closed results in an error.
  668. * Additionally, if the file descriptor refers to a file or resource shared
  669. * among multiple processes or threads, only the reference count is decremented,
  670. * and the resource itself is not released until all references are closed.
  671. *
  672. * @warning Always ensure `fd` is valid before calling this function. Attempting
  673. * to close an invalid or already closed descriptor may lead to undefined
  674. * behavior or errors.
  675. *
  676. * @see sys_open(), sys_read(), sys_write(), close()
  677. */
  678. sysret_t sys_close(int fd)
  679. {
  680. int ret = close(fd);
  681. return (ret < 0 ? GET_ERRNO() : ret);
  682. }
  683. /**
  684. * @brief Performs control operations on a file descriptor.
  685. *
  686. * This system call allows a program to manipulate the behavior of a device or file
  687. * associated with the file descriptor `fd` by issuing a control command (`cmd`).
  688. * The function provides an interface to interact with device drivers, such as modifying
  689. * the settings of a device or performing custom operations.
  690. *
  691. * @param fd The file descriptor representing the device or file on which the ioctl
  692. * command will be performed. This should be a valid, open file descriptor.
  693. * @param cmd The control command to be executed. The exact behavior depends on the
  694. * device and the command. Commands are usually defined by the device driver
  695. * or the kernel and can vary widely.
  696. * @param data A pointer to a buffer used for passing data to and from the command.
  697. * The contents of the buffer depend on the specific command. For input
  698. * commands, it may contain the data to be written to the device. For output
  699. * commands, it may hold the data returned by the device.
  700. * @return On success, returns 0. On failure, returns `errno`.
  701. *
  702. * @note The actual functionality of `sys_ioctl` depends heavily on the specific `cmd`
  703. * and the type of device associated with the file descriptor `fd`. Each device
  704. * may have a different set of valid ioctl commands.
  705. *
  706. * @warning Ensure that `fd` refers to a valid file descriptor for a device that supports
  707. * ioctl commands. Providing an invalid command or using an unsupported device
  708. * may lead to undefined behavior or errors.
  709. *
  710. * @see sys_open(), sys_read(), sys_write(), ioctl()
  711. */
  712. sysret_t sys_ioctl(int fd, unsigned long cmd, void *data)
  713. {
  714. int ret = ioctl(fd, cmd, data);
  715. return (ret < 0 ? GET_ERRNO() : ret);
  716. }
  717. /**
  718. * @brief Retrieves information about a file associated with a file descriptor.
  719. *
  720. * This system call retrieves the status information about the file referred to
  721. * by the file descriptor `file` and stores it in the structure pointed to by `buf`.
  722. * It is typically used to obtain metadata such as file size, permissions, type,
  723. * and timestamps.
  724. *
  725. * @param file The file descriptor referring to an open file. It must be a valid file
  726. * descriptor returned by `sys_open()` or similar system calls.
  727. * @param buf A pointer to a `struct stat` that will be populated with the file's
  728. * status information, including attributes like size, access times,
  729. * permissions, and more.
  730. * @return On success, returns `0`. On failure, returns `errno` to indicate the error.
  731. *
  732. * @note The structure `struct stat` typically includes the following fields:
  733. * - `st_size`: Size of the file in bytes.
  734. * - `st_mode`: File type and permissions.
  735. * - `st_mtime`: Last modification time.
  736. * - `st_atime`: Last access time.
  737. * - `st_ctime`: Time of last status change.
  738. *
  739. * @warning Ensure that `file` is a valid, open file descriptor. Invalid file
  740. * descriptors or unsupported file types may lead to errors when using
  741. * this function.
  742. *
  743. * @see sys_open(), sys_close(), stat(), fstat()
  744. */
  745. sysret_t sys_fstat(int file, struct stat *buf)
  746. {
  747. #ifdef ARCH_MM_MMU
  748. int ret = -1;
  749. struct stat statbuff = { 0 };
  750. if (!lwp_user_accessable((void *)buf, sizeof(struct stat)))
  751. {
  752. return -EFAULT;
  753. }
  754. else
  755. {
  756. ret = fstat(file, &statbuff);
  757. if (ret == 0)
  758. {
  759. lwp_put_to_user(buf, &statbuff, sizeof statbuff);
  760. }
  761. else
  762. {
  763. ret = GET_ERRNO();
  764. }
  765. return ret;
  766. }
  767. #else
  768. if (!lwp_user_accessable((void *)buf, sizeof(struct stat)))
  769. {
  770. return -EFAULT;
  771. }
  772. int ret = fstat(file, buf);
  773. return (ret < 0 ? GET_ERRNO() : ret);
  774. #endif
  775. }
  776. /**
  777. * @brief Monitors multiple file descriptors to see if they are ready for I/O.
  778. *
  779. * This system call monitors the file descriptors specified in `fds` for any
  780. * I/O events such as readiness for reading, writing, or exceptional conditions.
  781. * It waits up to the specified timeout and returns with information about which
  782. * file descriptors are ready for the requested operations.
  783. *
  784. * @param fds An array of `struct pollfd` structures, each specifying a file descriptor
  785. * to be monitored and the events to be checked for. On return, each structure
  786. * will contain the result of the poll operation for that file descriptor.
  787. * @param nfds The number of elements in the `fds` array.
  788. * @param timeout The maximum time (in milliseconds) to wait for events. If `timeout`
  789. * is `-1`, the call will block indefinitely. If `timeout` is `0`,
  790. * the call will return immediately.
  791. * @return On success, returns the number of file descriptors with events that are ready,
  792. * or `0` if the timeout expired with no events. On error, returns `-1` and sets `errno`.
  793. *
  794. * @note The `pollfd` structure used for each file descriptor contains the following fields:
  795. * - `fd`: The file descriptor to be monitored.
  796. * - `events`: The events to monitor (e.g., `POLLIN`, `POLLOUT`).
  797. * - `revents`: The events that actually occurred.
  798. *
  799. * @warning Ensure that `fds` contains valid file descriptors. Invalid descriptors or
  800. * unsupported types (such as sockets) may result in errors. Also, be mindful
  801. * of the timeout behavior - passing `0` will cause an immediate return, and passing
  802. * `-1` will block indefinitely.
  803. *
  804. * @see sys_select(), poll(), select()
  805. */
  806. sysret_t sys_poll(struct pollfd *fds, nfds_t nfds, int timeout)
  807. {
  808. int ret = -1;
  809. #ifdef ARCH_MM_MMU
  810. struct pollfd *kfds = RT_NULL;
  811. if (!lwp_user_accessable((void *)fds, nfds * sizeof *fds))
  812. {
  813. return -EFAULT;
  814. }
  815. kfds = (struct pollfd *)kmem_get(nfds * sizeof *kfds);
  816. if (!kfds)
  817. {
  818. return -ENOMEM;
  819. }
  820. lwp_get_from_user(kfds, fds, nfds * sizeof *kfds);
  821. ret = poll(kfds, nfds, timeout);
  822. if (ret > 0)
  823. {
  824. lwp_put_to_user(fds, kfds, nfds * sizeof *kfds);
  825. }
  826. kmem_put(kfds);
  827. return ret;
  828. #else
  829. if (!lwp_user_accessable((void *)fds, nfds * sizeof *fds))
  830. {
  831. return -EFAULT;
  832. }
  833. ret = poll(fds, nfds, timeout);
  834. return ret;
  835. #endif /* ARCH_MM_MMU */
  836. }
  837. /**
  838. * @brief Monitors multiple file descriptors for readiness to perform I/O operations.
  839. *
  840. * This system call allows a program to monitor multiple file descriptors to see if
  841. * they are ready for reading, writing, or have exceptional conditions. It waits
  842. * for one or more of the file descriptors to become ready or for the specified
  843. * timeout to expire.
  844. *
  845. * @param nfds The highest-numbered file descriptor in any of the sets, plus one.
  846. * This is the number of file descriptors to monitor.
  847. * @param readfds A pointer to an `fd_set` structure specifying the file descriptors
  848. * to be checked for readability. If a file descriptor is ready to
  849. * read, it will be set in the returned `fd_set`.
  850. * @param writefds A pointer to an `fd_set` structure specifying the file descriptors
  851. * to be checked for writability. If a file descriptor is ready to
  852. * write, it will be set in the returned `fd_set`.
  853. * @param exceptfds A pointer to an `fd_set` structure specifying the file descriptors
  854. * to be checked for exceptional conditions (e.g., out-of-band data).
  855. * If a file descriptor has exceptional conditions, it will be set in
  856. * the returned `fd_set`.
  857. * @param timeout A pointer to a `struct timeval` that specifies the maximum time
  858. * to wait for an event. If `NULL`, the call blocks indefinitely. If
  859. * `timeout` is `0`, the call will return immediately.
  860. * @return On success, returns the number of file descriptors that are ready for
  861. * the requested operations, or `0` if the timeout expired without any events.
  862. * On error, returns `-1` and sets `errno`.
  863. *
  864. * @note The `fd_set` structures should be initialized using the `FD_ZERO` macro
  865. * and populated using the `FD_SET` macro. After the call, the `fd_set` structures
  866. * will contain the file descriptors that are ready for the requested operations.
  867. *
  868. * @warning Ensure that the `fd_set` structures are properly initialized and that
  869. * `nfds` correctly reflects the number of file descriptors to monitor.
  870. * Passing invalid file descriptors or incorrect `nfds` can lead to undefined behavior.
  871. *
  872. * @see sys_poll(), sys_read(), sys_write(), poll(), select()
  873. */
  874. sysret_t sys_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
  875. {
  876. #ifdef ARCH_MM_MMU
  877. int ret = -1;
  878. fd_set *kreadfds = RT_NULL, *kwritefds = RT_NULL, *kexceptfds = RT_NULL;
  879. if (readfds)
  880. {
  881. if (!lwp_user_accessable((void *)readfds, sizeof *readfds))
  882. {
  883. SET_ERRNO(EFAULT);
  884. goto quit;
  885. }
  886. kreadfds = (fd_set *)kmem_get(sizeof *kreadfds);
  887. if (!kreadfds)
  888. {
  889. SET_ERRNO(ENOMEM);
  890. goto quit;
  891. }
  892. lwp_get_from_user(kreadfds, readfds, sizeof *kreadfds);
  893. }
  894. if (writefds)
  895. {
  896. if (!lwp_user_accessable((void *)writefds, sizeof *writefds))
  897. {
  898. SET_ERRNO(EFAULT);
  899. goto quit;
  900. }
  901. kwritefds = (fd_set *)kmem_get(sizeof *kwritefds);
  902. if (!kwritefds)
  903. {
  904. SET_ERRNO(ENOMEM);
  905. goto quit;
  906. }
  907. lwp_get_from_user(kwritefds, writefds, sizeof *kwritefds);
  908. }
  909. if (exceptfds)
  910. {
  911. if (!lwp_user_accessable((void *)exceptfds, sizeof *exceptfds))
  912. {
  913. SET_ERRNO(EFAULT);
  914. goto quit;
  915. }
  916. kexceptfds = (fd_set *)kmem_get(sizeof *kexceptfds);
  917. if (!kexceptfds)
  918. {
  919. SET_ERRNO(EINVAL);
  920. goto quit;
  921. }
  922. lwp_get_from_user(kexceptfds, exceptfds, sizeof *kexceptfds);
  923. }
  924. ret = select(nfds, kreadfds, kwritefds, kexceptfds, timeout);
  925. if (kreadfds)
  926. {
  927. lwp_put_to_user(readfds, kreadfds, sizeof *kreadfds);
  928. }
  929. if (kwritefds)
  930. {
  931. lwp_put_to_user(writefds, kwritefds, sizeof *kwritefds);
  932. }
  933. if (kexceptfds)
  934. {
  935. lwp_put_to_user(exceptfds, kexceptfds, sizeof *kexceptfds);
  936. }
  937. quit:
  938. if (ret < 0)
  939. {
  940. ret = GET_ERRNO();
  941. }
  942. if (kreadfds)
  943. {
  944. kmem_put(kreadfds);
  945. }
  946. if (kwritefds)
  947. {
  948. kmem_put(kwritefds);
  949. }
  950. if (kexceptfds)
  951. {
  952. kmem_put(kexceptfds);
  953. }
  954. return ret;
  955. #else
  956. int ret;
  957. if (!lwp_user_accessable((void *)readfds, sizeof *readfds))
  958. {
  959. return -EFAULT;
  960. }
  961. if (!lwp_user_accessable((void *)writefds, sizeof *writefds))
  962. {
  963. return -EFAULT;
  964. }
  965. if (!lwp_user_accessable((void *)exceptfds, sizeof *exceptfds))
  966. {
  967. return -EFAULT;
  968. }
  969. ret = select(nfds, readfds, writefds, exceptfds, timeout);
  970. return (ret < 0 ? GET_ERRNO() : ret);
  971. #endif
  972. }
  973. /**
  974. * @brief Removes a file or symbolic link from the filesystem.
  975. *
  976. * This system call deletes the file or symbolic link specified by `pathname`.
  977. * After the call, the file will be unlinked from the filesystem, meaning it will
  978. * no longer be accessible via its pathname. If the file is still open, it will
  979. * remain available to processes that have it open until all file descriptors are
  980. * closed. If the file is a regular file and has no other hard links, it will be
  981. * removed from the disk once all references to it are closed.
  982. *
  983. * @param pathname The path to the file or symbolic link to be removed. It can be
  984. * an absolute or relative path.
  985. * @return On success, returns `0`. On failure, returns `errno` to indicate
  986. * the error.
  987. *
  988. * @note If the file is currently being used by a process (i.e., the file descriptor
  989. * is still open), it will not be immediately removed from the disk. The actual
  990. * removal occurs once the file is no longer in use. Symbolic links are removed
  991. * as soon as the call is executed.
  992. *
  993. * @warning Ensure that the file or link to be removed exists and that the `pathname`
  994. * is correctly specified. The operation will fail if the file is open and
  995. * in use by other processes or if the pathname does not exist.
  996. *
  997. * @see sys_open(), sys_remove(), unlink()
  998. */
  999. sysret_t sys_unlink(const char *pathname)
  1000. {
  1001. #ifdef ARCH_MM_MMU
  1002. int ret = -1;
  1003. rt_size_t len = 0;
  1004. char *kname = RT_NULL;
  1005. len = lwp_user_strlen(pathname);
  1006. if (!len)
  1007. {
  1008. return -EINVAL;
  1009. }
  1010. kname = (char *)kmem_get(len + 1);
  1011. if (!kname)
  1012. {
  1013. return -ENOMEM;
  1014. }
  1015. if (lwp_get_from_user(kname, (void *)pathname, len + 1) != (len + 1))
  1016. {
  1017. kmem_put(kname);
  1018. return -EINVAL;
  1019. }
  1020. ret = unlink(kname);
  1021. if (ret < 0)
  1022. {
  1023. ret = GET_ERRNO();
  1024. }
  1025. kmem_put(kname);
  1026. return ret;
  1027. #else
  1028. int ret = 0;
  1029. ret = unlink(pathname);
  1030. return (ret < 0 ? GET_ERRNO() : ret);
  1031. #endif
  1032. }
  1033. /**
  1034. * @brief Suspends execution for a specified amount of time.
  1035. *
  1036. * This system call suspends the execution of the calling thread for the duration
  1037. * specified by the `rqtp` argument. The `rqtp` argument is a pointer to a `struct timespec`
  1038. * that defines the sleep time in seconds and nanoseconds. If the sleep is interrupted by a signal,
  1039. * the function may return early with the remaining time in `rmtp`, which is an optional argument.
  1040. *
  1041. * @param rqtp A pointer to a `struct timespec` that specifies the requested sleep time.
  1042. * The structure contains two fields: `tv_sec` (seconds) and `tv_nsec` (nanoseconds).
  1043. * @param rmtp A pointer to a `struct timespec` where the remaining time will be stored if the
  1044. * sleep is interrupted by a signal. This can be `NULL` if the remaining time is not needed.
  1045. * @return On success, returns `0`. On failure, returns `errno` to indicate the error.
  1046. *
  1047. * @note The `timespec` structure has two fields:
  1048. * - `tv_sec`: The number of whole seconds to sleep.
  1049. * - `tv_nsec`: The number of nanoseconds to sleep after the seconds. This value should be
  1050. * in the range [0, 1,000,000,000) nanoseconds.
  1051. *
  1052. * @warning Ensure that the values in `rqtp` are within valid ranges. A `tv_nsec` value greater than
  1053. * or equal to 1,000,000,000 will result in an error. If `rmtp` is provided, the caller
  1054. * must ensure the buffer is large enough to store the remaining time.
  1055. *
  1056. * @see sys_sleep(), clock_nanosleep(), nanosleep()
  1057. */
  1058. sysret_t sys_nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
  1059. {
  1060. int ret = 0;
  1061. LOG_D("sys_nanosleep\n");
  1062. if (!lwp_user_accessable((void *)rqtp, sizeof *rqtp))
  1063. return -EFAULT;
  1064. #ifdef ARCH_MM_MMU
  1065. struct timespec rqtp_k;
  1066. struct timespec rmtp_k;
  1067. lwp_get_from_user(&rqtp_k, (void *)rqtp, sizeof rqtp_k);
  1068. ret = nanosleep(&rqtp_k, &rmtp_k);
  1069. if ((ret != -1 || rt_get_errno() == EINTR) && rmtp && lwp_user_accessable((void *)rmtp, sizeof *rmtp))
  1070. {
  1071. lwp_put_to_user(rmtp, (void *)&rmtp_k, sizeof rmtp_k);
  1072. if (ret != 0)
  1073. return -EINTR;
  1074. }
  1075. #else
  1076. if (rmtp)
  1077. {
  1078. if (!lwp_user_accessable((void *)rmtp, sizeof *rmtp))
  1079. return -EFAULT;
  1080. ret = nanosleep(rqtp, rmtp);
  1081. }
  1082. #endif
  1083. return (ret < 0 ? GET_ERRNO() : ret);
  1084. }
  1085. /**
  1086. * @brief Retrieves the current time and timezone information.
  1087. *
  1088. * This system call retrieves the current time in seconds and microseconds since
  1089. * the Unix epoch (1970-01-01 00:00:00 UTC) and stores it in the `tp` argument.
  1090. * It also retrieves the timezone information, if requested, and stores it in the
  1091. * `tzp` argument. The time returned is the local time of the system unless
  1092. * UTC is specified.
  1093. *
  1094. * @param tp A pointer to a `struct timeval` where the current time will be stored.
  1095. * The `struct timeval` contains two fields:
  1096. * - `tv_sec`: The number of seconds since the Unix epoch.
  1097. * - `tv_usec`: The number of microseconds past `tv_sec`.
  1098. * @param tzp A pointer to a `struct timezone` where the timezone information will
  1099. * be stored. This structure contains two fields:
  1100. * - `tz_minuteswest`: The number of minutes west of UTC.
  1101. * - `tz_dsttime`: A flag indicating the type of daylight saving time (DST) adjustment.
  1102. * If `tzp` is `NULL`, timezone information is not provided.
  1103. * @return On success, returns `0`. On failure, returns error code.
  1104. *
  1105. * @note The `struct timeval` represents the current time in seconds and microseconds,
  1106. * while `struct timezone` provides information on the timezone relative to UTC
  1107. * and any daylight saving adjustments.
  1108. *
  1109. * @warning Ensure that `tp` and `tzp` are valid pointers before calling the function.
  1110. * If you don't need timezone information, you can pass `NULL` for `tzp`.
  1111. *
  1112. * @see sys_time(), time(), gettimeofday()
  1113. */
  1114. sysret_t sys_gettimeofday(struct timeval *tp, struct timezone *tzp)
  1115. {
  1116. #ifdef ARCH_MM_MMU
  1117. struct timeval t_k;
  1118. if (tp)
  1119. {
  1120. if (!lwp_user_accessable((void *)tp, sizeof *tp))
  1121. {
  1122. return -EFAULT;
  1123. }
  1124. t_k.tv_sec = rt_tick_get() / RT_TICK_PER_SECOND;
  1125. t_k.tv_usec = (rt_tick_get() % RT_TICK_PER_SECOND) * (1000000 / RT_TICK_PER_SECOND);
  1126. lwp_put_to_user(tp, (void *)&t_k, sizeof t_k);
  1127. }
  1128. #else
  1129. if (tp)
  1130. {
  1131. if (!lwp_user_accessable((void *)tp, sizeof *tp))
  1132. {
  1133. return -EFAULT;
  1134. }
  1135. tp->tv_sec = rt_tick_get() / RT_TICK_PER_SECOND;
  1136. tp->tv_usec = (rt_tick_get() % RT_TICK_PER_SECOND) * (1000000 / RT_TICK_PER_SECOND);
  1137. }
  1138. #endif
  1139. return 0;
  1140. }
  1141. /**
  1142. * @brief Sets the system's current time and timezone information.
  1143. *
  1144. * @param tv A pointer to a `struct timeval` that contains the new system time to set.
  1145. * The `struct timeval` consists of:
  1146. * - `tv_sec`: The number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).
  1147. * - `tv_usec`: The number of microseconds past `tv_sec`.
  1148. * @param tzp A pointer to a `struct timezone` that contains the new timezone settings.
  1149. * The `struct timezone` consists of:
  1150. * - `tz_minuteswest`: The number of minutes west of UTC.
  1151. * - `tz_dsttime`: The type of daylight saving time adjustment.
  1152. * If `tzp` is `NULL`, the timezone information is not changed.
  1153. * @return On success, returns `0`. On failure, returns error code.
  1154. *
  1155. * @note haven't supported now.
  1156. *
  1157. * @see sys_gettimeofday(), settimeofday(), time()
  1158. */
  1159. sysret_t sys_settimeofday(const struct timeval *tv, const struct timezone *tzp)
  1160. {
  1161. return 0;
  1162. }
  1163. /**
  1164. * @brief Replaces the current process with a new process.
  1165. *
  1166. * This system call loads a new program into the current process's address space,
  1167. * replacing the current program with the one specified by `filename`. It passes the
  1168. * arguments `argv` and environment variables `envp` to the new program. If the execution
  1169. * is successful, the current process is completely replaced, and no code after the
  1170. * `sys_exec` call is executed. If an error occurs, the system call returns, and the
  1171. * current process continues executing.
  1172. *
  1173. * @param filename The path to the executable file to be run. This can be an absolute
  1174. * or relative path.
  1175. * @param argc The number of arguments passed to the new program. This includes the
  1176. * executable name itself as the first argument.
  1177. * @param argv An array of strings (character pointers), where each string is an argument
  1178. * passed to the new program. The first element (`argv[0]`) is conventionally
  1179. * the name of the executable.
  1180. * @param envp An array of strings representing the environment variables for the new
  1181. * process. The array is terminated by a `NULL` pointer.
  1182. * @return This function does not return on success, as the current process is replaced.
  1183. * On failure, it returns error code to indicate the error.
  1184. *
  1185. * @note The new process inherits most of the attributes of the current process, such
  1186. * as file descriptors, unless explicitly modified. It is important that `argv`
  1187. * and `envp` are properly formatted, and the `filename` points to a valid executable.
  1188. *
  1189. * @warning If `filename` is invalid or not an executable, or if the arguments or
  1190. * environment variables are incorrectly set, the system call will fail and
  1191. * return `-1`. Ensure that the executable file is accessible and that `argv`
  1192. * and `envp` are properly constructed.
  1193. *
  1194. * @see execve(), execvp(), execv(), execle()
  1195. */
  1196. sysret_t sys_exec(char *filename, int argc, char **argv, char **envp)
  1197. {
  1198. int ret = 0;
  1199. int len = 0;
  1200. char *kfilename = RT_NULL;
  1201. len = lwp_user_strlen(filename);
  1202. if (len <= 0)
  1203. {
  1204. return -EFAULT;
  1205. }
  1206. kfilename = (char *)kmem_get(len + 1);
  1207. if (!kfilename)
  1208. {
  1209. return -ENOMEM;
  1210. }
  1211. if (lwp_get_from_user(kfilename, (void *)filename, len + 1) != (len + 1))
  1212. {
  1213. kmem_put(kfilename);
  1214. return -EFAULT;
  1215. }
  1216. ret = lwp_execve(kfilename, 0, argc, argv, envp);
  1217. kmem_put(kfilename);
  1218. return ret;
  1219. }
  1220. /**
  1221. * @brief Sends a signal to a process or a group of processes.
  1222. *
  1223. * This system call sends the signal specified by `signo` to the process or process group
  1224. * identified by `pid`. If `pid` is positive, the signal is sent to the process with the
  1225. * specified process ID. If `pid` is `0`, the signal is sent to all processes in the
  1226. * same process group as the caller. If `pid` is `-1`, the signal is sent to all processes
  1227. * except for the caller. If `pid` is less than `-1`, the signal is sent to all processes
  1228. * in the process group with the process group ID equal to `-pid`.
  1229. *
  1230. * @param pid The process ID or process group ID to which the signal is to be sent.
  1231. * - A positive value sends the signal to the process with that ID.
  1232. * - `0` sends the signal to all processes in the same process group as the caller.
  1233. * - `-1` sends the signal to all processes except the caller.
  1234. * - A negative value sends the signal to all processes in the process group
  1235. * with the process group ID equal to `-pid`.
  1236. * @param signo The signal to send. This is an integer value that specifies the signal
  1237. * type. Common signal values include:
  1238. * - `SIGTERM` (terminate process)
  1239. * - `SIGKILL` (force kill process)
  1240. * - `SIGSTOP` (suspend process)
  1241. * - `SIGCONT` (resume process)
  1242. * @return On success, returns `0`. On failure, it returns error code to indicate the error.
  1243. *
  1244. * @note Signals are a mechanism for inter-process communication, allowing processes
  1245. * to send notifications or requests to other processes. The behavior of signals
  1246. * depends on the signal type and how the receiving process handles them.
  1247. *
  1248. * @warning The `signo` value must be a valid signal number. Passing an invalid signal
  1249. * number or an invalid `pid` may result in an error. Additionally, some signals
  1250. * (e.g., `SIGKILL`) cannot be caught or ignored by processes.
  1251. *
  1252. * @see signal(), killpg(), raise()
  1253. */
  1254. sysret_t sys_kill(int pid, int signo)
  1255. {
  1256. rt_err_t kret = 0;
  1257. sysret_t sysret;
  1258. struct rt_lwp *lwp = RT_NULL;
  1259. /* handling the semantics of sys_kill */
  1260. if (pid > 0)
  1261. {
  1262. /**
  1263. * Brief: Match the pid and send signal to the lwp if found
  1264. * Note: Critical Section
  1265. * - pid tree (READ. since the lwp is fetch from the pid tree, it must stay there)
  1266. */
  1267. lwp_pid_lock_take();
  1268. lwp = lwp_from_pid_raw_locked(pid);
  1269. if (lwp)
  1270. {
  1271. lwp_ref_inc(lwp);
  1272. lwp_pid_lock_release();
  1273. }
  1274. else
  1275. {
  1276. lwp_pid_lock_release();
  1277. kret = -RT_ENOENT;
  1278. }
  1279. if (lwp)
  1280. {
  1281. kret = lwp_signal_kill(lwp, signo, SI_USER, 0);
  1282. lwp_ref_dec(lwp);
  1283. }
  1284. }
  1285. else if (pid < -1 || pid == 0)
  1286. {
  1287. pid_t pgid = 0;
  1288. rt_processgroup_t group;
  1289. if (pid == 0)
  1290. {
  1291. /**
  1292. * sig shall be sent to all processes (excluding an unspecified set
  1293. * of system processes) whose process group ID is equal to the process
  1294. * group ID of the sender, and for which the process has permission to
  1295. * send a signal.
  1296. */
  1297. pgid = lwp_pgid_get_byprocess(lwp_self());
  1298. }
  1299. else
  1300. {
  1301. /**
  1302. * sig shall be sent to all processes (excluding an unspecified set
  1303. * of system processes) whose process group ID is equal to the absolute
  1304. * value of pid, and for which the process has permission to send a signal.
  1305. */
  1306. pgid = -pid;
  1307. }
  1308. group = lwp_pgrp_find(pgid);
  1309. if (group != RT_NULL)
  1310. {
  1311. PGRP_LOCK(group);
  1312. kret = lwp_pgrp_signal_kill(group, signo, SI_USER, 0);
  1313. PGRP_UNLOCK(group);
  1314. }
  1315. else
  1316. {
  1317. kret = -ECHILD;
  1318. }
  1319. }
  1320. else if (pid == -1)
  1321. {
  1322. /**
  1323. * sig shall be sent to all processes (excluding an unspecified set
  1324. * of system processes) for which the process has permission to send
  1325. * that signal.
  1326. */
  1327. kret = lwp_signal_kill_all(signo, SI_USER, 0);
  1328. }
  1329. switch (kret)
  1330. {
  1331. case -RT_ENOENT:
  1332. case -ECHILD:
  1333. sysret = -ESRCH;
  1334. break;
  1335. case -RT_EINVAL:
  1336. sysret = -EINVAL;
  1337. break;
  1338. case -RT_ENOSYS:
  1339. sysret = -ENOSYS;
  1340. break;
  1341. /**
  1342. * kill() never returns ENOMEM, so return normally to caller.
  1343. * IEEE Std 1003.1-2017 says the kill() function is successful
  1344. * if the process has permission to send sig to any of the
  1345. * processes specified by pid.
  1346. */
  1347. case -RT_ENOMEM:
  1348. default:
  1349. sysret = 0;
  1350. }
  1351. return sysret;
  1352. }
  1353. /**
  1354. * @brief Retrieves the process ID of the calling process.
  1355. *
  1356. * This system call returns the process ID (PID) of the calling process. The PID is a
  1357. * unique identifier assigned by the operating system to each running process. It can
  1358. * be used to refer to or manipulate the process in subsequent system calls.
  1359. *
  1360. * @return The PID of the calling process. On failure, returns `-1` and sets `errno`
  1361. * to indicate the error (although this function typically does not fail).
  1362. *
  1363. * @note The PID returned by this function is a positive integer, and it remains
  1364. * unique during the lifetime of the process. This value can be used to manage
  1365. * the process, including sending signals or querying process information.
  1366. *
  1367. * @warning This function does not take any arguments and is typically used when
  1368. * a process needs to obtain its own PID for management or logging purposes.
  1369. *
  1370. * @see getppid(), getuid(), getgid()
  1371. */
  1372. sysret_t sys_getpid(void)
  1373. {
  1374. return lwp_getpid();
  1375. }
  1376. /**
  1377. * @brief Retrieves the parent process ID of the calling process.
  1378. *
  1379. * This system call returns the process ID (PID) of the parent process of the calling process.
  1380. * The parent process is the process that created the calling process, typically through a
  1381. * system call like `fork()`. This information can be useful for process management and
  1382. * for determining the hierarchy of processes.
  1383. *
  1384. * @return The PID of the parent process. If the calling process has no parent (for example,
  1385. * the init process), it typically returns `1` as the PID of the system's "root" process.
  1386. * On failure, returns `-1` and sets `errno` to indicate the error (although this function
  1387. * typically does not fail).
  1388. *
  1389. * @note The `getppid()` function is commonly used when a process needs to know which
  1390. * process is responsible for it, or for managing relationships between parent and child processes.
  1391. *
  1392. * @warning This function does not take any arguments and is typically used when the
  1393. * process requires information about its parent. It should not be confused with `getpid()`,
  1394. * which retrieves the PID of the calling process itself.
  1395. *
  1396. * @see getpid(), getuid(), getgid()
  1397. */
  1398. sysret_t sys_getppid(void)
  1399. {
  1400. rt_lwp_t process;
  1401. process = lwp_self();
  1402. if (process->parent == RT_NULL)
  1403. {
  1404. LOG_E("%s: process %d has no parent process", __func__, lwp_to_pid(process));
  1405. return 0;
  1406. }
  1407. else
  1408. {
  1409. return lwp_to_pid(process->parent);
  1410. }
  1411. }
  1412. /**
  1413. * @brief Retrieves the priority of a process or process group.
  1414. *
  1415. * This system call returns the priority of a process or a process group, depending on
  1416. * the value of the `which` argument.
  1417. *
  1418. * @param which The entity for which the priority is being requested. Possible values include:
  1419. * - `PRIO_PROCESS`: Retrieves the priority of the process specified by `who`.
  1420. * - `PRIO_PGRP`: Retrieves the priority of the process group specified by `who`. (Currently not supported.)
  1421. * - `PRIO_USER`: Retrieves the priority of the user specified by `who` (the user ID). (Currently not supported.)
  1422. * @param who The ID of the process, process group, or user. The meaning of this parameter
  1423. * depends on the value of `which`:
  1424. * - When `which` is `PRIO_PROCESS`, `who` is the process ID (PID) of the process.
  1425. * - When `which` is `PRIO_PGRP`(Currently not supported.), `who` is the process group ID (PGID).
  1426. * - When `which` is `PRIO_USER`(Currently not supported.), `who` is the user ID (UID) of the user whose
  1427. * priority is being queried.
  1428. * @return On success, returns the priority value (a negative integer indicates a lower
  1429. * priority).
  1430. *
  1431. * @warning Ensure that `which` and `who` are correctly specified to avoid errors.
  1432. * Invalid values for `which` or `who` may result in an error, and the function
  1433. * will return `-1`.
  1434. *
  1435. * @see setpriority(), getpid(), getppid()
  1436. */
  1437. sysret_t sys_getpriority(int which, id_t who)
  1438. {
  1439. long prio = 0xff;
  1440. if (which == PRIO_PROCESS)
  1441. {
  1442. struct rt_lwp *lwp = RT_NULL;
  1443. lwp_pid_lock_take();
  1444. lwp = lwp_from_pid_locked(who);
  1445. if (lwp)
  1446. {
  1447. rt_thread_t thread = rt_list_entry(lwp->t_grp.prev, struct rt_thread, sibling);
  1448. prio = RT_SCHED_PRIV(thread).current_priority;
  1449. }
  1450. lwp_pid_lock_release();
  1451. }
  1452. return prio;
  1453. }
  1454. /**
  1455. * @brief Sets the priority of a process, process group, or user.
  1456. *
  1457. * This system call sets the priority of a process, process group, or user, depending
  1458. * on the value of the `which` argument. The priority is used by the operating system
  1459. * for scheduling processes. Lower numerical values represent higher priority in many
  1460. * systems, and the priority range may be system-specific.
  1461. *
  1462. * @param which The entity for which the priority is being set. Possible values include:
  1463. * - `PRIO_PROCESS`: Sets the priority of the process specified by `who`.
  1464. * - `PRIO_PGRP`: Sets the priority of the process group specified by `who`.(Currently not supported.)
  1465. * - `PRIO_USER`: Sets the priority of the user specified by `who` (the user ID).(Currently not supported.)
  1466. * @param who The ID of the process, process group, or user for which the priority is being set.
  1467. * The meaning of this parameter depends on the value of `which`:
  1468. * - When `which` is `PRIO_PROCESS`, `who` is the process ID (PID) of the process.
  1469. * - When `which` is `PRIO_PGRP`(Currently not supported.) , `who` is the process group ID (PGID).
  1470. * - When `which` is `PRIO_USER`(Currently not supported.) , `who` is the user ID (UID) of the user whose priority
  1471. * is being set.
  1472. * @param prio The priority value to set.
  1473. * @return On success, returns `0`. On failure, returns `-1`.
  1474. *
  1475. * @note This function modifies the priority of the specified process, process group, or user.
  1476. * The priority value is system-specific and may vary based on the system's scheduling
  1477. * policies. Ensure that the specified priority is within the acceptable range.
  1478. *
  1479. * @warning Ensure that `which`, `who`, and `prio` are valid. Invalid values for these
  1480. * parameters can result in errors, and the system call will return `-1`.
  1481. *
  1482. * @see getpriority(), getpid(), getppid()
  1483. */
  1484. sysret_t sys_setpriority(int which, id_t who, int prio)
  1485. {
  1486. if (which == PRIO_PROCESS)
  1487. {
  1488. struct rt_lwp *lwp = RT_NULL;
  1489. lwp_pid_lock_take();
  1490. lwp = lwp_from_pid_locked(who);
  1491. if (lwp && prio >= 0 && prio < RT_THREAD_PRIORITY_MAX)
  1492. {
  1493. rt_list_t *list;
  1494. rt_thread_t thread;
  1495. for (list = lwp->t_grp.next; list != &lwp->t_grp; list = list->next)
  1496. {
  1497. thread = rt_list_entry(list, struct rt_thread, sibling);
  1498. rt_thread_control(thread, RT_THREAD_CTRL_RESET_PRIORITY, &prio);
  1499. }
  1500. lwp_pid_lock_release();
  1501. return 0;
  1502. }
  1503. else
  1504. {
  1505. lwp_pid_lock_release();
  1506. }
  1507. }
  1508. return -1;
  1509. }
  1510. /**
  1511. * @brief Creates a semaphore.
  1512. *
  1513. * This system call creates a new semaphore with the specified `name` and initializes
  1514. * its value. The semaphore is used for synchronizing access to shared resources in
  1515. * concurrent programming. The semaphore's behavior is defined by the value (`value`)
  1516. * and any flags (`flag`) that specify additional properties or settings.
  1517. *
  1518. * @param name The name of the semaphore. This is a string used to identify the semaphore
  1519. * in the system. The name must be unique if the system requires it for reference.
  1520. * @param value The initial value of the semaphore. The value typically represents the
  1521. * number of available resources or tokens. The semaphore will be initialized
  1522. * with this value.
  1523. * @param flag The flag that specifies the attributes or properties of the semaphore.
  1524. * Flags can be used to define various characteristics of the semaphore,
  1525. * such as whether it is binary or counting, whether it is shared, etc.
  1526. *
  1527. * @return On success, returns a handle or reference to the created semaphore. On failure,
  1528. * returns `NULL`.
  1529. *
  1530. * @note Semaphores are commonly used in multithreading and multiprocessing environments
  1531. * to synchronize access to shared resources and ensure proper order of execution.
  1532. * The behavior of the semaphore depends on its type and the system's implementation.
  1533. *
  1534. * @warning Ensure that the `name` is unique and appropriate for your system's naming
  1535. * conventions. Invalid values for `value` or `flag` may lead to errors in semaphore
  1536. * creation.
  1537. *
  1538. * @see sem_wait(), sem_post(), sem_destroy()
  1539. */
  1540. rt_sem_t sys_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag)
  1541. {
  1542. int len = 0;
  1543. char *kname = RT_NULL;
  1544. len = lwp_user_strlen(name);
  1545. if (len <= 0)
  1546. {
  1547. return RT_NULL;
  1548. }
  1549. kname = (char *)kmem_get(len + 1);
  1550. if (!kname)
  1551. {
  1552. return RT_NULL;
  1553. }
  1554. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  1555. {
  1556. kmem_put(kname);
  1557. return RT_NULL;
  1558. }
  1559. rt_sem_t sem = rt_sem_create(kname, value, flag);
  1560. if (lwp_user_object_add(lwp_self(), (rt_object_t)sem) != 0)
  1561. {
  1562. rt_sem_delete(sem);
  1563. sem = NULL;
  1564. }
  1565. kmem_put(kname);
  1566. return sem;
  1567. }
  1568. /**
  1569. * @brief Deletes a semaphore and releases associated resources.
  1570. *
  1571. * This system call deletes an existing semaphore identified by the given handle `sem`.
  1572. * It releases any resources associated with the semaphore and ensures that it is no longer
  1573. * available for further synchronization operations. After deletion, the semaphore handle
  1574. * is invalid and should not be used.
  1575. *
  1576. * @param sem The semaphore handle to be deleted. This handle is obtained when the semaphore
  1577. * is created using `sys_sem_create()` or similar functions.
  1578. *
  1579. * @return On success, returns `0`. On failure, returns error code.
  1580. *
  1581. * @note Deleting a semaphore is a critical operation that should be performed only when
  1582. * the semaphore is no longer needed and no tasks are currently waiting or posting
  1583. * to it. Deleting a semaphore while it is still in use may lead to undefined behavior.
  1584. *
  1585. * @warning Ensure that no tasks are using or blocking on the semaphore before deleting it.
  1586. * Using a deleted semaphore will result in undefined behavior and potential system errors.
  1587. *
  1588. * @see sys_sem_create(), sem_wait(), sem_post()
  1589. */
  1590. sysret_t sys_sem_delete(rt_sem_t sem)
  1591. {
  1592. return lwp_user_object_delete(lwp_self(), (rt_object_t)sem);
  1593. }
  1594. /**
  1595. * @brief Attempts to take (acquire) a semaphore.
  1596. *
  1597. * This system call attempts to acquire a semaphore, blocking the calling task until the
  1598. * semaphore becomes available or the specified timeout expires. If the semaphore is already
  1599. * available, the calling task will immediately take it and proceed. If the semaphore is not
  1600. * available, the task will block until the semaphore becomes available or the timeout period
  1601. * has elapsed. The `time` parameter specifies the maximum amount of time the task will block
  1602. * waiting for the semaphore.
  1603. *
  1604. * @param sem The semaphore handle to be taken. This handle is obtained when the semaphore
  1605. * is created using `sys_sem_create()` or similar functions.
  1606. * @param time The maximum time to wait for the semaphore to become available. If the semaphore
  1607. * is not acquired within this time period, the function will return with an error.
  1608. * A value of `0` means no waiting (non-blocking), while a negative value may indicate
  1609. * an infinite wait, depending on the system's implementation.
  1610. *
  1611. * @return On success, returns `0` if the semaphore was successfully taken. On failure, returns error code.
  1612. *
  1613. * @warning Ensure that the semaphore handle is valid and has been properly created before
  1614. * calling this function. If the semaphore is deleted or invalid, the behavior of
  1615. * this function is undefined.
  1616. *
  1617. * @see sys_sem_create(), sys_sem_delete(), sem_post()
  1618. */
  1619. sysret_t sys_sem_take(rt_sem_t sem, rt_int32_t time)
  1620. {
  1621. return rt_sem_take_interruptible(sem, time);
  1622. }
  1623. /**
  1624. * @brief Releases a semaphore and wakes up any waiting tasks.
  1625. *
  1626. * This system call releases a semaphore, incrementing its value and allowing any tasks
  1627. * that are blocked (waiting) on the semaphore to proceed. If there are tasks waiting for
  1628. * the semaphore, one of them will be unblocked and allowed to take the semaphore.
  1629. * The release operation does not block the calling task, and it will return immediately.
  1630. *
  1631. * @param sem The semaphore handle to be released. This handle is obtained when the semaphore
  1632. * is created using `sys_sem_create()` or similar functions.
  1633. *
  1634. * @return On success, returns `0`. On failure, returns error code.
  1635. *
  1636. * @warning Ensure that the semaphore handle is valid before calling this function. If the semaphore
  1637. * is deleted or invalid, the behavior of this function is undefined.
  1638. *
  1639. * @see sys_sem_create(), sys_sem_delete(), sys_sem_take()
  1640. */
  1641. sysret_t sys_sem_release(rt_sem_t sem)
  1642. {
  1643. return rt_sem_release(sem);
  1644. }
  1645. /**
  1646. * @brief Creates a mutex.
  1647. *
  1648. * This system call creates a new mutex with the specified `name` and initializes it
  1649. * with the given `flag`. The mutex is used for synchronizing access to shared resources
  1650. * between tasks. Mutexes are typically used to ensure that only one task can access
  1651. * a critical section of code or a resource at a time. The `flag` parameter allows
  1652. * for setting certain properties of the mutex, such as whether it is recursive or whether
  1653. * it can be used by multiple tasks.
  1654. *
  1655. * @param name The name of the mutex. This is a string used to uniquely identify the mutex
  1656. * within the system. The name must be unique if the system requires it.
  1657. * @param flag The flag that specifies the attributes or properties of the mutex. Flags can
  1658. * define various mutex behaviors, such as whether the mutex is recursive (allows
  1659. * the same task to lock it multiple times) or whether it can be shared across
  1660. * different parts of the system.
  1661. *
  1662. * @return On success, returns a handle to the created mutex. On failure, returns `-RT_NULL`.
  1663. *
  1664. * @note Mutexes are typically used to prevent race conditions and ensure mutual exclusion
  1665. * when multiple tasks or threads are accessing shared resources.
  1666. *
  1667. * @warning Ensure that the `name` is unique and appropriate according to the system's
  1668. * naming conventions. Invalid values for `flag` or `name` may result in errors.
  1669. *
  1670. * @see sys_mutex_delete(), sys_mutex_lock(), sys_mutex_unlock()
  1671. */
  1672. rt_mutex_t sys_mutex_create(const char *name, rt_uint8_t flag)
  1673. {
  1674. int len = 0;
  1675. char *kname = RT_NULL;
  1676. rt_mutex_t mutex = RT_NULL;
  1677. len = lwp_user_strlen(name);
  1678. if (len <= 0)
  1679. {
  1680. return RT_NULL;
  1681. }
  1682. kname = (char *)kmem_get(len + 1);
  1683. if (!kname)
  1684. {
  1685. return RT_NULL;
  1686. }
  1687. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  1688. {
  1689. kmem_put(kname);
  1690. return RT_NULL;
  1691. }
  1692. mutex = rt_mutex_create(kname, flag);
  1693. if (mutex == RT_NULL)
  1694. return RT_NULL;
  1695. if (lwp_user_object_add(lwp_self(), (rt_object_t)mutex) != 0)
  1696. {
  1697. rt_mutex_delete(mutex);
  1698. mutex = RT_NULL;
  1699. }
  1700. kmem_put(kname);
  1701. return mutex;
  1702. }
  1703. /**
  1704. * @brief Deletes a mutex and releases associated resources.
  1705. *
  1706. * This system call deletes an existing mutex identified by the given handle `mutex`.
  1707. * It releases any resources associated with the mutex and ensures that it is no longer
  1708. * available for further synchronization operations. After deletion, the mutex handle
  1709. * becomes invalid and should not be used. This operation also ensures that no tasks
  1710. * can block or attempt to lock the mutex after it has been deleted.
  1711. *
  1712. * @param mutex The mutex handle to be deleted. This handle is obtained when the mutex
  1713. * is created using `sys_mutex_create()` or similar functions.
  1714. *
  1715. * @return On success, returns `0`. On failure, returns error code.
  1716. *
  1717. * @warning Ensure that the mutex handle is valid before calling this function. Deleting
  1718. * an already deleted or invalid mutex will result in undefined behavior.
  1719. *
  1720. * @see sys_mutex_create(), sys_mutex_lock(), sys_mutex_unlock()
  1721. */
  1722. sysret_t sys_mutex_delete(rt_mutex_t mutex)
  1723. {
  1724. return lwp_user_object_delete(lwp_self(), (rt_object_t)mutex);
  1725. }
  1726. /**
  1727. * @brief Attempts to acquire (lock) a mutex.
  1728. *
  1729. * This system call attempts to acquire a mutex, blocking the calling task until the
  1730. * mutex becomes available or the specified timeout expires. If the mutex is available,
  1731. * the calling task will immediately acquire it and proceed. If the mutex is already locked
  1732. * by another task, the calling task will block until the mutex is released or the timeout
  1733. * period elapses. The `time` parameter specifies the maximum amount of time the task will
  1734. * block while waiting for the mutex.
  1735. *
  1736. * @param mutex The mutex handle to be locked. This handle is obtained when the mutex is
  1737. * created using `sys_mutex_create()` or similar functions.
  1738. * @param time The maximum time to wait for the mutex to become available. If the mutex
  1739. * is not acquired within this time period, the function will return an error.
  1740. * A value of `0` means no waiting (non-blocking), while a negative value may
  1741. * indicate an infinite wait.
  1742. *
  1743. * @return On success, returns `0` if the mutex was successfully acquired. On failure, returns error code.
  1744. *
  1745. * @warning Ensure that the mutex handle is valid and has been properly created before
  1746. * calling this function. If the mutex is deleted or invalid, the behavior of
  1747. * this function is undefined.
  1748. *
  1749. * @see sys_mutex_create(), sys_mutex_delete(), sys_mutex_unlock()
  1750. */
  1751. sysret_t sys_mutex_take(rt_mutex_t mutex, rt_int32_t time)
  1752. {
  1753. return rt_mutex_take_interruptible(mutex, time);
  1754. }
  1755. /**
  1756. * @brief Releases (unlocks) a mutex.
  1757. *
  1758. * This system call releases a mutex that was previously acquired (locked) by the calling task.
  1759. * If any other task is waiting for the mutex, one of them will be unblocked and allowed to
  1760. * acquire the mutex. The release operation does not block the calling task, and it will return
  1761. * immediately after unlocking the mutex.
  1762. *
  1763. * @param mutex The mutex handle to be released. This handle is obtained when the mutex is
  1764. * created using `sys_mutex_create()` or similar functions.
  1765. *
  1766. * @return On success, returns `0`. On failure, returns error code.
  1767. *
  1768. * @warning Ensure that the mutex handle is valid before calling this function. Attempting
  1769. * to release a mutex that has not been locked or is already released can result
  1770. * in undefined behavior.
  1771. *
  1772. * @see sys_mutex_create(), sys_mutex_delete(), sys_mutex_take()
  1773. */
  1774. sysret_t sys_mutex_release(rt_mutex_t mutex)
  1775. {
  1776. return rt_mutex_release(mutex);
  1777. }
  1778. #ifdef ARCH_MM_MMU
  1779. /**
  1780. * @brief Adjusts the end of the data segment (heap) of the calling process.
  1781. *
  1782. * This system call changes the location of the program break, which defines the end of
  1783. * the data segment (heap) of the calling process. It provides a unified interface for adjusting
  1784. * the heap size. The `addr` parameter specifies the new location for the program break.
  1785. *
  1786. * @param addr The new program break location. If `addr` is `NULL`, the current program
  1787. * break is returned. If a valid address is provided, the program break will
  1788. * be adjusted to this address. The address must be page-aligned, and changes
  1789. * must stay within the process's allowed address space.
  1790. *
  1791. * @return On success, returns the new program break.
  1792. *
  1793. * @note This function is typically used to manage heap space in a process. The program
  1794. * break adjustment can impact memory allocations and deallocations in the heap.
  1795. *
  1796. * @warning The `addr` must be a valid address within the process's allocated memory
  1797. * space. Attempting to set an invalid program break address may result in
  1798. * undefined behavior or memory corruption.
  1799. *
  1800. * @see malloc(), free(), sys_sbrk()
  1801. */
  1802. rt_base_t sys_brk(void *addr)
  1803. {
  1804. return lwp_brk(addr);
  1805. }
  1806. /**
  1807. * @brief Maps a file or device into memory.
  1808. *
  1809. * This system call implements the `mmap2` system call, which maps a file or device into memory.
  1810. * It provides a way for processes to access file contents directly in memory, bypassing
  1811. * the need for explicit read or write operations. This function supports advanced memory
  1812. * mapping options such as shared or private mappings, specific protection flags, and
  1813. * offset alignment.
  1814. *
  1815. * @param addr The starting address for the memory mapping. If `NULL`, the kernel chooses
  1816. * the address. If not `NULL`, the address must be page-aligned and meet
  1817. * platform-specific alignment constraints.
  1818. * @param length The length of the memory mapping in bytes. This value is rounded up to
  1819. * the nearest page size.
  1820. * @param prot The memory protection flags. Possible values include:
  1821. * - `PROT_READ`: Pages can be read.
  1822. * - `PROT_WRITE`: Pages can be written.
  1823. * - `PROT_EXEC`: Pages can be executed.
  1824. * - `PROT_NONE`: Pages cannot be accessed.
  1825. * These flags can be combined using bitwise OR (`|`).
  1826. * @param flags Flags that determine the type and behavior of the mapping. Possible values include:
  1827. * - `MAP_SHARED`: Updates are visible to other processes that map this file.
  1828. * - `MAP_PRIVATE`: Updates are not visible to other processes and are not written to the file.
  1829. * - `MAP_FIXED`: Use the exact address specified in `addr`.
  1830. * - `MAP_ANONYMOUS`: The mapping is not backed by a file and uses zero-initialized memory.
  1831. * @param fd The file descriptor of the file to map. If `MAP_ANONYMOUS` is set in `flags`,
  1832. * `fd` is ignored and should be set to `-1`.
  1833. * @param pgoffset The offset in the file where the mapping starts, specified in pages (not bytes).
  1834. * This allows finer-grained control over the starting point of the mapping.
  1835. *
  1836. * @return On success, returns a pointer to the mapped memory region.
  1837. *
  1838. * @warning Ensure that the combination of `addr`, `length`, `prot`, `flags`, and `fd` is valid.
  1839. * Improper use may lead to undefined behavior or memory access violations.
  1840. *
  1841. * @see mmap(), munmap(), msync()
  1842. */
  1843. void *sys_mmap2(void *addr, size_t length, int prot,
  1844. int flags, int fd, size_t pgoffset)
  1845. {
  1846. sysret_t rc = 0;
  1847. long offset = 0;
  1848. /* aligned for user addr */
  1849. if ((rt_base_t)addr & ARCH_PAGE_MASK)
  1850. {
  1851. if (flags & MAP_FIXED)
  1852. rc = -EINVAL;
  1853. else
  1854. {
  1855. offset = (char *)addr - (char *)RT_ALIGN_DOWN((rt_base_t)addr, ARCH_PAGE_SIZE);
  1856. length += offset;
  1857. addr = (void *)RT_ALIGN_DOWN((rt_base_t)addr, ARCH_PAGE_SIZE);
  1858. }
  1859. }
  1860. if (rc == 0)
  1861. {
  1862. /* fix parameter passing (both along have same effect) */
  1863. if (fd == -1 || flags & MAP_ANONYMOUS)
  1864. {
  1865. fd = -1;
  1866. /* MAP_SHARED has no effect and treated as nothing */
  1867. flags &= ~MAP_SHARED;
  1868. flags |= MAP_PRIVATE | MAP_ANONYMOUS;
  1869. }
  1870. rc = (sysret_t)lwp_mmap2(lwp_self(), addr, length, prot, flags, fd, pgoffset);
  1871. }
  1872. return rc < 0 ? (char *)rc : (char *)rc + offset;
  1873. }
  1874. /**
  1875. * @brief Unmaps a memory region previously mapped with mmap or mmap2.
  1876. *
  1877. * This system call implements the `munmap` system call, which removes a mapping
  1878. * for a region of memory that was previously created using `mmap` or `mmap2`.
  1879. *
  1880. * @param addr The starting address of the memory region to unmap. This address
  1881. * must be page-aligned and refer to a region previously mapped.
  1882. * @param length The length of the memory region to unmap, in bytes. This value
  1883. * is rounded up to the nearest page size internally if needed.
  1884. *
  1885. * @return On success, returns `0`. On failure, returns error code.
  1886. *
  1887. * @warning
  1888. * - Ensure the specified memory region corresponds to a valid, active mapping.
  1889. * Providing invalid parameters may result in undefined behavior.
  1890. * - Unmapping a region that is still in use by another thread or process can
  1891. * cause concurrency issues or data corruption.
  1892. *
  1893. * @see mmap(), mmap2(), msync()
  1894. */
  1895. sysret_t sys_munmap(void *addr, size_t length)
  1896. {
  1897. return lwp_munmap(lwp_self(), addr, length);
  1898. }
  1899. /**
  1900. * @brief Changes the size or location of an existing memory mapping.
  1901. *
  1902. * This system call implements the `mremap` system call, allowing the resizing
  1903. * or relocation of a previously created memory mapping. It is typically used
  1904. * to dynamically adjust memory allocation for mapped regions without unmapping
  1905. * and remapping them explicitly.
  1906. *
  1907. * @param old_address The starting address of the existing memory mapping to be resized
  1908. * or relocated. This must be the address returned by a previous
  1909. * `mmap` or `mremap` call.
  1910. * @param old_size The current size of the memory mapping, in bytes. It must match
  1911. * the size of the original mapping.
  1912. * @param new_size The new desired size of the memory mapping, in bytes. The size will
  1913. * be rounded up to the nearest page size if necessary.
  1914. * @param flags Options to control the behavior of the remapping. Possible values include:
  1915. * - `MREMAP_MAYMOVE`: Allows the kernel to move the mapping to a new
  1916. * address if the current region cannot be resized in place.
  1917. * - `MREMAP_FIXED`: Requires the mapping to be relocated to the
  1918. * specified `new_address`. This flag must be used with caution.
  1919. * @param new_address If `MREMAP_FIXED` is set in `flags`, this specifies the address
  1920. * for the new mapping. Otherwise, it is ignored.
  1921. *
  1922. * @return On success, returns a pointer to the resized or relocated memory mapping.
  1923. *
  1924. * @warning
  1925. * - Ensure that the `old_address` and `old_size` correspond to a valid, existing mapping.
  1926. *
  1927. * @see mmap(), munmap(), msync()
  1928. */
  1929. void *sys_mremap(void *old_address, size_t old_size,
  1930. size_t new_size, int flags, void *new_address)
  1931. {
  1932. return lwp_mremap(lwp_self(), old_address, old_size, new_size, flags, new_address);
  1933. }
  1934. sysret_t sys_madvise(void *addr, size_t len, int behav)
  1935. {
  1936. return -ENOSYS;
  1937. }
  1938. #endif
  1939. /**
  1940. * @brief Creates an event object for inter-thread or inter-process communication.
  1941. *
  1942. * @param name A string representing the name of the event. If `NULL`, the event will
  1943. * be created without a name. Named events can be identified and accessed
  1944. * globally if supported by the system.
  1945. * @param flag Specifies the behavior of the event. Possible values include:
  1946. * - `RT_IPC_FLAG_FIFO`: Events are handled in a first-in, first-out order.
  1947. * - `RT_IPC_FLAG_PRIO`: Events are handled in priority order.
  1948. *
  1949. * @return On success, returns a handle (`rt_event_t`) to the created event. On failure,
  1950. * returns `-RT_NULL` to indicate that the event could not be created.
  1951. *
  1952. * @note
  1953. * - The event object must be explicitly deleted using `sys_event_delete` when it is
  1954. * no longer needed to free system resources.
  1955. *
  1956. * @warning
  1957. * - Ensure that sufficient system resources (e.g., memory) are available to create
  1958. * the event. If resources are insufficient, the function will fail.
  1959. * - Named events can potentially lead to naming conflicts if multiple events with
  1960. * the same name are created. Use unique names to avoid such issues.
  1961. *
  1962. * @see sys_event_delete(), sys_event_send(), sys_event_recv()
  1963. */
  1964. rt_event_t sys_event_create(const char *name, rt_uint8_t flag)
  1965. {
  1966. int len = 0;
  1967. rt_event_t event = RT_NULL;
  1968. char *kname = RT_NULL;
  1969. len = lwp_user_strlen(name);
  1970. if (len <= 0)
  1971. {
  1972. return RT_NULL;
  1973. }
  1974. kname = (char *)kmem_get(len + 1);
  1975. if (!kname)
  1976. {
  1977. return RT_NULL;
  1978. }
  1979. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  1980. {
  1981. kmem_put(kname);
  1982. return RT_NULL;
  1983. }
  1984. event = rt_event_create(kname, flag);
  1985. if (lwp_user_object_add(lwp_self(), (rt_object_t)event) != 0)
  1986. {
  1987. rt_event_delete(event);
  1988. event = NULL;
  1989. }
  1990. kmem_put(kname);
  1991. return event;
  1992. }
  1993. /**
  1994. * @brief Deletes a system event object.
  1995. *
  1996. * This system call removes the specified system event object, releasing
  1997. * any resources associated with it. After deletion, the event object
  1998. * should not be used.
  1999. *
  2000. * @param[in] event The handle to the event object to be deleted.
  2001. * Must be a valid `rt_event_t` object.
  2002. *
  2003. * @return sysret_t Returns a status code indicating the result of the
  2004. * operation:
  2005. * - `0` if the operation was successful.
  2006. * - An appropriate error code otherwise.
  2007. *
  2008. * @note Ensure that the event is no longer being accessed by any
  2009. * threads or tasks before calling this function.
  2010. *
  2011. * @warning Deleting an event that is in use or invalid may lead to
  2012. * undefined behavior.
  2013. * @see sys_event_create(), sys_event_send(), sys_event_recv()
  2014. */
  2015. sysret_t sys_event_delete(rt_event_t event)
  2016. {
  2017. return lwp_user_object_delete(lwp_self(), (rt_object_t)event);
  2018. }
  2019. /**
  2020. * @brief Sends an event to the specified event object.
  2021. *
  2022. * This system call sends an event to the specified event object, setting
  2023. * the specified bits in the event object's set. The event can be used
  2024. * to signal other threads or tasks that a particular condition has
  2025. * occurred.
  2026. *
  2027. * @param[in] event The handle to the event object to which the event
  2028. * will be sent. Must be a valid `rt_event_t` object.
  2029. * @param[in] set The bits to set in the event object's set. The bits
  2030. * are specified as a bitmask, where each bit represents
  2031. * a different event condition.
  2032. *
  2033. * @return sysret_t Returns a status code indicating the result of the
  2034. * operation:
  2035. * - `0` if the operation was successful.
  2036. * - An appropriate error code otherwise.
  2037. *
  2038. * @note The event object must be created before sending events to it.
  2039. *
  2040. * @warning Ensure that the event object is valid and has been created
  2041. * before calling this function.
  2042. * @see sys_event_create(), sys_event_recv()
  2043. */
  2044. sysret_t sys_event_send(rt_event_t event, rt_uint32_t set)
  2045. {
  2046. return rt_event_send(event, set);
  2047. }
  2048. /**
  2049. * @brief Receives an event from the specified event object.
  2050. *
  2051. * This system call waits for an event to be received from the specified
  2052. * event object. The function blocks until the specified event bits are
  2053. * set in the event object's set or the specified timeout period has
  2054. * elapsed. If the event is received, the function returns the set of
  2055. * bits that were set in the event object.
  2056. *
  2057. * @param[in] event The handle to the event object from which the event
  2058. * will be received. Must be a valid `rt_event_t` object.
  2059. * @param[in] set The bits to wait for in the event object's set. The
  2060. * bits are specified as a bitmask, where each bit
  2061. * represents a different event condition.
  2062. * @param[in] opt The options for receiving the event. Possible values
  2063. * include:
  2064. * - `EV_EVENT_ANY`: Wait for any of the specified bits
  2065. * to be set.
  2066. * - `EV_EVENT_ALL`: Wait for all of the specified bits
  2067. * to be set.
  2068. * @param[in] timeout The maximum time to wait for the event to be
  2069. * received, in milliseconds. A value of `0` means
  2070. * no waiting (non-blocking), while a negative value
  2071. * may indicate an infinite wait.
  2072. * @param[out] recved A pointer to a variable that will receive the set
  2073. * of bits that were set in the event object. If the
  2074. * event is received, this variable will be updated
  2075. * with the set of bits.
  2076. *
  2077. * @return sysret_t Returns a status code indicating the result of the
  2078. * operation:
  2079. * - `0` if the operation was successful.
  2080. * - An appropriate error code otherwise.
  2081. *
  2082. * @note The event object must be created before receiving events from it.
  2083. *
  2084. * @warning Ensure that the event object is valid and has been created
  2085. * before calling this function.
  2086. * @see sys_event_create(), sys_event_send()
  2087. */
  2088. sysret_t sys_event_recv(rt_event_t event,
  2089. rt_uint32_t set,
  2090. rt_uint8_t opt,
  2091. rt_int32_t timeout,
  2092. rt_uint32_t *recved)
  2093. {
  2094. int ret = 0;
  2095. rt_uint32_t krecved;
  2096. if ((recved != NULL) && !lwp_user_accessable((void *)recved, sizeof(rt_uint32_t *)))
  2097. {
  2098. return -EFAULT;
  2099. }
  2100. ret = rt_event_recv(event, set, opt, timeout, &krecved);
  2101. if ((ret == RT_EOK) && recved)
  2102. {
  2103. lwp_put_to_user((void *)recved, &krecved, sizeof(rt_uint32_t *));
  2104. }
  2105. return ret;
  2106. }
  2107. /**
  2108. * @brief Creates a mailbox for inter-thread or inter-process communication.
  2109. *
  2110. * This system call creates a mailbox object with the specified name and size.
  2111. * The mailbox is used to exchange messages between threads or tasks in a
  2112. * synchronized manner. The mailbox can be used to send and receive messages
  2113. * of a specified size.
  2114. *
  2115. * @param[in] name A string representing the name of the mailbox. If `NULL`,
  2116. * the mailbox will be created without a name. Named mailboxes
  2117. * can be identified and accessed globally if supported by the system.
  2118. * @param[in] size The size of the mailbox, which determines the maximum number
  2119. * of messages that can be stored in the mailbox at any given time.
  2120. * @param[in] flag The behavior of the mailbox. Possible values include:
  2121. * - `RT_IPC_FLAG_FIFO`: Messages are handled in a first-in, first-out order.
  2122. * - `RT_IPC_FLAG_PRIO`: Messages are handled in priority order.
  2123. *
  2124. * @return rt_mailbox_t Returns a handle to the created mailbox object.
  2125. * On failure, returns `-RT_NULL`.
  2126. *
  2127. * @note
  2128. * - The mailbox object must be explicitly deleted using `sys_mb_delete` when it is
  2129. * no longer needed to free system resources.
  2130. *
  2131. * @warning
  2132. * - Ensure that sufficient system resources (e.g., memory) are available to create
  2133. * the mailbox. If resources are insufficient, the function will fail.
  2134. * - Named mailboxes can potentially lead to naming conflicts if multiple mailboxes
  2135. * with the same name are created. Use unique names to avoid such issues.
  2136. *
  2137. * @see sys_mb_delete(), sys_mb_send(), sys_mb_recv()
  2138. */
  2139. rt_mailbox_t sys_mb_create(const char *name, rt_size_t size, rt_uint8_t flag)
  2140. {
  2141. int len = 0;
  2142. rt_mailbox_t mb = RT_NULL;
  2143. char *kname = RT_NULL;
  2144. len = lwp_user_strlen(name);
  2145. if (len <= 0)
  2146. {
  2147. return RT_NULL;
  2148. }
  2149. kname = (char *)kmem_get(len + 1);
  2150. if (!kname)
  2151. {
  2152. return RT_NULL;
  2153. }
  2154. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  2155. {
  2156. kmem_put(kname);
  2157. return RT_NULL;
  2158. }
  2159. mb = rt_mb_create(kname, size, flag);
  2160. if (lwp_user_object_add(lwp_self(), (rt_object_t)mb) != 0)
  2161. {
  2162. rt_mb_delete(mb);
  2163. mb = NULL;
  2164. }
  2165. kmem_put(kname);
  2166. return mb;
  2167. }
  2168. /**
  2169. * @brief Deletes a mailbox object.
  2170. *
  2171. * This system call deletes the specified mailbox object, releasing any resources
  2172. * associated with it. After deletion, the mailbox object should not be used.
  2173. *
  2174. * @param[in] mb The handle to the mailbox object to be deleted.
  2175. * Must be a valid `rt_mailbox_t` object.
  2176. *
  2177. * @return sysret_t Returns a status code indicating the result of the operation:
  2178. * - `0` if the operation was successful.
  2179. * - An appropriate error code otherwise.
  2180. *
  2181. * @note Ensure that the mailbox is no longer being accessed by any threads or tasks
  2182. * before calling this function.
  2183. *
  2184. * @warning Deleting a mailbox that is in use or invalid may lead to undefined behavior.
  2185. *
  2186. * @see sys_mb_create(), sys_mb_send(), sys_mb_recv()
  2187. */
  2188. sysret_t sys_mb_delete(rt_mailbox_t mb)
  2189. {
  2190. return lwp_user_object_delete(lwp_self(), (rt_object_t)mb);
  2191. }
  2192. /**
  2193. * @brief Sends a message to a mailbox object.
  2194. *
  2195. * This system call posts a message (a single value) to the specified mailbox.
  2196. * If the mailbox is full, the function will return an error code immediately without waiting time.
  2197. *
  2198. * @param[in] mb The handle to the mailbox object where the message
  2199. * will be sent. Must be a valid `rt_mailbox_t` object.
  2200. * @param[in] value The value to be sent to the mailbox. Typically, this
  2201. * is a pointer or an integral value that represents
  2202. * the message content.
  2203. *
  2204. * @return sysret_t Returns a status code indicating the result of the
  2205. * operation:
  2206. * - `0` if the message was successfully sent.
  2207. * - `-RT_EFULL` if the mailbox is full.
  2208. * - An appropriate error code for other failures.
  2209. *
  2210. * @note Ensure the mailbox has been properly initialized before calling
  2211. * this function. Sending messages to an uninitialized or invalid
  2212. * mailbox may result in undefined behavior.
  2213. *
  2214. * @warning If the mailbox is full and the function blocks, ensure
  2215. * proper handling to avoid potential deadlocks.
  2216. *
  2217. * @see sys_mb_create(), sys_mb_recv(), sys_mb_send_wait()
  2218. */
  2219. sysret_t sys_mb_send(rt_mailbox_t mb, rt_ubase_t value)
  2220. {
  2221. return rt_mb_send(mb, value);
  2222. }
  2223. /**
  2224. * @brief Sends a message to a mailbox object with a timeout.
  2225. *
  2226. * This system call attempts to post a message (a single value) to the specified mailbox.
  2227. * If the mailbox is full, the function will wait for a specified timeout period
  2228. * for space to become available. If the timeout expires before the message is sent,
  2229. * the function returns an error.
  2230. *
  2231. * @param[in] mb The handle to the mailbox object where the message
  2232. * will be sent. Must be a valid `rt_mailbox_t` object.
  2233. * @param[in] value The value to be sent to the mailbox. Typically, this
  2234. * is a pointer or an integral value representing the
  2235. * message content.
  2236. * @param[in] timeout The maximum time to wait for space to become available
  2237. * in the mailbox, in milliseconds.
  2238. * - a negative value can be used to wait indefinitely.
  2239. * - `0` can be used for non-blocking behavior.
  2240. *
  2241. * @return sysret_t Returns a status code indicating the result of the
  2242. * operation:
  2243. * - `0` if the message was successfully sent.
  2244. * - `-RT_ETIMEOUT` if the operation timed out.
  2245. * - `-RT_EFULL` if the mailbox is full and `timeout` is `0`.
  2246. * - An appropriate error code for other failures.
  2247. *
  2248. * @note Ensure the mailbox has been properly initialized before calling this function.
  2249. * Passing an uninitialized or invalid mailbox handle may result in undefined behavior.
  2250. *
  2251. * @warning Using a negative value without appropriate logic may lead to indefinite blocking,
  2252. * potentially causing deadlocks.
  2253. * @see sys_mb_send()
  2254. */
  2255. sysret_t sys_mb_send_wait(rt_mailbox_t mb,
  2256. rt_ubase_t value,
  2257. rt_int32_t timeout)
  2258. {
  2259. return rt_mb_send_wait(mb, value, timeout);
  2260. }
  2261. /**
  2262. * @brief Receives a message from a mailbox with a timeout.
  2263. *
  2264. * This system call attempts to receive a message from the specified mailbox.
  2265. * If the mailbox is empty, the function will wait for a specified timeout
  2266. * period for a message to arrive. If no message is received within the timeout,
  2267. * an error is returned.
  2268. *
  2269. * @param[in] mb The handle to the mailbox object from which the message
  2270. * is to be received. Must be a valid `rt_mailbox_t` object.
  2271. * @param[out] value Pointer to a variable where the received message will
  2272. * be stored. Must not be NULL.
  2273. * @param[in] timeout The maximum time to wait for a message, in milliseconds.
  2274. * - a negative value: Wait indefinitely until a message is available.
  2275. * - `0`: Non-blocking mode. If no message is available, return immediately.
  2276. *
  2277. * @return sysret_t Returns a status code indicating the result of the operation:
  2278. * - `0`: The message was successfully received.
  2279. * - `-RT_ETIMEOUT`: The operation timed out before a message was received.
  2280. * - Other error codes may indicate failures.
  2281. *
  2282. * @note Ensure the mailbox is properly initialized and the `value` pointer
  2283. * is valid before calling this function. Passing an invalid mailbox
  2284. * or NULL `value` pointer may lead to undefined behavior.
  2285. *
  2286. * @warning Using a negative value without proper safeguards may cause
  2287. * indefinite blocking, potentially resulting in deadlocks.
  2288. */
  2289. sysret_t sys_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout)
  2290. {
  2291. int ret = 0;
  2292. rt_ubase_t *kvalue;
  2293. if (!lwp_user_accessable((void *)value, sizeof(rt_ubase_t *)))
  2294. {
  2295. return -EFAULT;
  2296. }
  2297. kvalue = kmem_get(sizeof(rt_ubase_t *));
  2298. if (kvalue == RT_NULL)
  2299. {
  2300. return -ENOMEM;
  2301. }
  2302. ret = rt_mb_recv(mb, (rt_ubase_t *)kvalue, timeout);
  2303. if (ret == RT_EOK)
  2304. {
  2305. lwp_put_to_user(value, kvalue, sizeof(rt_ubase_t *));
  2306. }
  2307. kmem_put(kvalue);
  2308. return ret;
  2309. }
  2310. rt_weak int syslog_ctrl(int type, char *buf, int len)
  2311. {
  2312. return -EINVAL;
  2313. }
  2314. /**
  2315. * @brief Sends a log message to the system log.
  2316. *
  2317. * This system call sends a message to the system log for recording or debugging purposes.
  2318. *
  2319. * @param[in] type The type of the log message, typically representing the severity
  2320. * or category (e.g., debug, info, warning, error). This should be
  2321. * a valid predefined log type.
  2322. * @param[in] buf A pointer to a buffer containing the log message. Must be a
  2323. * null-terminated string and a valid pointer.
  2324. * @param[in] len The length of the log message to be sent, excluding the null
  2325. * terminator. If the length exceeds the system log's limit,
  2326. * the message may be truncated.
  2327. *
  2328. * @return sysret_t Returns a status code indicating the result of the operation:
  2329. * - `0`: The log message was successfully recorded.
  2330. * - Other error codes may indicate additional failures.
  2331. *
  2332. * @note Ensure the log type is a valid predefined value supported by the system.
  2333. * The buffer must remain valid and accessible during the execution of this function.
  2334. *
  2335. * @warning Sending excessively large or frequent log messages may impact system performance.
  2336. */
  2337. sysret_t sys_syslog(int type, char *buf, int len)
  2338. {
  2339. char *tmp;
  2340. int ret = -1;
  2341. if (!lwp_user_accessable((void *)buf, len))
  2342. {
  2343. return -EFAULT;
  2344. }
  2345. tmp = (char *)rt_malloc(len);
  2346. if (!tmp)
  2347. {
  2348. return -ENOMEM;
  2349. }
  2350. ret = syslog_ctrl(type, tmp, len);
  2351. lwp_put_to_user(buf, tmp, len);
  2352. rt_free(tmp);
  2353. return ret;
  2354. }
  2355. /**
  2356. * @brief Creates a message queue.
  2357. *
  2358. * This system call creates a new message queue with a specified name, message size,
  2359. * maximum number of messages, and associated flags. The message queue allows
  2360. * messages of a given size to be sent and received between tasks or threads.
  2361. *
  2362. * @param[in] name The name of the message queue. It should be a unique
  2363. * identifier and a null-terminated string.
  2364. * @param[in] msg_size The size of each message in the queue. This defines
  2365. * the maximum size for individual messages that can
  2366. * be sent or received.
  2367. * @param[in] max_msgs The maximum number of messages the queue can hold.
  2368. * If the queue is full, further send operations may
  2369. * block or return an error depending on the flags.
  2370. * @param[in] flag Flags that control the behavior of the message queue.
  2371. * This can specify whether the queue is blocking,
  2372. * non-blocking, or has other specific attributes.
  2373. *
  2374. * @return rt_mq_t Returns the handle to the created message queue, or `NULL`
  2375. * if the creation failed (e.g., due to invalid parameters
  2376. * or insufficient resources).
  2377. *
  2378. * @note Ensure that the message queue name is unique. The size of the messages
  2379. * and the number of messages should be chosen based on the application
  2380. * requirements.
  2381. *
  2382. * @warning Creating too many message queues or setting an overly large
  2383. * `max_msgs` may lead to resource exhaustion.
  2384. */
  2385. rt_mq_t sys_mq_create(const char *name,
  2386. rt_size_t msg_size,
  2387. rt_size_t max_msgs,
  2388. rt_uint8_t flag)
  2389. {
  2390. rt_mq_t mq = RT_NULL;
  2391. int len = 0;
  2392. char *kname = RT_NULL;
  2393. len = lwp_user_strlen(name);
  2394. if (len <= 0)
  2395. {
  2396. return RT_NULL;
  2397. }
  2398. kname = (char *)kmem_get(len + 1);
  2399. if (!kname)
  2400. {
  2401. return RT_NULL;
  2402. }
  2403. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  2404. {
  2405. kmem_put(kname);
  2406. return RT_NULL;
  2407. }
  2408. mq = rt_mq_create(kname, msg_size, max_msgs, flag);
  2409. if (lwp_user_object_add(lwp_self(), (rt_object_t)mq) != 0)
  2410. {
  2411. rt_mq_delete(mq);
  2412. mq = NULL;
  2413. }
  2414. kmem_put(kname);
  2415. return mq;
  2416. }
  2417. /**
  2418. * @brief Deletes a message queue.
  2419. *
  2420. * This system call deletes the specified message queue and releases any resources
  2421. * associated with it. After calling this function, the message queue handle
  2422. * becomes invalid and should not be used.
  2423. *
  2424. * @param[in] mq The handle to the message queue to be deleted.
  2425. * Must be a valid `rt_mq_t` object.
  2426. *
  2427. * @return sysret_t Returns a status code indicating the result of the operation:
  2428. * - `0`: The message queue was successfully deleted.
  2429. * - An appropriate error code for other failures.
  2430. *
  2431. * @note Ensure that no tasks or threads are using the message queue before
  2432. * deleting it to avoid undefined behavior or data loss.
  2433. *
  2434. * @warning Deleting an active message queue that is being used by tasks or
  2435. * threads may lead to resource leaks or corruption. Ensure proper
  2436. * synchronization before deletion.
  2437. */
  2438. sysret_t sys_mq_delete(rt_mq_t mq)
  2439. {
  2440. return lwp_user_object_delete(lwp_self(), (rt_object_t)mq);
  2441. }
  2442. /**
  2443. * @brief Sends a message to a message queue.
  2444. *
  2445. * This system call sends a message to the specified message queue. The message
  2446. * is copied into the queue's buffer. If the queue is full, the behavior will
  2447. * depend on the flags set during queue creation (e.g., whether it is blocking
  2448. * or non-blocking).
  2449. *
  2450. * @param[in] mq The handle to the message queue where the message will be sent.
  2451. * Must be a valid `rt_mq_t` object.
  2452. * @param[in] buffer A pointer to the message data to be sent. This must not be NULL.
  2453. * @param[in] size The size of the message to be sent, in bytes. This should be
  2454. * less than or equal to the maximum message size defined when
  2455. * the queue was created.
  2456. *
  2457. * @return sysret_t Returns a status code indicating the result of the operation:
  2458. * - `0`: The message was successfully sent to the queue.
  2459. * - An appropriate error code for other failures.
  2460. *
  2461. * @note Ensure that the message size does not exceed the maximum allowed message
  2462. * size when the queue was created. Passing an invalid queue handle or buffer
  2463. * may result in undefined behavior.
  2464. *
  2465. * @warning Sending messages to a full queue in blocking mode may cause the calling
  2466. * task or thread to block indefinitely if not properly handled.
  2467. */
  2468. sysret_t sys_mq_send(rt_mq_t mq, void *buffer, rt_size_t size)
  2469. {
  2470. int ret = 0;
  2471. void *kbuffer = RT_NULL;
  2472. if (!lwp_user_accessable((void *)buffer, size))
  2473. {
  2474. return -EFAULT;
  2475. }
  2476. kbuffer = kmem_get(size);
  2477. if (kbuffer == RT_NULL)
  2478. {
  2479. return -ENOMEM;
  2480. }
  2481. if (lwp_get_from_user(kbuffer, buffer, size) != size)
  2482. {
  2483. kmem_put(kbuffer);
  2484. return -EINVAL;
  2485. }
  2486. ret = rt_mq_send(mq, kbuffer, size);
  2487. kmem_put(kbuffer);
  2488. return ret;
  2489. }
  2490. /**
  2491. * @brief Sends an urgent message to a message queue.
  2492. *
  2493. * This system call sends a message to the specified message queue with higher priority,
  2494. * meaning it will be placed at the front of the queue, bypassing normal message
  2495. * order. The message is copied into the queue's buffer. If the queue is full,
  2496. * the behavior will depend on the flags set during queue creation (e.g., whether
  2497. * it is blocking or non-blocking).
  2498. *
  2499. * @param[in] mq The handle to the message queue where the message will be sent.
  2500. * Must be a valid `rt_mq_t` object.
  2501. * @param[in] buffer A pointer to the message data to be sent. This must not be NULL.
  2502. * @param[in] size The size of the message to be sent, in bytes. This should be
  2503. * less than or equal to the maximum message size defined when
  2504. * the queue was created.
  2505. *
  2506. * @return sysret_t Returns a status code indicating the result of the operation:
  2507. * - `0`: The urgent message was successfully sent to the queue.
  2508. * - `-RT_EFULL`: The queue is full and the message could not be sent.
  2509. * - An appropriate error code for other failures.
  2510. *
  2511. * @note Ensure that the message size does not exceed the maximum allowed message
  2512. * size when the queue was created. The urgent message will be processed before
  2513. * other normal messages in the queue.
  2514. *
  2515. * @warning Sending urgent messages to a full queue in blocking mode may cause the
  2516. * calling task or thread to block indefinitely if not properly handled.
  2517. */
  2518. sysret_t sys_mq_urgent(rt_mq_t mq, void *buffer, rt_size_t size)
  2519. {
  2520. int ret = 0;
  2521. void *kbuffer = RT_NULL;
  2522. if (!lwp_user_accessable((void *)buffer, size))
  2523. {
  2524. return -EFAULT;
  2525. }
  2526. kbuffer = kmem_get(size);
  2527. if (kbuffer == RT_NULL)
  2528. {
  2529. return -ENOMEM;
  2530. }
  2531. if (lwp_get_from_user(kbuffer, buffer, size) != size)
  2532. {
  2533. kmem_put(kbuffer);
  2534. return -EINVAL;
  2535. }
  2536. ret = rt_mq_urgent(mq, kbuffer, size);
  2537. kmem_put(kbuffer);
  2538. return ret;
  2539. }
  2540. /**
  2541. * @brief Receives a message from a message queue.
  2542. *
  2543. * This system call attempts to receive a message from the specified message queue.
  2544. * The message is copied into the provided buffer. If no message is available
  2545. * in the queue, the function will block for a specified timeout period before
  2546. * returning. If the timeout expires without receiving a message, an error is returned.
  2547. *
  2548. * @param[in] mq The handle to the message queue from which the message
  2549. * will be received. Must be a valid `rt_mq_t` object.
  2550. * @param[out] buffer A pointer to the buffer where the received message will
  2551. * be stored. Must not be NULL and large enough to hold the
  2552. * message.
  2553. * @param[in] size The size of the buffer, in bytes. This should be at least
  2554. * the size of a message in the queue.
  2555. * @param[in] timeout The maximum time to wait for a message, in milliseconds.
  2556. * - a negative value: Wait indefinitely until a message is available.
  2557. * - `0`: Non-blocking mode. If no message is available, return immediately.
  2558. *
  2559. * @return sysret_t Returns a status code indicating the result of the operation:
  2560. * - `0`: The message was successfully received.
  2561. * - `-RT_ETIMEOUT`: The operation timed out before a message was received.
  2562. * - Other error codes may indicate additional failures.
  2563. *
  2564. * @note Ensure the buffer is large enough to store the message received from the queue.
  2565. * If the buffer is too small, the function may fail or behave unexpectedly.
  2566. *
  2567. * @warning Using a negative value without proper safeguards may cause indefinite
  2568. * blocking, potentially resulting in deadlocks if no message is received.
  2569. */
  2570. sysret_t sys_mq_recv(rt_mq_t mq,
  2571. void *buffer,
  2572. rt_size_t size,
  2573. rt_int32_t timeout)
  2574. {
  2575. int ret = 0;
  2576. void *kbuffer = RT_NULL;
  2577. if (!lwp_user_accessable((void *)buffer, size))
  2578. {
  2579. return -EFAULT;
  2580. }
  2581. kbuffer = kmem_get(size);
  2582. if (kbuffer == RT_NULL)
  2583. {
  2584. return -ENOMEM;
  2585. }
  2586. ret = rt_mq_recv(mq, kbuffer, size, timeout);
  2587. if (ret > 0)
  2588. lwp_put_to_user((void *)buffer, (void *)kbuffer, ret);
  2589. kmem_put(kbuffer);
  2590. return ret;
  2591. }
  2592. static void timer_timeout_callback(void *parameter)
  2593. {
  2594. rt_sem_t sem = (rt_sem_t)parameter;
  2595. rt_sem_release(sem);
  2596. }
  2597. /**
  2598. * @brief Creates a timer.
  2599. *
  2600. * This system call creates a timer that can be used to trigger events or
  2601. * actions after a specified timeout or interval. The timer will operate in a
  2602. * real-time manner and can be configured to trigger once or repeatedly. The
  2603. * created timer can be started, stopped, or deleted as required.
  2604. *
  2605. * @param[in] name The name of the timer. It should be a unique string identifier.
  2606. * The name is used for debugging and logging purposes.
  2607. * @param[in] data A pointer to user-defined data that will be passed to the timer's
  2608. * callback function when it is triggered. This may be used to carry
  2609. * context or other necessary information for the callback.
  2610. * @param[in] period The timer period in milliseconds. The timer will trigger every
  2611. * `period` milliseconds, or after the specified timeout.
  2612. * @param[in] flag Flags that control the behavior of the timer. These can specify
  2613. * whether the timer is one-shot (triggers once) or periodic
  2614. * (triggers repeatedly).
  2615. *
  2616. * @return rt_timer_t Returns the handle to the created timer, or `NULL` if the creation failed.
  2617. *
  2618. * @note The timer callback function must be implemented to handle the event triggered
  2619. * by the timer. Ensure that the `data` parameter, if used, is properly handled
  2620. * in the callback.
  2621. *
  2622. * @warning Ensure the timer's period and flags are configured correctly to avoid
  2623. * undesired behavior, especially if the timer is periodic.
  2624. */
  2625. rt_timer_t sys_rt_timer_create(const char *name,
  2626. void *data,
  2627. rt_tick_t time,
  2628. rt_uint8_t flag)
  2629. {
  2630. int len = 0;
  2631. char *kname = RT_NULL;
  2632. rt_timer_t timer = RT_NULL;
  2633. len = lwp_user_strlen(name);
  2634. if (len <= 0)
  2635. {
  2636. return RT_NULL;
  2637. }
  2638. kname = (char *)kmem_get(len + 1);
  2639. if (!kname)
  2640. {
  2641. return RT_NULL;
  2642. }
  2643. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  2644. {
  2645. kmem_put(kname);
  2646. return RT_NULL;
  2647. }
  2648. timer = rt_timer_create(kname, timer_timeout_callback, (void *)data, time, flag);
  2649. if (lwp_user_object_add(lwp_self(), (rt_object_t)timer) != 0)
  2650. {
  2651. rt_timer_delete(timer);
  2652. timer = NULL;
  2653. }
  2654. kmem_put(kname);
  2655. return timer;
  2656. }
  2657. /**
  2658. * @brief Deletes a timer.
  2659. *
  2660. * This system call deletes the specified timer and releases any resources
  2661. * associated with it. Once the timer is deleted, its handle becomes invalid,
  2662. * and any further operations on the timer should be avoided.
  2663. *
  2664. * @param[in] timer The handle to the timer to be deleted. Must be a valid `rt_timer_t` object.
  2665. *
  2666. * @return sysret_t Returns a status code indicating the result of the operation:
  2667. * - `0`: The timer was successfully deleted.
  2668. * - Other error codes may indicate additional failures.
  2669. *
  2670. * @note Ensure that the timer is not active or being used before deleting it to avoid
  2671. * any unexpected behavior or resource leaks.
  2672. *
  2673. * @warning Deleting an active timer may lead to undefined behavior, especially
  2674. * if the timer is in the middle of triggering or executing its callback.
  2675. */
  2676. sysret_t sys_rt_timer_delete(rt_timer_t timer)
  2677. {
  2678. return lwp_user_object_delete(lwp_self(), (rt_object_t)timer);
  2679. }
  2680. /**
  2681. * @brief Starts a timer.
  2682. *
  2683. * This system call starts the specified timer, causing it to begin counting down
  2684. * based on its configured period. Once the timer reaches the set period, it triggers the
  2685. * associated callback function. The behavior depends on whether the timer is configured
  2686. * as one-shot or periodic.
  2687. *
  2688. * @param[in] timer The handle to the timer to be started. Must be a valid `rt_timer_t` object.
  2689. *
  2690. * @return sysret_t Returns a status code indicating the result of the operation:
  2691. * - `0`: The timer was successfully started.
  2692. * - Other error codes may indicate additional failures.
  2693. *
  2694. * @note Ensure that the timer has been created and is in a valid state before attempting to start it.
  2695. *
  2696. * @warning Starting a timer that is already running may lead to undefined behavior. Ensure that the
  2697. * timer is stopped or not in use before starting it.
  2698. */
  2699. sysret_t sys_rt_timer_start(rt_timer_t timer)
  2700. {
  2701. return rt_timer_start(timer);
  2702. }
  2703. /**
  2704. * @brief Stops a timer.
  2705. *
  2706. * This system call stops the specified timer, halting its countdown and
  2707. * preventing it from triggering further callbacks. If the timer is periodic,
  2708. * stopping it will prevent further periodic triggers until it is started again.
  2709. *
  2710. * @param[in] timer The handle to the timer to be stopped. Must be a valid `rt_timer_t` object.
  2711. *
  2712. * @return sysret_t Returns a status code indicating the result of the operation:
  2713. * - `0`: The timer was successfully stopped.
  2714. * - Other error codes may indicate additional failures.
  2715. *
  2716. * @note Ensure that the timer is in a valid state before attempting to stop it.
  2717. * Stopping an inactive or already stopped timer may not have any effect.
  2718. *
  2719. * @warning Stopping a timer that is actively triggering or in use may disrupt its expected
  2720. * behavior. Ensure proper synchronization or state management when stopping
  2721. * the timer during active use.
  2722. */
  2723. sysret_t sys_rt_timer_stop(rt_timer_t timer)
  2724. {
  2725. return rt_timer_stop(timer);
  2726. }
  2727. /**
  2728. * @brief Controls various properties of a timer.
  2729. *
  2730. * This system call provides control over various aspects of a timer, such as
  2731. * modifying its configuration, querying its status, or changing its behavior.
  2732. * The specific behavior is determined by the command (`cmd`) and any associated arguments (`arg`).
  2733. *
  2734. * @param[in] timer The handle to the timer to be controlled. Must be a valid `rt_timer_t` object.
  2735. * @param[in] cmd The command to execute. The meaning of this parameter depends on the command value.
  2736. * Common commands might include modifying the timer period, changing its callback,
  2737. * or querying its current state.
  2738. * @param[in] arg A pointer to any additional arguments needed for the command. The type and content
  2739. * of this argument depend on the specific command being executed.
  2740. *
  2741. * @return sysret_t Returns a status code indicating the result of the operation:
  2742. * - `0`: The timer control operation was successful.
  2743. * - Other error codes may indicate additional failures.
  2744. *
  2745. * @note Ensure that the provided command (`cmd`) is valid for the specific timer implementation.
  2746. * Incorrect commands or arguments may lead to unexpected behavior or errors.
  2747. *
  2748. * @warning Using invalid or unsupported commands may cause undefined behavior or crashes.
  2749. */
  2750. sysret_t sys_rt_timer_control(rt_timer_t timer, int cmd, void *arg)
  2751. {
  2752. return rt_timer_control(timer, cmd, arg);
  2753. }
  2754. /* MUSL compatible */
  2755. struct ksigevent
  2756. {
  2757. union sigval sigev_value;
  2758. int sigev_signo;
  2759. int sigev_notify;
  2760. int sigev_tid;
  2761. };
  2762. /* to protect unsafe implementation in current rt-smart toolchain */
  2763. RT_STATIC_ASSERT(sigevent_compatible, offsetof(struct ksigevent, sigev_tid) == offsetof(struct sigevent, sigev_notify_function));
  2764. /**
  2765. * @brief Creates a per-process timer.
  2766. *
  2767. * This system call creates a new timer associated with the specified clock, and
  2768. * initializes the timer with the provided event notification attributes.
  2769. * Once created, the timer can be started, stopped, or controlled as needed.
  2770. * The timer will trigger when the specified expiration time or interval is reached.
  2771. *
  2772. * @param[in] clockid The clock to be used for the timer. Common clock values include:
  2773. * - `CLOCK_REALTIME`: System real-time clock.
  2774. * - `CLOCK_MONOTONIC`: Monotonic clock that cannot be set and is not affected by system time changes.
  2775. * - Other clock IDs can be used depending on the platform and requirements.
  2776. * @param[in] sevp A pointer to a `sigevent` structure that specifies how the process
  2777. * should be notified when the timer expires. This can include notification
  2778. * types such as signal delivery, thread notification, or posting to a queue.
  2779. * @param[out] timerid A pointer to a `timer_t` variable where the created timer's ID will be stored.
  2780. * The timer ID will be used for subsequent timer operations (e.g., starting, stopping).
  2781. *
  2782. * @return sysret_t Returns a status code indicating the result of the operation:
  2783. * - `0`: The timer was successfully created.
  2784. * - Other error codes may indicate additional failures.
  2785. *
  2786. * @warning Ensure that the provided `sigevent` structure is properly configured, as invalid or
  2787. * unsupported notification types may result in unexpected behavior.
  2788. */
  2789. sysret_t sys_timer_create(clockid_t clockid, struct sigevent * restrict sevp, timer_t * restrict timerid)
  2790. {
  2791. int ret = 0;
  2792. #ifdef ARCH_MM_MMU
  2793. struct sigevent sevp_k;
  2794. timer_t timerid_k;
  2795. int utimer;
  2796. if (sevp == NULL)
  2797. {
  2798. sevp_k.sigev_notify = SIGEV_SIGNAL;
  2799. sevp_k.sigev_signo = SIGALRM;
  2800. sevp = &sevp_k;
  2801. }
  2802. else
  2803. {
  2804. /* clear extra bytes if any */
  2805. if (sizeof(struct ksigevent) < sizeof(struct sigevent))
  2806. memset(&sevp_k, 0, sizeof(sevp_k));
  2807. /* musl passes `struct ksigevent` to kernel, we shoule only get size of that bytes */
  2808. if (!lwp_get_from_user(&sevp_k, (void *)sevp, sizeof(struct ksigevent)))
  2809. {
  2810. return -EINVAL;
  2811. }
  2812. }
  2813. ret = _SYS_WRAP(timer_create(clockid, &sevp_k, &timerid_k));
  2814. if (ret != -RT_ERROR)
  2815. {
  2816. utimer = (rt_ubase_t)timerid_k;
  2817. if (!lwp_put_to_user(sevp, (void *)&sevp_k, sizeof(struct ksigevent)) ||
  2818. !lwp_put_to_user(timerid, (void *)&utimer, sizeof(utimer)))
  2819. ret = -EINVAL;
  2820. }
  2821. #else
  2822. ret = _SYS_WRAP(timer_create(clockid, sevp, timerid));
  2823. #endif
  2824. return ret;
  2825. }
  2826. /**
  2827. * @brief Deletes a timer.
  2828. *
  2829. * This system call deletes the specified timer and releases any resources associated
  2830. * with it. Once the timer is deleted, it can no longer be used, and any further
  2831. * operations on the timer (such as starting or stopping) will result in an error.
  2832. *
  2833. * @param[in] timerid The ID of the timer to be deleted. This is the timer handle
  2834. * returned by `sys_timer_create`.
  2835. *
  2836. * @return sysret_t Returns a status code indicating the result of the operation:
  2837. * - `0`: The timer was successfully deleted.
  2838. * - Other error codes may indicate additional failures.
  2839. *
  2840. * @note After calling this function, the timer ID becomes invalid, and it should
  2841. * not be used in any further operations.
  2842. *
  2843. * @warning Make sure the timer is not active or in use when attempting to delete it,
  2844. * as deleting an active timer may cause unexpected behavior or resource leaks.
  2845. */
  2846. sysret_t sys_timer_delete(timer_t timerid)
  2847. {
  2848. int ret = timer_delete(timerid);
  2849. return (ret < 0 ? GET_ERRNO() : ret);
  2850. }
  2851. /**
  2852. * @brief Changes the time or interval of an existing timer.
  2853. *
  2854. * This system call modifies the expiration time or interval of a previously created
  2855. * timer. It can either set a new expiration time for the timer or update the
  2856. * interval for periodic timers. The timer can be started or modified based on
  2857. * the flags provided. The current (old) timer settings can be retrieved if
  2858. * requested.
  2859. *
  2860. * @param[in] timerid The ID of the timer to modify. This is the timer handle
  2861. * returned by `sys_timer_create`.
  2862. * @param[in] flags Flags that control the behavior of the operation. Common
  2863. * values include:
  2864. * - `TIMER_ABSTIME`: Specifies that `new_value` contains
  2865. * an absolute time. Otherwise, it is treated as relative.
  2866. * @param[in] new_value A pointer to the `itimerspec` structure specifying
  2867. * the new time settings for the timer. The structure includes:
  2868. * - `it_value`: The initial expiration time (relative or absolute).
  2869. * - `it_interval`: The period for periodic timers.
  2870. * @param[out] old_value A pointer to an `itimerspec` structure where the previous
  2871. * timer settings will be stored. If NULL, the old value is ignored.
  2872. *
  2873. * @return sysret_t Returns a status code indicating the result of the operation:
  2874. * - `0`: The timer time/interval was successfully updated.
  2875. * - Other error codes may indicate additional failures.
  2876. *
  2877. * @warning Modifying a timer that is currently active can cause timing-related issues
  2878. * if not handled correctly. Make sure the timer is in an appropriate state
  2879. * before making changes.
  2880. */
  2881. sysret_t sys_timer_settime(timer_t timerid, int flags,
  2882. const struct itimerspec * restrict new_value,
  2883. struct itimerspec * restrict old_value)
  2884. {
  2885. int ret = 0;
  2886. #ifdef ARCH_MM_MMU
  2887. struct itimerspec new_value_k;
  2888. struct itimerspec old_value_k;
  2889. if (!lwp_get_from_user(&new_value_k, (void *)new_value, sizeof(*new_value)) ||
  2890. (old_value && !lwp_get_from_user(&old_value_k, (void *)old_value, sizeof(*old_value))))
  2891. {
  2892. return -EFAULT;
  2893. }
  2894. ret = timer_settime(timerid, flags, &new_value_k, &old_value_k);
  2895. lwp_put_to_user(old_value, (void *)&old_value_k, sizeof old_value_k);
  2896. #else
  2897. ret = timer_settime(timerid, flags, new_value, old_value);
  2898. #endif
  2899. return (ret < 0 ? GET_ERRNO() : ret);
  2900. }
  2901. /**
  2902. * @brief Retrieves the current time and interval of a timer.
  2903. *
  2904. * This system call fetches the current expiration time (`it_value`) and interval (`it_interval`)
  2905. * of a previously created timer. It allows the caller to determine the current state of the timer,
  2906. * whether it is one-shot or periodic, and the remaining time before expiration.
  2907. *
  2908. * @param[in] timerid The ID of the timer to query. This is the timer handle
  2909. * returned by `sys_timer_create`.
  2910. * @param[out] curr_value A pointer to an `itimerspec` structure where the current timer values
  2911. * will be stored. This structure includes:
  2912. * - `it_value`: The remaining time until the timer expires.
  2913. * - `it_interval`: The interval between subsequent expirations (for periodic timers).
  2914. *
  2915. * @return sysret_t Returns a status code indicating the result of the operation:
  2916. * - `0`: The current time/interval was successfully retrieved.
  2917. * - Other error codes may indicate additional failures.
  2918. *
  2919. * @warning Ensure that the timer ID is valid before calling this function, as invalid timer IDs
  2920. * will result in errors.
  2921. */
  2922. sysret_t sys_timer_gettime(timer_t timerid, struct itimerspec *curr_value)
  2923. {
  2924. int ret = 0;
  2925. #ifdef ARCH_MM_MMU
  2926. struct itimerspec curr_value_k;
  2927. lwp_get_from_user(&curr_value_k, (void *)curr_value, sizeof curr_value_k);
  2928. ret = timer_gettime(timerid, &curr_value_k);
  2929. lwp_put_to_user(curr_value, (void *)&curr_value_k, sizeof curr_value_k);
  2930. #else
  2931. ret = timer_gettime(timerid, curr_value);
  2932. #endif
  2933. return (ret < 0 ? GET_ERRNO() : ret);
  2934. }
  2935. /**
  2936. * @brief Retrieves the overrun count for a periodic timer.
  2937. *
  2938. * This system call retrieves the number of times a periodic timer has "overrun." An overrun occurs
  2939. * when a timer expires before the previous expiration has been acknowledged or handled. For periodic
  2940. * timers, this indicates how many times the timer's expiration has been missed due to delayed processing
  2941. * or handling.
  2942. *
  2943. * @param[in] timerid The ID of the timer to query. This is the timer handle
  2944. * returned by `sys_timer_create`.
  2945. *
  2946. * @return sysret_t Returns a status code indicating the result of the operation:
  2947. * - `0`: The overrun count was successfully retrieved.
  2948. * - Other error codes may indicate additional failures.
  2949. *
  2950. * @warning Ensure that the timer ID is valid before calling this function, as invalid timer IDs
  2951. * will result in errors.
  2952. */
  2953. sysret_t sys_timer_getoverrun(timer_t timerid)
  2954. {
  2955. int ret = 0;
  2956. ret = timer_getoverrun(timerid);
  2957. return (ret < 0 ? GET_ERRNO() : ret);
  2958. }
  2959. /**
  2960. * @brief Creates a new thread.
  2961. *
  2962. * This system call creates a new thread within the calling process. The newly created
  2963. * thread starts executing the function specified by the `arg` argument, which typically
  2964. * contains the necessary arguments or function pointer for the thread's execution.
  2965. *
  2966. * @param[in] arg An array of arguments that will be passed to the function executed
  2967. * by the new thread. This can include function pointers, structures,
  2968. * or any necessary data the thread will need to execute its work.
  2969. *
  2970. * @return rt_thread_t Returns a handle to the newly created thread. If the thread
  2971. * creation fails, `NULL` is returned.
  2972. *
  2973. * @warning Ensure that the system has sufficient resources to create a new thread.
  2974. * Thread creation failures can occur if system limits are exceeded or resources
  2975. * are unavailable.
  2976. */
  2977. rt_thread_t sys_thread_create(void *arg[])
  2978. {
  2979. void *user_stack = 0;
  2980. struct rt_lwp *lwp = 0;
  2981. rt_thread_t thread = RT_NULL;
  2982. int tid = 0;
  2983. lwp = rt_thread_self()->lwp;
  2984. lwp_ref_inc(lwp);
  2985. #ifdef ARCH_MM_MMU
  2986. user_stack = lwp_map_user(lwp, 0, (size_t)arg[3], 0);
  2987. if (!user_stack)
  2988. {
  2989. goto fail;
  2990. }
  2991. if ((tid = lwp_tid_get()) == 0)
  2992. {
  2993. goto fail;
  2994. }
  2995. thread = rt_thread_create((const char *)arg[0],
  2996. _crt_thread_entry,
  2997. (void *)arg[2],
  2998. ALLOC_KERNEL_STACK_SIZE,
  2999. (rt_uint8_t)(size_t)arg[4],
  3000. (rt_uint32_t)(rt_size_t)arg[5]);
  3001. if (!thread)
  3002. {
  3003. goto fail;
  3004. }
  3005. #ifdef RT_USING_SMP
  3006. RT_SCHED_CTX(thread).bind_cpu = lwp->bind_cpu;
  3007. #endif
  3008. thread->cleanup = lwp_cleanup;
  3009. thread->user_entry = (void (*)(void *))arg[1];
  3010. thread->user_stack = (void *)user_stack;
  3011. thread->user_stack_size = (rt_size_t)arg[3];
  3012. #else
  3013. rt_uint32_t kstack_size = (rt_uint32_t)arg[7];
  3014. if (kstack_size < ALLOC_KERNEL_STACK_SIZE_MIN)
  3015. {
  3016. /* When kstack size is 0, the default size of the kernel stack is used */
  3017. kstack_size = kstack_size ? ALLOC_KERNEL_STACK_SIZE_MIN : ALLOC_KERNEL_STACK_SIZE;
  3018. }
  3019. else if (kstack_size > ALLOC_KERNEL_STACK_SIZE_MAX)
  3020. {
  3021. kstack_size = ALLOC_KERNEL_STACK_SIZE_MAX;
  3022. }
  3023. user_stack = (void *)arg[3];
  3024. if ((!user_stack) || ((rt_uint32_t)arg[6] == RT_NULL))
  3025. {
  3026. goto fail;
  3027. }
  3028. if ((tid = lwp_tid_get()) == 0)
  3029. {
  3030. goto fail;
  3031. }
  3032. thread = rt_thread_create((const char *)arg[0], _crt_thread_entry, (void *)arg[2], kstack_size, (rt_uint8_t)(size_t)arg[5], (rt_uint32_t)arg[6]);
  3033. if (!thread)
  3034. {
  3035. goto fail;
  3036. }
  3037. thread->cleanup = lwp_cleanup;
  3038. thread->user_entry = (void (*)(void *))arg[1];
  3039. thread->user_stack = (void *)user_stack;
  3040. thread->user_stack_size = (uint32_t)arg[4];
  3041. rt_memset(thread->user_stack, '#', thread->user_stack_size);
  3042. #endif /* ARCH_MM_MMU */
  3043. thread->lwp = (void *)lwp;
  3044. thread->tid = tid;
  3045. lwp_tid_set_thread(tid, thread);
  3046. if (lwp->debug)
  3047. {
  3048. rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void *)0);
  3049. }
  3050. LWP_LOCK(lwp);
  3051. rt_list_insert_after(&lwp->t_grp, &thread->sibling);
  3052. LWP_UNLOCK(lwp);
  3053. return thread;
  3054. fail:
  3055. lwp_tid_put(tid);
  3056. if (lwp)
  3057. {
  3058. lwp_ref_dec(lwp);
  3059. }
  3060. return RT_NULL;
  3061. }
  3062. #ifdef ARCH_MM_MMU
  3063. long _sys_clone(void *arg[])
  3064. {
  3065. struct rt_lwp *lwp = 0;
  3066. rt_thread_t thread = RT_NULL;
  3067. rt_thread_t self = RT_NULL;
  3068. int tid = 0;
  3069. rt_err_t err;
  3070. unsigned long flags = 0;
  3071. void *user_stack = RT_NULL;
  3072. int *new_tid = RT_NULL;
  3073. void *tls = RT_NULL;
  3074. /*
  3075. musl call flags (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
  3076. | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
  3077. | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED);
  3078. */
  3079. /* check args */
  3080. if (!lwp_user_accessable(arg, sizeof(void *[SYS_CLONE_ARGS_NR])))
  3081. {
  3082. return -EFAULT;
  3083. }
  3084. flags = (unsigned long)(size_t)arg[0];
  3085. if ((flags & (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_THREAD | CLONE_SYSVSEM)) != (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_THREAD | CLONE_SYSVSEM))
  3086. {
  3087. return -EINVAL;
  3088. }
  3089. user_stack = arg[1];
  3090. new_tid = (int *)arg[2];
  3091. tls = (void *)arg[3];
  3092. if ((flags & CLONE_PARENT_SETTID) == CLONE_PARENT_SETTID)
  3093. {
  3094. if (!lwp_user_accessable(new_tid, sizeof(int)))
  3095. {
  3096. return -EFAULT;
  3097. }
  3098. }
  3099. self = rt_thread_self();
  3100. lwp = self->lwp;
  3101. lwp_ref_inc(lwp);
  3102. if (!user_stack)
  3103. {
  3104. SET_ERRNO(EINVAL);
  3105. goto fail;
  3106. }
  3107. if ((tid = lwp_tid_get()) == 0)
  3108. {
  3109. SET_ERRNO(ENOMEM);
  3110. goto fail;
  3111. }
  3112. thread = rt_thread_create(self->parent.name,
  3113. RT_NULL,
  3114. RT_NULL,
  3115. self->stack_size,
  3116. RT_SCHED_PRIV(self).init_priority,
  3117. RT_SCHED_PRIV(self).init_tick);
  3118. if (!thread)
  3119. {
  3120. goto fail;
  3121. }
  3122. #ifdef RT_USING_SMP
  3123. RT_SCHED_CTX(self).bind_cpu = lwp->bind_cpu;
  3124. #endif
  3125. thread->cleanup = lwp_cleanup;
  3126. thread->user_entry = RT_NULL;
  3127. thread->user_stack = RT_NULL;
  3128. thread->user_stack_size = 0;
  3129. thread->lwp = (void *)lwp;
  3130. thread->tid = tid;
  3131. if ((flags & CLONE_SETTLS) == CLONE_SETTLS)
  3132. {
  3133. thread->thread_idr = tls;
  3134. }
  3135. if ((flags & CLONE_PARENT_SETTID) == CLONE_PARENT_SETTID)
  3136. {
  3137. *new_tid = (int)(tid);
  3138. }
  3139. if ((flags & CLONE_CHILD_CLEARTID) == CLONE_CHILD_CLEARTID)
  3140. {
  3141. thread->clear_child_tid = (int *)arg[4];
  3142. }
  3143. if (lwp->debug)
  3144. {
  3145. rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void *)0);
  3146. }
  3147. LWP_LOCK(lwp);
  3148. rt_list_insert_after(&lwp->t_grp, &thread->sibling);
  3149. LWP_UNLOCK(lwp);
  3150. /* copy origin stack */
  3151. lwp_memcpy(thread->stack_addr, self->stack_addr, thread->stack_size);
  3152. lwp_tid_set_thread(tid, thread);
  3153. arch_set_thread_context(arch_clone_exit,
  3154. (void *)((char *)thread->stack_addr + thread->stack_size),
  3155. user_stack, &thread->sp);
  3156. /* new thread never reach there */
  3157. rt_thread_startup(thread);
  3158. return (long)tid;
  3159. fail:
  3160. err = GET_ERRNO();
  3161. RT_ASSERT(err < 0);
  3162. lwp_tid_put(tid);
  3163. if (thread)
  3164. {
  3165. rt_thread_delete(thread);
  3166. }
  3167. if (lwp)
  3168. {
  3169. lwp_ref_dec(lwp);
  3170. }
  3171. return (long)err;
  3172. }
  3173. /**
  3174. * @brief Creates a new process or thread (clone).
  3175. *
  3176. * This system call creates a new process or thread by duplicating the calling process.
  3177. * The new process/thread begins execution by calling the function specified in the
  3178. * `arg[]` array, which typically contains the necessary arguments or function pointer.
  3179. * It is used to implement process/thread creation in the system and is often a lower-level
  3180. * operation in process management.
  3181. *
  3182. * @param[in] arg An array of arguments passed to the new process or thread. This could
  3183. * include function pointers, structures, or any necessary data the
  3184. * new process/thread will need to execute its work.
  3185. *
  3186. * @return long Returns a status code or the process/thread ID of the newly created
  3187. * process/thread. On success, it may return a positive value (such as a
  3188. * thread ID). On failure, a negative value indicating the error is returned.
  3189. *
  3190. * @warning Be cautious when using this function as improper management of process/thread
  3191. * creation can lead to resource exhaustion, deadlocks, or other synchronization issues.
  3192. */
  3193. rt_weak long sys_clone(void *arg[])
  3194. {
  3195. return _sys_clone(arg);
  3196. }
  3197. static void lwp_struct_copy(struct rt_lwp *dst, struct rt_lwp *src)
  3198. {
  3199. #ifdef ARCH_MM_MMU
  3200. dst->end_heap = src->end_heap;
  3201. #endif
  3202. dst->lwp_type = src->lwp_type;
  3203. dst->text_entry = src->text_entry;
  3204. dst->text_size = src->text_size;
  3205. dst->data_entry = src->data_entry;
  3206. dst->data_size = src->data_size;
  3207. dst->args = src->args;
  3208. dst->background = src->background;
  3209. dst->tty = src->tty;
  3210. /* terminal API */
  3211. dst->term_ctrlterm = src->term_ctrlterm;
  3212. rt_memcpy(dst->cmd, src->cmd, RT_NAME_MAX);
  3213. if (src->exe_file)
  3214. {
  3215. if (dst->exe_file)
  3216. {
  3217. rt_free(dst->exe_file);
  3218. }
  3219. dst->exe_file = strndup(src->exe_file, DFS_PATH_MAX);
  3220. }
  3221. rt_memcpy(&dst->signal.sig_action, &src->signal.sig_action, sizeof(dst->signal.sig_action));
  3222. rt_memcpy(&dst->signal.sig_action_mask, &src->signal.sig_action_mask, sizeof(dst->signal.sig_action_mask));
  3223. rt_memcpy(&dst->signal.sig_action_nodefer, &src->signal.sig_action_nodefer, sizeof(dst->signal.sig_action_nodefer));
  3224. rt_memcpy(&dst->signal.sig_action_onstack, &src->signal.sig_action_onstack, sizeof(dst->signal.sig_action_onstack));
  3225. rt_memcpy(&dst->signal.sig_action_restart, &dst->signal.sig_action_restart, sizeof(dst->signal.sig_action_restart));
  3226. rt_memcpy(&dst->signal.sig_action_siginfo, &dst->signal.sig_action_siginfo, sizeof(dst->signal.sig_action_siginfo));
  3227. rt_memcpy(&dst->signal.sig_action_nocldstop, &dst->signal.sig_action_nocldstop, sizeof(dst->signal.sig_action_nocldstop));
  3228. rt_memcpy(&dst->signal.sig_action_nocldwait, &dst->signal.sig_action_nocldwait, sizeof(dst->signal.sig_action_nocldwait));
  3229. rt_strcpy(dst->working_directory, src->working_directory);
  3230. }
  3231. static int lwp_copy_files(struct rt_lwp *dst, struct rt_lwp *src)
  3232. {
  3233. struct dfs_fdtable *dst_fdt;
  3234. struct dfs_fdtable *src_fdt;
  3235. src_fdt = &src->fdt;
  3236. dst_fdt = &dst->fdt;
  3237. /* init fds */
  3238. dst_fdt->fds = rt_calloc(src_fdt->maxfd, sizeof(void *));
  3239. if (dst_fdt->fds)
  3240. {
  3241. struct dfs_file *d_s;
  3242. int i;
  3243. dst_fdt->maxfd = src_fdt->maxfd;
  3244. dfs_file_lock();
  3245. /* dup files */
  3246. for (i = 0; i < src_fdt->maxfd; i++)
  3247. {
  3248. d_s = fdt_get_file(src_fdt, i);
  3249. if (d_s)
  3250. {
  3251. dst_fdt->fds[i] = d_s;
  3252. d_s->ref_count++;
  3253. }
  3254. }
  3255. dfs_file_unlock();
  3256. return 0;
  3257. }
  3258. return -RT_ERROR;
  3259. }
  3260. sysret_t _sys_fork(void)
  3261. {
  3262. int tid = 0;
  3263. sysret_t falival = 0;
  3264. struct rt_lwp *lwp = RT_NULL;
  3265. struct rt_lwp *self_lwp = RT_NULL;
  3266. rt_thread_t thread = RT_NULL;
  3267. rt_thread_t self_thread = RT_NULL;
  3268. void *user_stack = RT_NULL;
  3269. rt_processgroup_t group;
  3270. /* new lwp */
  3271. lwp = lwp_create(LWP_CREATE_FLAG_ALLOC_PID);
  3272. if (!lwp)
  3273. {
  3274. SET_ERRNO(ENOMEM);
  3275. goto fail;
  3276. }
  3277. /* new tid */
  3278. if ((tid = lwp_tid_get()) == 0)
  3279. {
  3280. SET_ERRNO(ENOMEM);
  3281. goto fail;
  3282. }
  3283. /* user space init */
  3284. if (lwp_user_space_init(lwp, 1) != 0)
  3285. {
  3286. SET_ERRNO(ENOMEM);
  3287. goto fail;
  3288. }
  3289. self_lwp = lwp_self();
  3290. /* copy address space of process from this proc to forked one */
  3291. if (lwp_fork_aspace(lwp, self_lwp) != 0)
  3292. {
  3293. SET_ERRNO(ENOMEM);
  3294. goto fail;
  3295. }
  3296. /* copy lwp struct data */
  3297. lwp_struct_copy(lwp, self_lwp);
  3298. /* copy files */
  3299. if (lwp_copy_files(lwp, self_lwp) != 0)
  3300. {
  3301. SET_ERRNO(ENOMEM);
  3302. goto fail;
  3303. }
  3304. /* create thread */
  3305. self_thread = rt_thread_self();
  3306. thread = rt_thread_create(self_thread->parent.name,
  3307. RT_NULL,
  3308. RT_NULL,
  3309. self_thread->stack_size,
  3310. RT_SCHED_PRIV(self_thread).init_priority,
  3311. RT_SCHED_PRIV(self_thread).init_tick);
  3312. if (!thread)
  3313. {
  3314. SET_ERRNO(ENOMEM);
  3315. goto fail;
  3316. }
  3317. thread->cleanup = self_thread->cleanup;
  3318. thread->user_entry = self_thread->user_entry;
  3319. thread->user_stack = self_thread->user_stack;
  3320. thread->user_stack_size = self_thread->user_stack_size;
  3321. thread->signal.sigset_mask = self_thread->signal.sigset_mask;
  3322. thread->thread_idr = self_thread->thread_idr;
  3323. thread->clear_child_tid = self_thread->clear_child_tid;
  3324. thread->lwp = (void *)lwp;
  3325. thread->tid = tid;
  3326. LWP_LOCK(self_lwp);
  3327. /* add thread to lwp process */
  3328. rt_list_insert_after(&lwp->t_grp, &thread->sibling);
  3329. LWP_UNLOCK(self_lwp);
  3330. lwp_children_register(self_lwp, lwp);
  3331. /* set pgid and sid */
  3332. group = lwp_pgrp_find(lwp_pgid_get_byprocess(self_lwp));
  3333. if (group)
  3334. {
  3335. lwp_pgrp_insert(group, lwp);
  3336. }
  3337. else
  3338. {
  3339. LOG_W("the process group of pid: %d cannot be found", lwp_pgid_get_byprocess(self_lwp));
  3340. }
  3341. /* copy kernel stack context from self thread */
  3342. lwp_memcpy(thread->stack_addr, self_thread->stack_addr, self_thread->stack_size);
  3343. lwp_tid_set_thread(tid, thread);
  3344. /* duplicate user objects */
  3345. lwp_user_object_dup(lwp, self_lwp);
  3346. user_stack = arch_get_user_sp();
  3347. arch_set_thread_context(arch_fork_exit,
  3348. (void *)((char *)thread->stack_addr + thread->stack_size),
  3349. user_stack, &thread->sp);
  3350. rt_thread_startup(thread);
  3351. return lwp_to_pid(lwp);
  3352. fail:
  3353. falival = GET_ERRNO();
  3354. if (tid != 0)
  3355. {
  3356. lwp_tid_put(tid);
  3357. }
  3358. if (thread)
  3359. {
  3360. rt_thread_delete(thread);
  3361. }
  3362. if (lwp)
  3363. {
  3364. lwp_ref_dec(lwp);
  3365. }
  3366. return falival;
  3367. }
  3368. /* arm needs to wrap fork/clone call to preserved lr & caller saved regs */
  3369. /**
  3370. * @brief Creates a child process by duplicating the calling process.
  3371. *
  3372. * This system call creates a new child process by duplicating the calling process. The
  3373. * new child process is a copy of the parent process, except for the returned value.
  3374. * The child process starts executing from the point of the fork, but the return value
  3375. * differs between the parent and child: the parent receives the process ID (PID) of the
  3376. * child, and the child receives a return value of 0.
  3377. *
  3378. * @return sysret_t Returns a status code indicating the result of the operation:
  3379. * - A positive value (the child's PID) is returned to the parent.
  3380. * - A value of 0 is returned to the child process.
  3381. * - A negative value indicates an error (e.g., resource limits exceeded).
  3382. *
  3383. * @note This function is commonly used in operating systems to create new processes.
  3384. *
  3385. * @warning Be aware that improper management of child processes (such as failing to handle
  3386. * process termination or excessive forking) can lead to resource exhaustion or
  3387. * other system issues. Ensure proper process handling in the parent and child
  3388. * processes to avoid leaks and inconsistencies.
  3389. */
  3390. rt_weak sysret_t sys_fork(void)
  3391. {
  3392. return _sys_fork();
  3393. }
  3394. rt_weak sysret_t sys_vfork(void)
  3395. {
  3396. return sys_fork();
  3397. }
  3398. #define _swap_lwp_data(lwp_used, lwp_new, type, member) \
  3399. do \
  3400. { \
  3401. type tmp; \
  3402. tmp = lwp_used->member; \
  3403. lwp_used->member = lwp_new->member; \
  3404. lwp_new->member = tmp; \
  3405. } while (0)
  3406. /**
  3407. * @brief Executes a program in the current process.
  3408. *
  3409. * This system call replaces the current process image with a new program specified by the
  3410. * `path` argument. It loads the program located at the given `path` and passes the arguments
  3411. * (`argv`) and environment variables (`envp`) to it. This effectively replaces the calling
  3412. * process with a new one, and if successful, it never returns. If there is an error, the current
  3413. * process continues to execute, and an error code is returned.
  3414. *
  3415. * @param[in] path The path to the executable file to be executed. This should be an
  3416. * absolute or relative file path to the program.
  3417. * @param[in] argv An array of arguments to pass to the new program. The first element
  3418. * (`argv[0]`) should typically be the name of the program, and the array
  3419. * should be terminated with a `NULL` pointer.
  3420. * @param[in] envp An array of environment variables to pass to the new program. This is
  3421. * typically in the form of `key=value` strings, with the array terminated
  3422. * by a `NULL` pointer.
  3423. *
  3424. * @return sysret_t Returns a status code:
  3425. * - `0`: The program was successfully executed (this value is
  3426. * never returned since the process is replaced).
  3427. * - Other error codes may indicate issues with the program execution
  3428. *
  3429. * @note If `execve` is successful, it does not return to the calling function. The process
  3430. * image is replaced by the new program.
  3431. */
  3432. sysret_t sys_execve(const char *path, char * const argv[], char * const envp[])
  3433. {
  3434. rt_err_t error = -1;
  3435. size_t len;
  3436. struct rt_lwp *new_lwp = NULL;
  3437. struct rt_lwp *lwp;
  3438. int uni_thread;
  3439. rt_thread_t thread;
  3440. struct process_aux *aux;
  3441. struct lwp_args_info args_info;
  3442. char *kpath = RT_NULL;
  3443. lwp = lwp_self();
  3444. thread = rt_thread_self();
  3445. uni_thread = 1;
  3446. LWP_LOCK(lwp);
  3447. if (lwp->t_grp.prev != &thread->sibling)
  3448. {
  3449. uni_thread = 0;
  3450. }
  3451. if (lwp->t_grp.next != &thread->sibling)
  3452. {
  3453. uni_thread = 0;
  3454. }
  3455. LWP_UNLOCK(lwp);
  3456. if (!uni_thread)
  3457. {
  3458. return -EINVAL;
  3459. }
  3460. len = lwp_user_strlen(path);
  3461. if (len <= 0)
  3462. {
  3463. return -EFAULT;
  3464. }
  3465. kpath = rt_malloc(len + 1);
  3466. if (!kpath)
  3467. {
  3468. return -ENOMEM;
  3469. }
  3470. if (lwp_get_from_user(kpath, (void *)path, len) != len)
  3471. {
  3472. rt_free(kpath);
  3473. return -EFAULT;
  3474. }
  3475. kpath[len] = '\0';
  3476. if (access(kpath, X_OK) != 0)
  3477. {
  3478. error = rt_get_errno();
  3479. rt_free(kpath);
  3480. return (sysret_t)error;
  3481. }
  3482. /* setup args */
  3483. error = lwp_args_init(&args_info);
  3484. if (error)
  3485. {
  3486. rt_free(kpath);
  3487. return -ENOMEM;
  3488. }
  3489. if (argv)
  3490. {
  3491. error = lwp_args_put_argv(&args_info, (void *)argv);
  3492. if (error)
  3493. {
  3494. error = -EFAULT;
  3495. goto quit;
  3496. }
  3497. }
  3498. if (envp)
  3499. {
  3500. error = lwp_args_put_envp(&args_info, (void *)envp);
  3501. if (error)
  3502. {
  3503. error = -EFAULT;
  3504. goto quit;
  3505. }
  3506. }
  3507. /* alloc new lwp to operation */
  3508. new_lwp = lwp_create(LWP_CREATE_FLAG_NONE);
  3509. if (!new_lwp)
  3510. {
  3511. error = -ENOMEM;
  3512. goto quit;
  3513. }
  3514. error = lwp_user_space_init(new_lwp, 0);
  3515. if (error != 0)
  3516. {
  3517. error = -ENOMEM;
  3518. goto quit;
  3519. }
  3520. /* file is a script ? */
  3521. path = kpath;
  3522. while (1)
  3523. {
  3524. error = lwp_args_load_script(&args_info, path);
  3525. if (error != 0)
  3526. {
  3527. break;
  3528. }
  3529. path = lwp_args_get_argv_0(&args_info);
  3530. }
  3531. /* now load elf */
  3532. if ((aux = lwp_argscopy(new_lwp, &args_info)) == NULL)
  3533. {
  3534. error = -ENOMEM;
  3535. goto quit;
  3536. }
  3537. error = lwp_load(path, new_lwp, RT_NULL, 0, aux);
  3538. if (error == RT_EOK)
  3539. {
  3540. int off = 0;
  3541. int last_backslash = 0;
  3542. /* clear all user objects */
  3543. lwp_user_object_clear(lwp);
  3544. /* find last \ or / to get base name */
  3545. while (1)
  3546. {
  3547. char c = path[off++];
  3548. if (c == '\0')
  3549. {
  3550. break;
  3551. }
  3552. if (c == '\\' || c == '/')
  3553. {
  3554. last_backslash = off;
  3555. }
  3556. }
  3557. /**
  3558. * Set thread name and swap the data of lwp and new_lwp.
  3559. * Since no other threads can access the lwp field, it't uneccessary to
  3560. * take a lock here
  3561. */
  3562. RT_ASSERT(rt_list_entry(lwp->t_grp.prev, struct rt_thread, sibling) == thread);
  3563. strncpy(thread->parent.name, path + last_backslash, RT_NAME_MAX - 1);
  3564. strncpy(lwp->cmd, new_lwp->cmd, RT_NAME_MAX);
  3565. rt_free(lwp->exe_file);
  3566. lwp->exe_file = strndup(new_lwp->exe_file, DFS_PATH_MAX);
  3567. #ifdef ARCH_MM_MMU
  3568. _swap_lwp_data(lwp, new_lwp, struct rt_aspace *, aspace);
  3569. _swap_lwp_data(lwp, new_lwp, size_t, end_heap);
  3570. #endif
  3571. _swap_lwp_data(lwp, new_lwp, uint8_t, lwp_type);
  3572. _swap_lwp_data(lwp, new_lwp, void *, text_entry);
  3573. _swap_lwp_data(lwp, new_lwp, uint32_t, text_size);
  3574. _swap_lwp_data(lwp, new_lwp, void *, data_entry);
  3575. _swap_lwp_data(lwp, new_lwp, uint32_t, data_size);
  3576. _swap_lwp_data(lwp, new_lwp, void *, args);
  3577. lwp_thread_signal_detach(&thread->signal);
  3578. rt_memset(&thread->signal.sigset_mask, 0, sizeof(thread->signal.sigset_mask));
  3579. lwp_signal_detach(&lwp->signal);
  3580. lwp_signal_init(&lwp->signal);
  3581. /* to do: clsoe files with flag CLOEXEC, recy sub-thread */
  3582. lwp_aspace_switch(thread);
  3583. lwp_ref_dec(new_lwp);
  3584. arch_start_umode(lwp->args,
  3585. lwp->text_entry,
  3586. (void *)USER_STACK_VEND,
  3587. (char *)thread->stack_addr + thread->stack_size);
  3588. /* never reach here */
  3589. }
  3590. error = -EINVAL;
  3591. quit:
  3592. if (kpath)
  3593. {
  3594. rt_free(kpath);
  3595. }
  3596. lwp_args_detach(&args_info);
  3597. if (new_lwp)
  3598. {
  3599. lwp_ref_dec(new_lwp);
  3600. }
  3601. return error;
  3602. }
  3603. #endif /* ARCH_MM_MMU */
  3604. /**
  3605. * @brief Deletes a thread.
  3606. *
  3607. * This system call is used to delete an existing thread. The specified thread is terminated,
  3608. * and its resources are released. If the thread is currently running, it will be forcefully
  3609. * terminated. The thread identifier (`thread`) refers to the thread that is to be deleted.
  3610. *
  3611. * @param[in] thread The identifier of the thread to be deleted.
  3612. *
  3613. * @return sysret_t Returns a status code:
  3614. * - `SYSRET_OK`: The thread was successfully deleted.
  3615. * - Other error codes may indicate additional failures.
  3616. *
  3617. * @note This function should be used carefully, as forcefully terminating a thread may
  3618. * lead to resource leaks or inconsistent state if the thread is performing critical
  3619. * operations at the time of termination.
  3620. *
  3621. * @warning Ensure that the thread being deleted has completed its necessary operations
  3622. * and that there are no outstanding resources or critical tasks before deleting
  3623. * it. Otherwise, it might lead to undefined behavior or resource leaks.
  3624. */
  3625. sysret_t sys_thread_delete(rt_thread_t thread)
  3626. {
  3627. #ifdef ARCH_MM_MMU
  3628. return rt_thread_delete(thread);
  3629. #else
  3630. sysret_t ret = 0;
  3631. if (thread->parent.type != RT_Object_Class_Thread)
  3632. {
  3633. ret = -EINVAL;
  3634. goto __exit;
  3635. }
  3636. ret = rt_thread_delete(thread);
  3637. if (rt_thread_self() == thread)
  3638. {
  3639. rt_schedule();
  3640. }
  3641. __exit:
  3642. return ret;
  3643. #endif
  3644. }
  3645. /**
  3646. * @brief Starts a previously created thread.
  3647. *
  3648. * This system call is used to start a thread that was created but has not yet started running.
  3649. * It initiates the thread's execution, allowing it to begin performing its assigned task.
  3650. * The `thread` parameter refers to the thread that is to be started.
  3651. *
  3652. * @param[in] thread The identifier of the thread to be started.
  3653. *
  3654. * @return sysret_t Returns a status code:
  3655. * - `0`: The thread was successfully started.
  3656. * - Other error codes may indicate additional failures.
  3657. *
  3658. * @warning Ensure that the thread has been correctly initialized and is in a valid state
  3659. * before calling this function to avoid undefined behavior. Improper initialization
  3660. * could lead to issues such as the thread not running as expected.
  3661. */
  3662. sysret_t sys_thread_startup(rt_thread_t thread)
  3663. {
  3664. return rt_thread_startup(thread);
  3665. }
  3666. /**
  3667. * @brief Retrieves the identifier of the current thread.
  3668. *
  3669. * This system call returns the thread identifier of the currently executing thread. It allows
  3670. * a thread to obtain its own identifier, which can be useful for various thread management
  3671. * tasks such as self-identification, logging, or checking the thread's status.
  3672. *
  3673. * @return rt_thread_t The identifier of the current thread.
  3674. * If no thread is currently executing, a null or invalid thread ID
  3675. * might be returned depending on the system's implementation.
  3676. *
  3677. * @note This function is typically used when a thread needs to identify itself, especially
  3678. * in cases where thread management is performed dynamically or the thread identifier
  3679. * is required for synchronization or debugging purposes.
  3680. *
  3681. * @warning Be aware that in environments where there is no concept of threads or if the
  3682. * current context is not a thread (e.g., during interrupt handling or early system
  3683. * initialization), the return value might be invalid.
  3684. */
  3685. rt_thread_t sys_thread_self(void)
  3686. {
  3687. return rt_thread_self();
  3688. }
  3689. /* sys channel */
  3690. /**
  3691. * @brief Opens a communication channel.
  3692. *
  3693. * This system call is used to open a communication channel with a specified name and set of flags.
  3694. * The channel allows for inter-process or inter-thread communication, depending on the underlying system.
  3695. * The `name` parameter specifies the name of the channel, while the `flags` parameter allows
  3696. * configuration of the channel's behavior (e.g., read/write permissions, blocking or non-blocking mode).
  3697. *
  3698. * @param[in] name The name of the communication channel to be opened.
  3699. * @param[in] flags The flags to configure the behavior of the channel. These flags may
  3700. * define various properties such as access mode (e.g., read-only, write-only)
  3701. * or synchronization mode (e.g., blocking, non-blocking).
  3702. *
  3703. * @return sysret_t Returns a status code:
  3704. * - `0`: The channel was successfully opened.
  3705. * - Other error codes may indicate issues with the channel opening process.
  3706. *
  3707. * @warning Ensure that the correct flags are passed to configure the channel as required,
  3708. * as improper configuration might lead to access issues, data loss, or undefined behavior.
  3709. */
  3710. sysret_t sys_channel_open(const char *name, int flags)
  3711. {
  3712. rt_size_t ret = 0;
  3713. char *kname = RT_NULL;
  3714. int len = 0;
  3715. len = lwp_user_strlen(name);
  3716. if (len <= 0)
  3717. {
  3718. return -EFAULT;
  3719. }
  3720. kname = (char *)kmem_get(len + 1);
  3721. if (!kname)
  3722. {
  3723. return -ENOMEM;
  3724. }
  3725. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  3726. {
  3727. kmem_put(kname);
  3728. return -EFAULT;
  3729. }
  3730. ret = lwp_channel_open(FDT_TYPE_LWP, kname, flags);
  3731. kmem_put(kname);
  3732. return ret;
  3733. }
  3734. /**
  3735. * @brief Closes an open communication channel.
  3736. *
  3737. * This system call is used to close an already open communication channel specified by the file descriptor `fd`.
  3738. * After closing, the channel can no longer be used for communication, and any resources associated with
  3739. * the channel will be released. This function is necessary for proper resource management, ensuring that
  3740. * system resources (e.g., memory or file handles) are freed when no longer needed.
  3741. *
  3742. * @param[in] fd The file descriptor of the communication channel to be closed.
  3743. *
  3744. * @return sysret_t Returns a status code:
  3745. * - `SYSRET_OK`: The channel was successfully closed.
  3746. * - Other error codes may indicate issues with the channel closing process.
  3747. *
  3748. * @note This function should be called after communication is finished and the channel is no longer
  3749. * needed, to release any system resources associated with it.
  3750. *
  3751. * @warning Calling this function on an invalid or already closed file descriptor may lead to
  3752. * undefined behavior or errors. Ensure that the file descriptor is valid and that the
  3753. * channel is not already closed before attempting to close it.
  3754. */
  3755. sysret_t sys_channel_close(int fd)
  3756. {
  3757. return lwp_channel_close(FDT_TYPE_LWP, fd);
  3758. }
  3759. /**
  3760. * @brief Sends a message through a communication channel.
  3761. *
  3762. * This system call is used to send a message through a specified communication channel identified
  3763. * by the file descriptor `fd`. The message to be sent is provided in the `data` parameter.
  3764. * It allows inter-process or inter-thread communication by transmitting the given message over
  3765. * the open channel.
  3766. *
  3767. * @param[in] fd The file descriptor of the communication channel to send the message to.
  3768. * @param[in] data The message data to be sent. This parameter is typically a structure
  3769. * containing the message content and metadata.
  3770. *
  3771. * @return sysret_t Returns a status code:
  3772. * - `0`: The message was successfully sent.
  3773. * - Other error codes may indicate issues with the message sending process.
  3774. *
  3775. * @note Ensure the channel is open and properly configured for sending messages before
  3776. * calling this function. Additionally, confirm that the `data` structure is valid and
  3777. * initialized with the appropriate content.
  3778. *
  3779. * @warning Failure to verify the channel's readiness or the validity of the data may lead
  3780. * to errors, data loss, or undefined behavior.
  3781. */
  3782. sysret_t sys_channel_send(int fd, rt_channel_msg_t data)
  3783. {
  3784. rt_size_t ret = 0;
  3785. rt_channel_msg_t kdata = RT_NULL;
  3786. if (!lwp_user_accessable((void *)data, sizeof(*data)))
  3787. {
  3788. return -EFAULT;
  3789. }
  3790. kdata = kmem_get(sizeof(*data));
  3791. if (kdata == RT_NULL)
  3792. return -ENOMEM;
  3793. if (lwp_get_from_user(kdata, data, sizeof(*kdata)) != sizeof(*kdata))
  3794. {
  3795. kmem_put(kdata);
  3796. return -EFAULT;
  3797. }
  3798. ret = lwp_channel_send(FDT_TYPE_LWP, fd, kdata);
  3799. kmem_put(kdata);
  3800. return ret;
  3801. }
  3802. /**
  3803. * @brief Sends a message through a communication channel and waits for a response with a timeout.
  3804. *
  3805. * This system call sends a message (`data`) through a specified communication channel identified by the file descriptor `fd`.
  3806. * It then waits for a response (`data_ret`) within the specified timeout period. This is a synchronous operation
  3807. * commonly used in request-response communication patterns between processes or threads.
  3808. *
  3809. * @param[in] fd The file descriptor of the communication channel to send the message to.
  3810. * @param[in] data The message data to be sent. This is typically a structure containing
  3811. * the message content and metadata.
  3812. * @param[out] data_ret The buffer to store the response message received from the channel.
  3813. * @param[in] time The timeout period (in milliseconds) to wait for the response.
  3814. * If set to a negative value, the function will wait indefinitely.
  3815. *
  3816. * @return sysret_t Returns a status code:
  3817. * - `0`: The message was successfully sent, and a response was received.
  3818. * - Other error codes may indicate issues with the communication process.
  3819. *
  3820. * @note This function combines sending and receiving operations into a single atomic action.
  3821. * It is useful for scenarios requiring synchronous communication with a defined timeout
  3822. * to handle cases where a response may not be immediately available.
  3823. *
  3824. * @warning Ensure that the channel is open and properly configured for bidirectional communication.
  3825. * Verify that the `data` structure is valid and initialized, and the `data_ret` buffer is large
  3826. * enough to store the expected response to avoid memory issues or data corruption.
  3827. */
  3828. sysret_t sys_channel_send_recv_timeout(int fd, rt_channel_msg_t data, rt_channel_msg_t data_ret, rt_int32_t time)
  3829. {
  3830. rt_size_t ret = 0;
  3831. rt_channel_msg_t kdata = RT_NULL;
  3832. rt_channel_msg_t kdata_ret = RT_NULL;
  3833. if (!lwp_user_accessable((void *)data, sizeof(*data)))
  3834. {
  3835. return -EFAULT;
  3836. }
  3837. kdata = kmem_get(sizeof(*data));
  3838. if (kdata == RT_NULL)
  3839. return -ENOMEM;
  3840. if (lwp_get_from_user(kdata, data, sizeof(*kdata)) != sizeof(*kdata))
  3841. {
  3842. kmem_put(kdata);
  3843. return -EFAULT;
  3844. }
  3845. kdata_ret = kmem_get(sizeof(*data_ret));
  3846. if (kdata_ret == RT_NULL)
  3847. return -ENOMEM;
  3848. ret = lwp_channel_send_recv_timeout(FDT_TYPE_LWP, fd, kdata, kdata_ret, time);
  3849. lwp_put_to_user(data_ret, kdata_ret, sizeof(*kdata_ret));
  3850. kmem_put(kdata);
  3851. kmem_put(kdata_ret);
  3852. return ret;
  3853. }
  3854. /**
  3855. * @brief Sends a reply message through a communication channel.
  3856. *
  3857. * This system call is used to send a reply (`data`) through a communication channel identified
  3858. * by the file descriptor `fd`. It is typically called in response to a received request
  3859. * within a request-response communication pattern. The reply is sent to the requesting entity
  3860. * through the same channel.
  3861. *
  3862. * @param[in] fd The file descriptor of the communication channel to send the reply to.
  3863. * @param[in] data The reply message to be sent. This is typically a structure containing
  3864. * the reply content and metadata.
  3865. *
  3866. * @return sysret_t Returns a status code:
  3867. * - `0`: The reply was successfully sent.
  3868. * - Other error codes may indicate issues with the reply sending process.
  3869. *
  3870. * @note This function is usually called in a server or responder context, where a request
  3871. * is received, processed, and the result is sent back to the requester. Ensure that
  3872. * the channel is open and configured to send replies before calling this function.
  3873. *
  3874. * @warning Ensure the `data` structure is valid and properly initialized before sending.
  3875. * Sending invalid or corrupted data may lead to unexpected behavior or communication failures.
  3876. */
  3877. sysret_t sys_channel_reply(int fd, rt_channel_msg_t data)
  3878. {
  3879. rt_size_t ret = 0;
  3880. rt_channel_msg_t kdata = RT_NULL;
  3881. if (!lwp_user_accessable((void *)data, sizeof(*data)))
  3882. {
  3883. return -EFAULT;
  3884. }
  3885. kdata = kmem_get(sizeof(*data));
  3886. if (kdata == RT_NULL)
  3887. return -ENOMEM;
  3888. if (lwp_get_from_user(kdata, data, sizeof(*kdata)) != sizeof(*data))
  3889. {
  3890. kmem_put(kdata);
  3891. return -EFAULT;
  3892. }
  3893. ret = lwp_channel_reply(FDT_TYPE_LWP, fd, kdata);
  3894. kmem_put(kdata);
  3895. return ret;
  3896. }
  3897. /**
  3898. * @brief Receives a message from a communication channel with a timeout.
  3899. *
  3900. * This system call attempts to receive a message from a specified communication channel identified
  3901. * by the file descriptor `fd`. The received message is stored in the `data` buffer. If no message
  3902. * is available within the specified timeout period, the function returns with a timeout status.
  3903. *
  3904. * @param[in] fd The file descriptor of the communication channel to receive the message from.
  3905. * @param[out] data The buffer to store the received message. This parameter is typically a
  3906. * structure containing the message content and metadata.
  3907. * @param[in] time The timeout period (in milliseconds) to wait for a message.
  3908. * A negative value indicates that the function will wait indefinitely.
  3909. *
  3910. * @return sysret_t Returns a status code:
  3911. * - `0`: A message was successfully received.
  3912. * - `-ETIMEDOUT`: The operation timed out before a message was received.
  3913. * - Other error codes may indicate issues with the message receiving process.
  3914. *
  3915. * @note This function is useful in scenarios where blocking indefinitely is not desirable,
  3916. * allowing the caller to specify a timeout for receiving messages. It is commonly
  3917. * used in event-driven or time-sensitive communication systems.
  3918. *
  3919. * @warning Ensure that the channel is open and configured for receiving messages before calling
  3920. * this function. The `data` buffer must be valid and large enough to store the expected
  3921. * message to avoid memory corruption or data loss.
  3922. */
  3923. sysret_t sys_channel_recv_timeout(int fd, rt_channel_msg_t data, rt_int32_t time)
  3924. {
  3925. rt_size_t ret = 0;
  3926. rt_channel_msg_t kdata = RT_NULL;
  3927. kdata = kmem_get(sizeof(*data));
  3928. if (kdata == RT_NULL)
  3929. return -ENOMEM;
  3930. ret = lwp_channel_recv_timeout(FDT_TYPE_LWP, fd, kdata, time);
  3931. lwp_put_to_user(data, kdata, sizeof(*kdata));
  3932. kmem_put(kdata);
  3933. return ret;
  3934. }
  3935. static struct rt_semaphore critical_lock;
  3936. static int critical_init(void)
  3937. {
  3938. rt_sem_init(&critical_lock, "ct_lock", 1, RT_IPC_FLAG_FIFO);
  3939. return 0;
  3940. }
  3941. INIT_DEVICE_EXPORT(critical_init);
  3942. /**
  3943. * @brief Enters a critical section to prevent context switching or interrupts.
  3944. *
  3945. * @note Critical sections are typically used to protect shared resources or perform
  3946. * non-interruptible operations. Ensure to exit the critical section as soon as
  3947. * possible by calling `sys_exit_critical` to avoid system performance degradation
  3948. * or deadlocks.
  3949. *
  3950. * @warning Failure to exit a critical section (e.g., due to an exception or missing
  3951. * `sys_exit_critical` call) may lead to system instability or a complete halt.
  3952. */
  3953. void sys_enter_critical(void)
  3954. {
  3955. rt_sem_take(&critical_lock, RT_WAITING_FOREVER);
  3956. }
  3957. /**
  3958. * @brief Exits a critical section and restores the system's previous state.
  3959. *
  3960. * @note Exiting the critical section as soon as the protected operation is completed
  3961. * is essential to avoid performance degradation or system deadlocks. Ensure
  3962. * that every call to `sys_enter_critical` is matched with a corresponding
  3963. * `sys_exit_critical` call.
  3964. *
  3965. * @warning Calling this function without a prior `sys_enter_critical` may result
  3966. * in undefined behavior or system instability. Use carefully in nested
  3967. * critical sections and ensure proper tracking of critical section depth
  3968. * if required.
  3969. */
  3970. void sys_exit_critical(void)
  3971. {
  3972. rt_sem_release(&critical_lock);
  3973. }
  3974. /* syscall: "sys_log" ret: "int" args: "const char*" "size" */
  3975. static int __sys_log_enable = 0;
  3976. static int sys_log_enable(int argc, char **argv)
  3977. {
  3978. if (argc == 1)
  3979. {
  3980. rt_kprintf("sys_log = %d\n", __sys_log_enable);
  3981. return 0;
  3982. }
  3983. else
  3984. {
  3985. __sys_log_enable = atoi(argv[1]);
  3986. }
  3987. return 0;
  3988. }
  3989. MSH_CMD_EXPORT_ALIAS(sys_log_enable, sys_log, sys_log 1(enable) / 0(disable));
  3990. /**
  3991. * @brief Logs a message to the system logging mechanism.
  3992. *
  3993. * This system call writes a log message to the system log for diagnostic or informational purposes.
  3994. * The message is specified by the `log` parameter, and its size is given by the `size` parameter.
  3995. * The logging mechanism is typically used for tracking system events, debugging, or reporting errors.
  3996. *
  3997. * @param[in] log A pointer to the message to be logged. The message should be a valid character
  3998. * array or string.
  3999. * @param[in] size The size of the log message in bytes. This specifies the number of bytes to write
  4000. * from the `log` buffer.
  4001. *
  4002. * @return sysret_t Returns a status code:
  4003. * - `0`: The log message was successfully written.
  4004. * - Other error codes may indicate issues with the logging process.
  4005. *
  4006. * @note Ensure that the `log` pointer is valid and points to a properly initialized memory buffer.
  4007. * Truncation may occur if the logging system has a size limitation. Logging should not be used
  4008. * in performance-critical paths as it may introduce latency.
  4009. *
  4010. * @warning Passing a `NULL` pointer or an invalid `size` may lead to undefined behavior. Ensure the
  4011. * logging system is properly initialized before invoking this function.
  4012. */
  4013. sysret_t sys_log(const char *log, int size)
  4014. {
  4015. char *klog = RT_NULL;
  4016. rt_device_t console = RT_NULL;
  4017. if (!lwp_user_accessable((void *)log, size))
  4018. return -EFAULT;
  4019. klog = kmem_get(size);
  4020. if (klog == RT_NULL)
  4021. {
  4022. return -ENOMEM;
  4023. }
  4024. if (lwp_get_from_user((void *)klog, (void *)log, size) != size)
  4025. {
  4026. kmem_put(klog);
  4027. return -EINVAL;
  4028. }
  4029. console = rt_console_get_device();
  4030. if (console && __sys_log_enable)
  4031. {
  4032. rt_device_write(console, -1, klog, size);
  4033. }
  4034. kmem_put(klog);
  4035. return 0;
  4036. }
  4037. /**
  4038. * @brief Retrieves information about a file or directory.
  4039. *
  4040. * This system call obtains metadata about the specified file or directory and stores it in
  4041. * the `buf` structure. The metadata includes attributes such as file size, permissions,
  4042. * ownership, and timestamps.
  4043. *
  4044. * @param[in] file A pointer to the path of the file or directory to be queried.
  4045. * The path should be a null-terminated string.
  4046. * @param[out] buf A pointer to a `struct stat` structure where the file's metadata
  4047. * will be stored. This structure must be allocated by the caller.
  4048. *
  4049. * @return sysret_t Returns a status code:
  4050. * - `0`: The operation completed successfully, and the metadata
  4051. * has been written to `buf`.
  4052. * - Other error codes may indicate issues with the file path.
  4053. *
  4054. * @note The `file` path must be valid and accessible by the calling process. Ensure that
  4055. * the `buf` pointer points to a properly allocated memory region.
  4056. *
  4057. * @warning Passing a `NULL` pointer for `file` or `buf` may result in undefined behavior.
  4058. * Check all inputs before invoking this function to avoid potential issues.
  4059. */
  4060. sysret_t sys_stat(const char *file, struct stat *buf)
  4061. {
  4062. int ret = 0;
  4063. size_t len;
  4064. size_t copy_len;
  4065. char *copy_path;
  4066. struct stat statbuff = { 0 };
  4067. if (!lwp_user_accessable((void *)buf, sizeof(struct stat)))
  4068. {
  4069. return -EFAULT;
  4070. }
  4071. len = lwp_user_strlen(file);
  4072. if (len <= 0)
  4073. {
  4074. return -EFAULT;
  4075. }
  4076. copy_path = (char *)rt_malloc(len + 1);
  4077. if (!copy_path)
  4078. {
  4079. return -ENOMEM;
  4080. }
  4081. copy_len = lwp_get_from_user(copy_path, (void *)file, len);
  4082. if (copy_len == 0)
  4083. {
  4084. rt_free(copy_path);
  4085. return -EFAULT;
  4086. }
  4087. copy_path[copy_len] = '\0';
  4088. ret = _SYS_WRAP(stat(copy_path, &statbuff));
  4089. rt_free(copy_path);
  4090. if (ret == 0)
  4091. {
  4092. lwp_put_to_user(buf, &statbuff, sizeof statbuff);
  4093. }
  4094. return ret;
  4095. }
  4096. /**
  4097. * @brief Retrieves metadata about a file or symbolic link.
  4098. *
  4099. * This system call obtains metadata for the specified file or symbolic link and stores
  4100. * it in the `buf` structure. Unlike `sys_stat`, if the specified path refers to a
  4101. * symbolic link, this function retrieves information about the link itself, not the
  4102. * target it points to.
  4103. *
  4104. * @param[in] file A pointer to the path of the file or symbolic link to be queried.
  4105. * The path must be a null-terminated string.
  4106. * @param[out] buf A pointer to a `struct stat` structure where the metadata will be
  4107. * stored. This structure must be allocated by the caller.
  4108. *
  4109. * @return sysret_t Returns a status code:
  4110. * - `0`: The operation completed successfully, and the metadata
  4111. * has been written to `buf`.
  4112. * - Other error codes may indicate issues with the file path.
  4113. *
  4114. * @note This function is particularly useful for handling symbolic links when you want
  4115. * to get information about the link itself rather than the target file or directory.
  4116. * The `file` path must be valid and accessible by the calling process.
  4117. *
  4118. * @warning Passing a `NULL` pointer for `file` or `buf` may result in undefined behavior.
  4119. * Always check inputs for validity before invoking this function.
  4120. */
  4121. sysret_t sys_lstat(const char *file, struct stat *buf)
  4122. {
  4123. int ret = 0;
  4124. size_t len;
  4125. size_t copy_len;
  4126. char *copy_path;
  4127. struct stat statbuff = { 0 };
  4128. if (!lwp_user_accessable((void *)buf, sizeof(struct stat)))
  4129. {
  4130. return -EFAULT;
  4131. }
  4132. len = lwp_user_strlen(file);
  4133. if (len <= 0)
  4134. {
  4135. return -EFAULT;
  4136. }
  4137. copy_path = (char *)rt_malloc(len + 1);
  4138. if (!copy_path)
  4139. {
  4140. return -ENOMEM;
  4141. }
  4142. copy_len = lwp_get_from_user(copy_path, (void *)file, len);
  4143. if (copy_len == 0)
  4144. {
  4145. rt_free(copy_path);
  4146. return -EFAULT;
  4147. }
  4148. copy_path[copy_len] = '\0';
  4149. #ifdef RT_USING_DFS_V2
  4150. ret = _SYS_WRAP(dfs_file_lstat(copy_path, &statbuff));
  4151. #else
  4152. ret = _SYS_WRAP(stat(copy_path, &statbuff));
  4153. #endif
  4154. rt_free(copy_path);
  4155. if (ret == 0)
  4156. {
  4157. lwp_put_to_user(buf, &statbuff, sizeof statbuff);
  4158. }
  4159. return ret;
  4160. }
  4161. sysret_t sys_notimpl(void)
  4162. {
  4163. return -ENOSYS;
  4164. }
  4165. uint32_t sys_hw_interrupt_disable(void)
  4166. {
  4167. return rt_hw_interrupt_disable();
  4168. }
  4169. void sys_hw_interrupt_enable(uint32_t level)
  4170. {
  4171. rt_hw_interrupt_enable(level);
  4172. }
  4173. #ifdef ARCH_MM_MMU
  4174. /**
  4175. * @brief Allocates or retrieves a shared memory segment.
  4176. *
  4177. * This system call allocates a new shared memory segment or retrieves an existing one
  4178. * based on the specified `key`. Shared memory allows processes to communicate by
  4179. * sharing a region of memory.
  4180. *
  4181. * @param[in] key A unique identifier for the shared memory segment. If `key` matches
  4182. * an existing segment, it will be retrieved. If `create` is set and the
  4183. * segment does not exist, a new one will be created.
  4184. * @param[in] size The size (in bytes) of the shared memory segment. If creating a new
  4185. * segment, this specifies its size. If retrieving an existing segment,
  4186. * `size` is ignored.
  4187. * @param[in] create A flag indicating whether to create the segment if it does not exist:
  4188. * - `1`: Create the shared memory segment if it does not exist.
  4189. * - `0`: Only retrieve an existing segment.
  4190. *
  4191. * @return sysret_t Returns a status code:
  4192. * - `0`: The shared memory segment was successfully created or
  4193. * retrieved.
  4194. * - Other error codes may indicate issues with the shared memory
  4195. *
  4196. * @note Shared memory segments identified by the same `key` are accessible across
  4197. * processes. Ensure proper synchronization mechanisms (e.g., semaphores) are in
  4198. * place to manage access to the shared memory.
  4199. *
  4200. * @warning Using a `NULL` or invalid `key` may result in undefined behavior. When creating
  4201. * a new segment, ensure that `size` is non-zero and meaningful.
  4202. */
  4203. sysret_t sys_shmget(size_t key, size_t size, int create)
  4204. {
  4205. return lwp_shmget(key, size, create);
  4206. }
  4207. /**
  4208. * @brief Removes a shared memory segment.
  4209. *
  4210. * This system call removes the specified shared memory segment identified by its `id`.
  4211. * Once removed, the segment will no longer be accessible, and any memory associated
  4212. * with it will be freed. It is typically used to clean up shared memory resources
  4213. * when they are no longer needed.
  4214. *
  4215. * @param[in] id The identifier of the shared memory segment to be removed. This identifier
  4216. * was obtained when the segment was created or retrieved using `sys_shmget`.
  4217. *
  4218. * @return sysret_t Returns a status code:
  4219. * - `0`: The shared memory segment was successfully removed.
  4220. * - Other error codes may indicate issues with the shared memory removal.
  4221. *
  4222. * @note This function should be called only when all processes that were using the shared
  4223. * memory segment have finished accessing it. Removing the segment while it is in use
  4224. * by another process may result in undefined behavior or memory corruption.
  4225. *
  4226. * @warning Ensure that the shared memory segment is no longer needed by any process before
  4227. * calling this function to avoid premature removal and potential data loss.
  4228. */
  4229. sysret_t sys_shmrm(int id)
  4230. {
  4231. return lwp_shmrm(id);
  4232. }
  4233. /**
  4234. * @brief Attaches a shared memory segment to the calling process's address space.
  4235. *
  4236. * This system call maps a shared memory segment identified by `id` into the calling
  4237. * process's address space. The segment can then be accessed using the returned virtual
  4238. * address. If the segment was previously detached or created, it will be made available
  4239. * for reading and writing.
  4240. *
  4241. * @param[in] id The identifier of the shared memory segment to be attached.
  4242. * This identifier was obtained when the segment was created
  4243. * or retrieved using `sys_shmget`.
  4244. * @param[in] shm_vaddr A pointer to the desired virtual address where the shared
  4245. * memory segment should be mapped. If `NULL`, the system will
  4246. * choose an appropriate address.
  4247. *
  4248. * @return void* Returns the virtual address where the shared memory segment
  4249. * is mapped. On success, this will be the address in the
  4250. * calling process's address space. If the attachment fails,
  4251. * `NULL` is returned.
  4252. *
  4253. * @note Once the shared memory segment is attached, it can be accessed like any
  4254. * regular memory, but it should be used with caution, especially in multi-process
  4255. * environments. Ensure that proper synchronization mechanisms (e.g., semaphores)
  4256. * are used to manage concurrent access.
  4257. *
  4258. * @warning Ensure that the shared memory segment is properly allocated and not in use
  4259. * by other processes before attaching it. Passing invalid `id` or an inaccessible
  4260. * segment may result in undefined behavior.
  4261. */
  4262. void *sys_shmat(int id, void *shm_vaddr)
  4263. {
  4264. return lwp_shmat(id, shm_vaddr);
  4265. }
  4266. /**
  4267. * @brief Detaches a shared memory segment from the calling process's address space.
  4268. *
  4269. * This system call detaches the shared memory segment previously attached to the calling
  4270. * process's address space using `sys_shmat`. After calling this function, the shared
  4271. * memory will no longer be accessible via the returned address.
  4272. *
  4273. * @param[in] shm_vaddr A pointer to the virtual address where the shared memory
  4274. * segment was previously mapped. This address was returned
  4275. * by the `sys_shmat` function.
  4276. *
  4277. * @return sysret_t Returns a status code:
  4278. * - `0`: The shared memory segment was successfully detached.
  4279. * - Other error codes may indicate issues with the detachment process.
  4280. *
  4281. * @note It is important to ensure that no processes are using the shared memory segment
  4282. * before detaching it. Detaching the segment while it is still being accessed
  4283. * may lead to undefined behavior.
  4284. *
  4285. * @warning Ensure that `shm_vaddr` corresponds to a valid attached address returned
  4286. * by `sys_shmat`. Passing an incorrect or uninitialized address may result
  4287. * in undefined behavior.
  4288. */
  4289. sysret_t sys_shmdt(void *shm_vaddr)
  4290. {
  4291. return lwp_shmdt(shm_vaddr);
  4292. }
  4293. #elif defined RT_LWP_USING_SHM
  4294. /**
  4295. * @brief Allocates a new shared memory segment.
  4296. *
  4297. * This system call allocates a new shared memory segment of the specified size and
  4298. * returns a pointer to the allocated memory. The allocated segment can be used for
  4299. * inter-process communication or shared memory access. The segment is typically
  4300. * managed by the system, and it can be accessed by other processes with appropriate
  4301. * synchronization.
  4302. *
  4303. * @param[in] size The size (in bytes) of the shared memory segment to be allocated.
  4304. *
  4305. * @return void* Returns a pointer to the allocated shared memory segment.
  4306. * If the allocation fails, `RT_NULL` is returned.
  4307. *
  4308. * @note The allocated shared memory segment can be used like regular memory,
  4309. * but it should be accessed with proper synchronization mechanisms (e.g.,
  4310. * semaphores or mutexes) to avoid race conditions or data corruption in
  4311. * multi-process environments.
  4312. *
  4313. * @warning Ensure that the `size` parameter is a valid, non-zero value, and that
  4314. * there is enough system memory to allocate the requested size.
  4315. * Failure to do so may result in errors or resource exhaustion.
  4316. */
  4317. void *sys_shm_alloc(int size)
  4318. {
  4319. if (size < 0)
  4320. {
  4321. return RT_NULL;
  4322. }
  4323. return lwp_shm_alloc((rt_size_t)size);
  4324. }
  4325. /**
  4326. * @brief Retains an existing shared memory segment.
  4327. *
  4328. * This system call retains an existing shared memory segment that was previously
  4329. * allocated or attached, ensuring it remains available for further use. It is
  4330. * typically used to increment the reference count or to ensure the segment is
  4331. * not removed or deallocated while it is still being used.
  4332. *
  4333. * @param[in] mem A pointer to the shared memory segment to retain. This should be
  4334. * the address previously returned by a memory allocation or
  4335. * attachment function such as `sys_shmat` or `sys_shm_alloc`.
  4336. *
  4337. * @return void* Returns the original pointer `mem` if the retention is successful.
  4338. * If the operation fails, `NULL` is returned.
  4339. *
  4340. * @note This function does not affect the actual content of the shared memory segment,
  4341. * but ensures the segment is not removed or deallocated while still in use.
  4342. * It is generally used in conjunction with `sys_shmdt` or `sys_shmrm` to ensure
  4343. * proper resource management.
  4344. *
  4345. * @warning Ensure that the provided pointer `mem` corresponds to a valid shared
  4346. * memory segment that is currently allocated or attached. Passing an
  4347. * invalid or uninitialized pointer may result in undefined behavior.
  4348. */
  4349. void *sys_shm_retain(void *mem)
  4350. {
  4351. if (!lwp_user_accessable(mem, sizeof(void *)))
  4352. {
  4353. return RT_NULL;
  4354. }
  4355. return lwp_shm_retain(mem);
  4356. }
  4357. /**
  4358. * @brief Frees a previously allocated shared memory segment.
  4359. *
  4360. * This system call frees a shared memory segment that was previously allocated or
  4361. * retained using functions like `sys_shm_alloc` or `sys_shm_retain`. It ensures
  4362. * that the shared memory is properly deallocated, making it available for future
  4363. * allocations or for removal from the system.
  4364. *
  4365. * @param[in] mem A pointer to the shared memory segment to be freed. This should be
  4366. * the address returned by a memory allocation or retention function.
  4367. *
  4368. * @return sysret_t Returns a status code:
  4369. * - `0`: The shared memory segment was successfully freed.
  4370. * - Other error codes may indicate issues with the memory deallocation.
  4371. *
  4372. * @note After calling this function, the memory will be deallocated, and any subsequent
  4373. * access to the freed memory will result in undefined behavior. Ensure that no
  4374. * processes are using the shared memory before calling this function.
  4375. *
  4376. * @warning Ensure that `mem` corresponds to a valid shared memory segment that was
  4377. * previously allocated or retained. Passing an invalid or already freed
  4378. * pointer may result in undefined behavior.
  4379. */
  4380. sysret_t sys_shm_free(void *mem)
  4381. {
  4382. if (!lwp_user_accessable(mem, sizeof(void *)))
  4383. {
  4384. return -EFAULT;
  4385. }
  4386. lwp_shm_free(mem);
  4387. return 0;
  4388. }
  4389. #endif
  4390. /* device interfaces */
  4391. /**
  4392. * @brief Initializes a device.
  4393. *
  4394. * This system call initializes the specified device, preparing it for use. Device initialization
  4395. * typically involves setting up necessary hardware configurations, registering device drivers,
  4396. * and ensuring that the device is in a ready state for further operations. This function should
  4397. * be called before interacting with the device.
  4398. *
  4399. * @param[in] dev A pointer to the device structure that represents the device to be initialized.
  4400. * This structure contains device-specific configuration and state information.
  4401. *
  4402. * @return sysret_t Returns a status code:
  4403. * - `0`: The device was successfully initialized.
  4404. * - Other error codes may indicate issues with the device initialization process.
  4405. *
  4406. * @note This function is typically called once during system startup or when a device is
  4407. * first accessed. It ensures that all necessary setup steps are completed before
  4408. * the device can be used.
  4409. *
  4410. * @warning Ensure that the device passed to this function is valid and properly configured
  4411. * before initialization. Initializing an invalid or improperly configured device
  4412. * may result in unpredictable behavior.
  4413. */
  4414. sysret_t sys_device_init(rt_device_t dev)
  4415. {
  4416. return rt_device_init(dev);
  4417. }
  4418. /**
  4419. * @brief Registers a device with the system.
  4420. *
  4421. * This system call registers a device with the system, making it available for interaction
  4422. * by the operating system or other components. Registration typically involves associating
  4423. * the device with a name and setting up the necessary flags for the device's behavior.
  4424. *
  4425. * @param[in] dev A pointer to the device structure that represents the device to be registered.
  4426. * This structure contains the device's configuration, capabilities, and state.
  4427. * @param[in] name A string representing the name by which the device will be identified in the system.
  4428. * This name is used for device lookup and reference.
  4429. * @param[in] flags A set of flags that configure the behavior of the device, such as enabling
  4430. * or disabling certain features, or specifying the device's mode of operation.
  4431. *
  4432. * @return sysret_t Returns a status code:
  4433. * - `0`: The device was successfully registered.
  4434. * - Other error codes may indicate issues with the device registration process.
  4435. *
  4436. * @note This function should be called after the device has been initialized (via `sys_device_init`)
  4437. * and before the device is used by the system or other components.
  4438. *
  4439. * @warning Ensure that the `name` provided is unique and not already in use by another device in the system.
  4440. * Passing invalid `dev` or `flags` may result in unexpected behavior or failure of device registration.
  4441. */
  4442. sysret_t sys_device_register(rt_device_t dev, const char *name, rt_uint16_t flags)
  4443. {
  4444. return rt_device_register(dev, name, flags);
  4445. }
  4446. /**
  4447. * @brief Controls a device by sending a command.
  4448. *
  4449. * This system call sends a control command to the specified device, allowing the system or other
  4450. * components to modify the device's behavior or state. The command is specified by the `cmd`
  4451. * parameter, and the arguments for the command are passed via the `arg` parameter.
  4452. *
  4453. * @param[in] dev A pointer to the device structure representing the device to be controlled.
  4454. * The device must have been previously registered and initialized.
  4455. * @param[in] cmd The control command to be sent to the device. The meaning and behavior of the
  4456. * command are device-specific and depend on the device type.
  4457. * @param[in] arg A pointer to the arguments required by the command. The type and content of
  4458. * the arguments are determined by the command. Some commands may not require
  4459. * arguments, in which case `arg` can be `NULL`.
  4460. *
  4461. * @return sysret_t Returns a status code:
  4462. * - `0`: The command was successfully executed on the device.
  4463. * - Other error codes may indicate issues with the command execution or device control.
  4464. *
  4465. * @note The set of available commands (`cmd`) and the expected argument types (`arg`) are specific
  4466. * to each device. Refer to the device documentation for the supported commands and argument
  4467. * formats.
  4468. *
  4469. * @warning Ensure that the `dev` pointer is valid and points to a correctly initialized device.
  4470. * Providing an invalid device or incorrect command may result in undefined behavior.
  4471. */
  4472. sysret_t sys_device_control(rt_device_t dev, int cmd, void *arg)
  4473. {
  4474. return rt_device_control(dev, cmd, arg);
  4475. }
  4476. /**
  4477. * @brief Finds a device by its name.
  4478. *
  4479. * This system call searches for a device that has been registered with the system using the
  4480. * specified name. If the device exists, a pointer to the device structure is returned,
  4481. * allowing further interaction with the device. If no device with the specified name is found,
  4482. * a `NULL` pointer is returned.
  4483. *
  4484. * @param[in] name The name of the device to search for. This name must match the name used
  4485. * during device registration (e.g., via `sys_device_register`).
  4486. *
  4487. * @return rt_device_t Returns a pointer to the device structure if the device is found.
  4488. * Returns `NULL` if no device with the specified name exists.
  4489. *
  4490. * @note The device must have been previously registered with the system using `sys_device_register`.
  4491. *
  4492. * @warning Ensure that the provided `name` is a valid string and corresponds to a registered device.
  4493. * Passing an invalid or non-registered name will result in `NULL` being returned.
  4494. */
  4495. rt_device_t sys_device_find(const char *name)
  4496. {
  4497. return rt_device_find(name);
  4498. }
  4499. /**
  4500. * @brief Opens a device for use.
  4501. *
  4502. * This system call opens the specified device, making it ready for interaction with the system
  4503. * or other components. The device must have been previously registered and initialized.
  4504. * The `oflag` parameter specifies the open mode, which may determine how the device is accessed
  4505. * (e.g., read, write, or exclusive access).
  4506. *
  4507. * @param[in] dev A pointer to the device structure representing the device to be opened.
  4508. * The device must be registered and initialized before being opened.
  4509. * @param[in] oflag The open flags that determine the mode of access to the device. These flags
  4510. * may specify read, write, or other modes of operation, depending on the device's capabilities.
  4511. *
  4512. * @return sysret_t Returns a status code:
  4513. * - `0`: The device was successfully opened.
  4514. * - Other error codes may indicate issues with the device opening process.
  4515. *
  4516. * @note The open flags (`oflag`) should be set according to the device's capabilities. For example,
  4517. * some devices may support read or write operations, while others may only support one of them.
  4518. * Check the device documentation for supported flags.
  4519. *
  4520. * @warning Ensure that the device pointer (`dev`) is valid and that the device has been initialized
  4521. * properly. Incorrect flags or attempting to open a device that is already in use may result
  4522. * in errors or undefined behavior.
  4523. */
  4524. sysret_t sys_device_open(rt_device_t dev, rt_uint16_t oflag)
  4525. {
  4526. return rt_device_open(dev, oflag);
  4527. }
  4528. /**
  4529. * @brief Closes an open device.
  4530. *
  4531. * This system call closes an open device, releasing any resources or locks associated with it
  4532. * and making it unavailable for further interaction until it is opened again. The device must
  4533. * have been previously opened using `sys_device_open`. After calling this function, any further
  4534. * attempts to interact with the device will result in an error unless the device is opened again.
  4535. *
  4536. * @param[in] dev A pointer to the device structure representing the device to be closed.
  4537. * The device must be open before it can be closed.
  4538. *
  4539. * @return sysret_t Returns a status code:
  4540. * - `0`: The device was successfully closed.
  4541. * - Other error codes may indicate issues with the device closing process.
  4542. *
  4543. * @note This function should be called when the device is no longer needed or before shutting
  4544. * down the system to release device resources properly.
  4545. *
  4546. * @warning Ensure that the device has been opened before calling this function. Calling this function
  4547. * on an uninitialized or already closed device may result in undefined behavior or errors.
  4548. */
  4549. sysret_t sys_device_close(rt_device_t dev)
  4550. {
  4551. return rt_device_close(dev);
  4552. }
  4553. /**
  4554. * @brief Reads data from an open device.
  4555. *
  4556. * This system call reads data from the specified device, starting at the given position and
  4557. * storing the data in the provided buffer. The device must be open before this function can be called.
  4558. * The amount of data to read is determined by the `size` parameter.
  4559. *
  4560. * @param[in] dev A pointer to the device structure representing the device to read from.
  4561. * The device must be open and ready for reading.
  4562. * @param[in] pos The position within the device from which to begin reading. For devices that
  4563. * support seeking, this value is used to specify the starting point.
  4564. * @param[out] buffer A pointer to the buffer where the read data will be stored. This buffer should
  4565. * be large enough to hold the specified amount of data.
  4566. * @param[in] size The number of bytes to read from the device. This value determines how much
  4567. * data is read into the buffer.
  4568. *
  4569. * @return rt_ssize_t Returns the number of bytes actually read from the device:
  4570. * - On success: The number of bytes read, which may be less than `size` if
  4571. * the end of the device is reached or other factors limit the read.
  4572. * - On failure: A negative error code.
  4573. *
  4574. * @note The device must be open and in a readable state before calling this function.
  4575. * The `pos` parameter allows seeking within the device if it supports such operations.
  4576. *
  4577. * @warning Ensure that the buffer provided is large enough to hold the data being read.
  4578. * Providing an insufficient buffer may result in undefined behavior.
  4579. */
  4580. rt_ssize_t sys_device_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size)
  4581. {
  4582. return rt_device_read(dev, pos, buffer, size);
  4583. }
  4584. /**
  4585. * @brief Writes data to an open device.
  4586. *
  4587. * This system call writes data to the specified device, starting at the given position and using
  4588. * the provided buffer. The device must be open and ready for writing. The amount of data to write
  4589. * is determined by the `size` parameter.
  4590. *
  4591. * @param[in] dev A pointer to the device structure representing the device to write to.
  4592. * The device must be open and ready for writing.
  4593. * @param[in] pos The position within the device where the writing should start. For devices
  4594. * that support seeking, this value specifies the location to begin writing.
  4595. * @param[in] buffer A pointer to the buffer containing the data to be written to the device.
  4596. * This buffer should contain the data to be written and should be large enough
  4597. * to accommodate the specified size.
  4598. * @param[in] size The number of bytes to write to the device. This value indicates how much
  4599. * data should be written from the buffer to the device.
  4600. *
  4601. * @return rt_ssize_t Returns the number of bytes actually written to the device:
  4602. * - On success: The number of bytes written, which may be less than `size`
  4603. * if there is an issue with the device or the data was truncated.
  4604. * - On failure: A negative error code.
  4605. *
  4606. * @note The device must be open and in a writable state before calling this function.
  4607. * The `pos` parameter allows seeking within the device if it supports such operations.
  4608. *
  4609. * @warning Ensure that the buffer provided contains valid data and that it is large enough
  4610. * to fit the amount of data specified by `size`. Providing an insufficient buffer
  4611. * or invalid data may lead to undefined behavior.
  4612. */
  4613. rt_ssize_t sys_device_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size)
  4614. {
  4615. return rt_device_write(dev, pos, buffer, size);
  4616. }
  4617. #ifdef RT_USING_SAL
  4618. /* network interfaces */
  4619. /**
  4620. * @brief Accepts a connection on a socket.
  4621. *
  4622. * This system call is used to accept a pending connection request on a socket. It extracts the
  4623. * first connection request from the incoming queue, creates a new socket for the connection,
  4624. * and stores the address information of the remote peer in the provided address structure.
  4625. * The original socket must be a listening socket that has been previously bound and set to listen
  4626. * for incoming connections.
  4627. *
  4628. * @param[in] socket The listening socket file descriptor that is waiting for incoming connections.
  4629. * This socket must be in a listening state, created using `sys_socket` and
  4630. * bound to an address using `sys_bind`.
  4631. * @param[out] addr A pointer to a `musl_sockaddr` structure where the address of the connecting
  4632. * client will be stored. The structure is populated with information such as
  4633. * the client's IP address and port number.
  4634. * @param[in,out] addrlen A pointer to a socklen_t variable that specifies the size of the `addr`
  4635. * structure on input. On output, it will contain the actual size of the
  4636. * address returned in `addr`.
  4637. *
  4638. * @return sysret_t Returns a socket descriptor for the new connection on success, or
  4639. * `SYSRET_ERROR` on failure:
  4640. * - On success: A new socket descriptor that can be used for further
  4641. * communication with the connected peer.
  4642. * - On failure: A negative error code indicating the reason for the failure.
  4643. *
  4644. * @note The socket passed as `socket` must be in a listening state and ready to accept incoming
  4645. * connections. The `addr` structure is populated with the client's address details, which can
  4646. * be used for further operations, such as identifying the client.
  4647. *
  4648. * @warning Ensure that the `addr` structure is sufficiently large to hold the address information.
  4649. * The `addrlen` parameter must be set to the size of the `musl_sockaddr` structure before
  4650. * calling this function. Calling the function with an incorrectly sized `addrlen` may lead
  4651. * to buffer overflows or undefined behavior.
  4652. */
  4653. sysret_t sys_accept(int socket, struct musl_sockaddr *addr, socklen_t *addrlen)
  4654. {
  4655. int ret = -1;
  4656. struct sockaddr ksa;
  4657. struct musl_sockaddr kmusladdr;
  4658. socklen_t uaddrlen;
  4659. socklen_t kaddrlen;
  4660. if (addr)
  4661. {
  4662. if (!lwp_user_accessable(addrlen, sizeof(socklen_t)))
  4663. {
  4664. return -EFAULT;
  4665. }
  4666. lwp_get_from_user(&uaddrlen, addrlen, sizeof(socklen_t));
  4667. if (!uaddrlen)
  4668. {
  4669. return -EINVAL;
  4670. }
  4671. if (!lwp_user_accessable(addr, uaddrlen))
  4672. {
  4673. return -EFAULT;
  4674. }
  4675. }
  4676. kaddrlen = sizeof(struct sockaddr);
  4677. ret = accept(socket, &ksa, &kaddrlen);
  4678. if (ret >= 0)
  4679. {
  4680. if (addr)
  4681. {
  4682. sockaddr_tomusl(&ksa, &kmusladdr);
  4683. if (uaddrlen > sizeof(struct musl_sockaddr))
  4684. {
  4685. uaddrlen = sizeof(struct musl_sockaddr);
  4686. }
  4687. lwp_put_to_user(addr, &kmusladdr, uaddrlen);
  4688. lwp_put_to_user(addrlen, &uaddrlen, sizeof(socklen_t));
  4689. }
  4690. }
  4691. return ret;
  4692. }
  4693. /**
  4694. * @brief Binds a socket to a local address.
  4695. *
  4696. * This system call binds a socket to a specific local address and port. The socket must be created
  4697. * using `sys_socket` before it can be bound. The `bind` operation allows the application to associate
  4698. * a socket with a specific address, such as an IP address and port number, which can then be used
  4699. * for sending or receiving data.
  4700. *
  4701. * @param[in] socket The socket descriptor to which the address will be bound. This socket must
  4702. * be created using `sys_socket` and should not already be bound to another address.
  4703. * @param[in] name A pointer to a `musl_sockaddr` structure that contains the address to which
  4704. * the socket will be bound. This can represent an IP address and port number.
  4705. * @param[in] namelen The size of the `musl_sockaddr` structure in bytes. This value should be set
  4706. * to the actual size of the `name` structure before calling this function.
  4707. *
  4708. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  4709. *
  4710. * @note The `socket` must be created before calling this function, and the address provided in `name`
  4711. * should be a valid local address for the socket. This operation is typically used for server-side
  4712. * sockets that listen for incoming connections or for any socket that needs to specify its local
  4713. * address before communication.
  4714. *
  4715. * @warning If the specified address is already in use by another socket or if the socket type is incompatible
  4716. * with the address, the function will return an error. Ensure that the address is not in use and is
  4717. * valid for the socket type.
  4718. */
  4719. sysret_t sys_bind(int socket, const struct musl_sockaddr *name, socklen_t namelen)
  4720. {
  4721. rt_err_t ret = 0;
  4722. struct sockaddr sa;
  4723. struct sockaddr_un un_addr;
  4724. struct musl_sockaddr kname;
  4725. rt_uint16_t family = 0;
  4726. if (!lwp_user_accessable((void *)name, namelen))
  4727. {
  4728. return -EFAULT;
  4729. }
  4730. lwp_get_from_user(&family, (void *)name, 2);
  4731. if (family == AF_UNIX)
  4732. {
  4733. lwp_get_from_user(&un_addr, (void *)name, sizeof(struct sockaddr_un));
  4734. ret = bind(socket, (struct sockaddr *)&un_addr, namelen);
  4735. }
  4736. else if (family == AF_NETLINK)
  4737. {
  4738. lwp_get_from_user(&sa, (void *)name, namelen);
  4739. ret = bind(socket, &sa, namelen);
  4740. }
  4741. else
  4742. {
  4743. lwp_get_from_user(&kname, (void *)name, namelen);
  4744. sockaddr_tolwip(&kname, &sa);
  4745. ret = bind(socket, &sa, namelen);
  4746. }
  4747. return (ret < 0 ? GET_ERRNO() : ret);
  4748. }
  4749. /**
  4750. * @brief Shuts down part of a full-duplex connection.
  4751. *
  4752. * This system call disables further send or receive operations on a socket. The `how` parameter
  4753. * specifies which part of the connection should be shut down. This operation is typically used
  4754. * when the application no longer needs to send or receive data, but wants to keep the connection open
  4755. * for other purposes (e.g., receiving shutdown acknowledgment).
  4756. *
  4757. * @param[in] socket The socket descriptor to be shut down. This socket must be an open socket that
  4758. * has been created using `sys_socket`.
  4759. * @param[in] how The shutdown behavior:
  4760. * - `SHUT_RD`: Disables further receives on the socket. The application can no longer
  4761. * receive data from this socket.
  4762. * - `SHUT_WR`: Disables further sends on the socket. The application can no longer
  4763. * send data through this socket.
  4764. * - `SHUT_RDWR`: Disables both sends and receives on the socket. The socket is
  4765. * fully shut down for communication.
  4766. *
  4767. * @return sysret_t Returns `0` on success, or a negative error code (e.g., `SYSRET_ERROR`) on failure.
  4768. *
  4769. * @note The `socket` should be open and in a connected state when calling this function. The `how`
  4770. * parameter determines which part of the connection is to be shut down, allowing for finer control
  4771. * over communication termination.
  4772. *
  4773. * @warning Once a socket is shut down with `SHUT_RD`, no further data can be received on it. Similarly,
  4774. * after `SHUT_WR`, no more data can be sent. Calling `sys_shutdown` with incompatible `how` values
  4775. * or on an invalid socket may result in errors.
  4776. */
  4777. sysret_t sys_shutdown(int socket, int how)
  4778. {
  4779. return shutdown(socket, how);
  4780. }
  4781. /**
  4782. * @brief Retrieves the address of the peer connected to a socket.
  4783. *
  4784. * This system call retrieves the address of the peer (remote endpoint) that is connected to the specified
  4785. * socket. The socket must be connected (i.e., for stream-oriented protocols such as TCP). The address
  4786. * of the peer is stored in the `name` structure, and the size of the structure is updated in `namelen`.
  4787. *
  4788. * @param[in] socket The socket descriptor of the connected socket. This socket must be in a connected
  4789. * state (e.g., after a successful `sys_connect` or `sys_accept` call).
  4790. * @param[out] name A pointer to a `musl_sockaddr` structure where the address of the peer will be
  4791. * stored. This structure will be populated with the peer's IP address and port number.
  4792. * @param[in,out] namelen A pointer to a `socklen_t` variable that specifies the size of the `name` structure
  4793. * on input. On output, it will contain the actual size of the address returned in `name`.
  4794. *
  4795. * @return sysret_t Returns `SYSRET_OK` on success, or a negative error code on failure.
  4796. *
  4797. * @note The `socket` must be in a connected state when calling this function. The `name` structure will
  4798. * contain the peer's address information, which can be used for logging, debugging, or further
  4799. * communication.
  4800. *
  4801. * @warning Ensure that the `name` structure is sufficiently large to hold the peer's address information.
  4802. * The `namelen` parameter must be set to the size of the `name` structure before calling this function.
  4803. * Failing to provide a correctly sized `namelen` could result in buffer overflows or undefined behavior.
  4804. */
  4805. sysret_t sys_getpeername(int socket, struct musl_sockaddr *name, socklen_t *namelen)
  4806. {
  4807. int ret = -1;
  4808. struct sockaddr sa;
  4809. struct musl_sockaddr kname;
  4810. socklen_t unamelen;
  4811. socklen_t knamelen;
  4812. if (!lwp_user_accessable(namelen, sizeof(socklen_t)))
  4813. {
  4814. return -EFAULT;
  4815. }
  4816. lwp_get_from_user(&unamelen, namelen, sizeof(socklen_t));
  4817. if (!unamelen)
  4818. {
  4819. return -EINVAL;
  4820. }
  4821. if (!lwp_user_accessable(name, unamelen))
  4822. {
  4823. return -EFAULT;
  4824. }
  4825. knamelen = sizeof(struct sockaddr);
  4826. ret = getpeername(socket, &sa, &knamelen);
  4827. if (ret == 0)
  4828. {
  4829. sockaddr_tomusl(&sa, &kname);
  4830. if (unamelen > sizeof(struct musl_sockaddr))
  4831. {
  4832. unamelen = sizeof(struct musl_sockaddr);
  4833. }
  4834. lwp_put_to_user(name, &kname, unamelen);
  4835. lwp_put_to_user(namelen, &unamelen, sizeof(socklen_t));
  4836. }
  4837. else
  4838. {
  4839. ret = GET_ERRNO();
  4840. }
  4841. return ret;
  4842. }
  4843. /**
  4844. * @brief Retrieves the local address of the socket.
  4845. *
  4846. * This system call retrieves the local address (local endpoint) that is bound to the specified socket.
  4847. * The socket must be created and, if necessary, bound to a local address using `sys_bind`. The address
  4848. * of the local endpoint is stored in the `name` structure, and the size of the structure is updated in `namelen`.
  4849. *
  4850. * @param[in] socket The socket descriptor of the socket. This socket must be created and, if required,
  4851. * bound to a local address.
  4852. * @param[out] name A pointer to a `musl_sockaddr` structure where the local address of the socket will
  4853. * be stored. This structure will be populated with the local IP address and port number.
  4854. * @param[in,out] namelen A pointer to a `socklen_t` variable that specifies the size of the `name` structure
  4855. * on input. On output, it will contain the actual size of the address returned in `name`.
  4856. *
  4857. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  4858. *
  4859. * @note The `socket` must be created and, if needed, bound to a local address using `sys_bind`.
  4860. * The `name` structure will contain the local address of the socket, which can be used for logging,
  4861. * debugging, or further communication.
  4862. *
  4863. * @warning Ensure that the `name` structure is sufficiently large to hold the local address information.
  4864. * The `namelen` parameter must be set to the size of the `name` structure before calling this function.
  4865. * Failing to provide a correctly sized `namelen` could result in buffer overflows or undefined behavior.
  4866. */
  4867. sysret_t sys_getsockname(int socket, struct musl_sockaddr *name, socklen_t *namelen)
  4868. {
  4869. int ret = -1;
  4870. struct sockaddr sa;
  4871. struct musl_sockaddr kname;
  4872. socklen_t unamelen;
  4873. socklen_t knamelen;
  4874. if (!lwp_user_accessable(namelen, sizeof(socklen_t)))
  4875. {
  4876. return -EFAULT;
  4877. }
  4878. lwp_get_from_user(&unamelen, namelen, sizeof(socklen_t));
  4879. if (!unamelen)
  4880. {
  4881. return -EINVAL;
  4882. }
  4883. if (!lwp_user_accessable(name, unamelen))
  4884. {
  4885. return -EFAULT;
  4886. }
  4887. knamelen = sizeof(struct sockaddr);
  4888. ret = getsockname(socket, &sa, &knamelen);
  4889. if (ret == 0)
  4890. {
  4891. sockaddr_tomusl(&sa, &kname);
  4892. if (unamelen > sizeof(struct musl_sockaddr))
  4893. {
  4894. unamelen = sizeof(struct musl_sockaddr);
  4895. }
  4896. lwp_put_to_user(name, &kname, unamelen);
  4897. lwp_put_to_user(namelen, &unamelen, sizeof(socklen_t));
  4898. }
  4899. else
  4900. {
  4901. ret = GET_ERRNO();
  4902. }
  4903. return ret;
  4904. }
  4905. /**
  4906. * @brief Retrieves the value of a socket option.
  4907. *
  4908. * This system call retrieves the current value of a socket option for the specified socket. The socket
  4909. * options allow fine-grained control over various aspects of socket behavior, such as timeouts, buffering,
  4910. * and connection settings. The option value is stored in the `optval` buffer, and the size of the buffer
  4911. * is specified by the `optlen` parameter.
  4912. *
  4913. * @param[in] socket The socket descriptor for which the option value is being retrieved. The socket
  4914. * must be valid and open.
  4915. * @param[in] level The level at which the option is defined. Typically, this is `SOL_SOCKET` for general
  4916. * socket options, or a protocol-specific level (e.g., `IPPROTO_TCP` for TCP options).
  4917. * @param[in] optname The option name. This specifies which socket option to retrieve (e.g., `SO_RCVBUF`
  4918. * for receive buffer size or `SO_RCVBUF` for send buffer size).
  4919. * @param[out] optval A pointer to a buffer where the option value will be stored. The buffer's type depends
  4920. * on the option being retrieved.
  4921. * @param[in,out] optlen A pointer to a `socklen_t` variable that specifies the size of the `optval` buffer on
  4922. * input. On output, it will contain the actual size of the option value retrieved.
  4923. *
  4924. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  4925. *
  4926. * @note The `socket` must be valid and open when calling this function. The `level` and `optname` parameters
  4927. * define the specific option to be retrieved. The `optval` buffer will contain the option value after
  4928. * the function call, and `optlen` will be updated to reflect the size of the retrieved value.
  4929. *
  4930. * @warning Ensure that the `optval` buffer is large enough to hold the value for the specified option.
  4931. * The `optlen` parameter must be set to the correct size of the buffer before calling this function.
  4932. * Failing to provide a correctly sized buffer could result in undefined behavior or buffer overflows.
  4933. */
  4934. sysret_t sys_getsockopt(int socket, int level, int optname, void *optval, socklen_t *optlen)
  4935. {
  4936. int ret = 0;
  4937. socklen_t koptlen = 0;
  4938. void *koptval = RT_NULL;
  4939. if (!lwp_user_accessable((void *)optlen, sizeof(uint32_t)))
  4940. return -EFAULT;
  4941. if (lwp_get_from_user(&koptlen, optlen, sizeof(uint32_t)) != sizeof(uint32_t))
  4942. {
  4943. return -EINVAL;
  4944. }
  4945. if (!lwp_user_accessable((void *)optval, koptlen))
  4946. return -EFAULT;
  4947. koptval = kmem_get(koptlen);
  4948. if (koptval == RT_NULL)
  4949. {
  4950. return -ENOMEM;
  4951. }
  4952. if (lwp_get_from_user(koptval, optval, koptlen) != koptlen)
  4953. {
  4954. kmem_put(koptval);
  4955. return -EINVAL;
  4956. }
  4957. convert_sockopt(&level, &optname);
  4958. ret = getsockopt(socket, level, optname, koptval, &koptlen);
  4959. lwp_put_to_user((void *)optval, koptval, koptlen);
  4960. lwp_put_to_user((void *)optlen, &koptlen, sizeof(uint32_t));
  4961. kmem_put(koptval);
  4962. return (ret < 0 ? GET_ERRNO() : ret);
  4963. }
  4964. /**
  4965. * @brief Sets the value of a socket option.
  4966. *
  4967. * This system call sets a socket option for the specified socket. Socket options control various aspects
  4968. * of socket behavior, such as timeouts, buffer sizes, or connection parameters. The option value is
  4969. * provided in the `optval` buffer, and its length is specified by the `optlen` parameter.
  4970. *
  4971. * @param[in] socket The socket descriptor for which the option is being set. The socket must be valid and open.
  4972. * @param[in] level The level at which the option is defined. This can be `SOL_SOCKET` for general socket options,
  4973. * or a protocol-specific level (e.g., `IPPROTO_TCP` for TCP options).
  4974. * @param[in] optname The option name. This specifies which socket option to set (e.g., `SO_RCVBUF` for receive buffer size).
  4975. * @param[in] optval A pointer to the buffer that contains the option value to set. The format of this buffer depends
  4976. * on the option being set.
  4977. * @param[in] optlen The size of the `optval` buffer. This specifies the length of the data to be used when setting
  4978. * the option value.
  4979. *
  4980. * @return sysret_t Returns `0` on success, or a negative error code on failure:
  4981. *
  4982. * @note The `socket` must be valid and open. The `level` and `optname` parameters define the specific option to be set,
  4983. * and the `optval` buffer should contain the appropriate value for that option. The `optlen` parameter must
  4984. * match the size of the `optval` buffer.
  4985. *
  4986. * @warning Ensure that the `optval` buffer contains valid data for the specified option. The `optlen` parameter must be
  4987. * set to the correct size of the `optval` buffer before calling this function. Failing to provide a correctly
  4988. * sized buffer could result in undefined behavior or errors.
  4989. */
  4990. sysret_t sys_setsockopt(int socket, int level, int optname, const void *optval, socklen_t optlen)
  4991. {
  4992. int ret;
  4993. void *koptval = RT_NULL;
  4994. if (!lwp_user_accessable((void *)optval, optlen))
  4995. return -EFAULT;
  4996. koptval = kmem_get(optlen);
  4997. if (koptval == RT_NULL)
  4998. {
  4999. return -ENOMEM;
  5000. }
  5001. if (lwp_get_from_user(koptval, (void *)optval, optlen) != optlen)
  5002. {
  5003. kmem_put(koptval);
  5004. return -EINVAL;
  5005. }
  5006. convert_sockopt(&level, &optname);
  5007. ret = setsockopt(socket, level, optname, koptval, optlen);
  5008. kmem_put(koptval);
  5009. return (ret < 0 ? GET_ERRNO() : ret);
  5010. }
  5011. /**
  5012. * @brief Establishes a connection to a remote socket.
  5013. *
  5014. * This system call attempts to establish a connection to a remote socket specified by the `name` parameter.
  5015. * It is typically used for client-side socket operations to connect to a server. The connection is established
  5016. * by using the specified socket descriptor and the address of the remote server.
  5017. *
  5018. * @param[in] socket The socket descriptor for the connection attempt. The socket must be valid and in a
  5019. * `SOCK_STREAM` or `SOCK_DGRAM` state, depending on the protocol.
  5020. * @param[in] name A pointer to a `sockaddr` structure containing the address of the remote host. This address
  5021. * must include the correct IP address and port number for the connection.
  5022. * @param[in] namelen The size of the `sockaddr` structure pointed to by `name`. This should match the size
  5023. * of the address structure (e.g., `sizeof(struct sockaddr_in)` for IPv4).
  5024. *
  5025. * @return sysret_t Returns `0` on success, or a negative error code on failure:
  5026. *
  5027. * @note This function may block if the connection is being established, depending on the socket's configuration.
  5028. * For non-blocking sockets, it will return immediately, even if the connection has not been established.
  5029. *
  5030. * @warning The `socket` must be of a valid type (e.g., `SOCK_STREAM` for TCP or `SOCK_DGRAM` for UDP).
  5031. * The `name` parameter must point to a valid `sockaddr` structure that contains a correctly formatted address.
  5032. */
  5033. sysret_t sys_connect(int socket, const struct musl_sockaddr *name, socklen_t namelen)
  5034. {
  5035. int ret = 0;
  5036. rt_uint16_t family = 0;
  5037. struct sockaddr sa;
  5038. struct musl_sockaddr kname;
  5039. struct sockaddr_un addr_un;
  5040. if (!lwp_user_accessable((void *)name, namelen))
  5041. {
  5042. return -EFAULT;
  5043. }
  5044. lwp_get_from_user(&family, (void *)name, 2);
  5045. if (family == AF_UNIX)
  5046. {
  5047. if (!lwp_user_accessable((void *)name, sizeof(struct sockaddr_un)))
  5048. {
  5049. return -EFAULT;
  5050. }
  5051. lwp_get_from_user(&addr_un, (void *)name, sizeof(struct sockaddr_un));
  5052. ret = connect(socket, (struct sockaddr *)(&addr_un), namelen);
  5053. }
  5054. else
  5055. {
  5056. lwp_get_from_user(&kname, (void *)name, namelen);
  5057. sockaddr_tolwip(&kname, &sa);
  5058. ret = connect(socket, &sa, namelen);
  5059. }
  5060. return ret;
  5061. }
  5062. /**
  5063. * @brief Prepares a socket to accept incoming connection requests.
  5064. *
  5065. * This system call marks a socket as a passive socket, indicating that it will be used to accept
  5066. * incoming connection requests. It is typically used on server-side sockets after binding a
  5067. * local address and port using `sys_bind()`.
  5068. *
  5069. * @param[in] socket The socket descriptor to be set up for listening. The socket must be valid
  5070. * and of type `SOCK_STREAM` (for TCP connections).
  5071. * @param[in] backlog The maximum number of pending connections that can be queued. This value
  5072. * is system-dependent and may be limited to a lower maximum.
  5073. *
  5074. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5075. *
  5076. * @note Before calling this function, the socket must be bound to a local address and port using
  5077. * `sys_bind()`. Only sockets of type `SOCK_STREAM` can be used for listening. The actual
  5078. * maximum queue length may be less than the specified `backlog` value, depending on system limits.
  5079. *
  5080. * @warning Ensure that the socket is properly initialized, bound, and of the correct type before calling this function.
  5081. * Failure to do so will result in undefined behavior or errors.
  5082. */
  5083. sysret_t sys_listen(int socket, int backlog)
  5084. {
  5085. return listen(socket, backlog);
  5086. }
  5087. #define MUSLC_MSG_OOB 0x0001
  5088. #define MUSLC_MSG_PEEK 0x0002
  5089. #define MUSLC_MSG_DONTWAIT 0x0040
  5090. #define MUSLC_MSG_WAITALL 0x0100
  5091. #define MUSLC_MSG_MORE 0x8000
  5092. static int netflags_muslc_2_lwip(int flags)
  5093. {
  5094. int flgs = 0;
  5095. if (flags & MUSLC_MSG_PEEK)
  5096. {
  5097. flgs |= MSG_PEEK;
  5098. }
  5099. if (flags & MUSLC_MSG_WAITALL)
  5100. {
  5101. flgs |= MSG_WAITALL;
  5102. }
  5103. if (flags & MUSLC_MSG_OOB)
  5104. {
  5105. flgs |= MSG_OOB;
  5106. }
  5107. if (flags & MUSLC_MSG_DONTWAIT)
  5108. {
  5109. flgs |= MSG_DONTWAIT;
  5110. }
  5111. if (flags & MUSLC_MSG_MORE)
  5112. {
  5113. flgs |= MSG_MORE;
  5114. }
  5115. if (flags & MSG_ERRQUEUE)
  5116. {
  5117. flgs |= MSG_ERRQUEUE;
  5118. }
  5119. return flgs;
  5120. }
  5121. #ifdef ARCH_MM_MMU
  5122. static int copy_msghdr_from_user(struct msghdr *kmsg, struct msghdr *umsg,
  5123. struct iovec **out_iov, void **out_msg_control)
  5124. {
  5125. size_t iovs_size;
  5126. struct iovec *uiov, *kiov;
  5127. size_t iovs_buffer_size = 0;
  5128. void *iovs_buffer;
  5129. if (!lwp_user_accessable(umsg, sizeof(*umsg)))
  5130. {
  5131. return -EFAULT;
  5132. }
  5133. lwp_get_from_user(kmsg, umsg, sizeof(*kmsg));
  5134. iovs_size = sizeof(*kmsg->msg_iov) * kmsg->msg_iovlen;
  5135. if (!lwp_user_accessable(kmsg->msg_iov, iovs_size))
  5136. {
  5137. return -EFAULT;
  5138. }
  5139. /* user and kernel */
  5140. kiov = kmem_get(iovs_size * 2);
  5141. if (!kiov)
  5142. {
  5143. return -ENOMEM;
  5144. }
  5145. uiov = (void *)kiov + iovs_size;
  5146. lwp_get_from_user(uiov, kmsg->msg_iov, iovs_size);
  5147. if (out_iov)
  5148. {
  5149. *out_iov = uiov;
  5150. }
  5151. kmsg->msg_iov = kiov;
  5152. for (int i = 0; i < kmsg->msg_iovlen; ++i)
  5153. {
  5154. /*
  5155. * We MUST check we can copy data to user after socket done in uiov
  5156. * otherwise we will be lost the messages from the network!
  5157. */
  5158. if (!lwp_user_accessable(uiov->iov_base, uiov->iov_len))
  5159. {
  5160. kmem_put(kmsg->msg_iov);
  5161. return -EPERM;
  5162. }
  5163. iovs_buffer_size += uiov->iov_len;
  5164. kiov->iov_len = uiov->iov_len;
  5165. ++kiov;
  5166. ++uiov;
  5167. }
  5168. /* msg_iov and msg_control */
  5169. iovs_buffer = kmem_get(iovs_buffer_size + kmsg->msg_controllen);
  5170. if (!iovs_buffer)
  5171. {
  5172. kmem_put(kmsg->msg_iov);
  5173. return -ENOMEM;
  5174. }
  5175. kiov = kmsg->msg_iov;
  5176. for (int i = 0; i < kmsg->msg_iovlen; ++i)
  5177. {
  5178. kiov->iov_base = iovs_buffer;
  5179. iovs_buffer += kiov->iov_len;
  5180. ++kiov;
  5181. }
  5182. *out_msg_control = kmsg->msg_control;
  5183. /* msg_control is the end of the iovs_buffer */
  5184. kmsg->msg_control = iovs_buffer;
  5185. return 0;
  5186. }
  5187. #endif /* ARCH_MM_MMU */
  5188. /**
  5189. * @brief Receives a message from a socket using a message header structure.
  5190. *
  5191. * This system call is used to receive data and associated metadata from a socket.
  5192. * It supports both stream-oriented and message-oriented sockets and allows control
  5193. * over the behavior of the receiving operation via the `flags` parameter.
  5194. *
  5195. * @param[in] socket The socket descriptor from which the message will be received.
  5196. * The socket must be in a valid and connected state for stream-oriented
  5197. * sockets or bound for message-oriented sockets.
  5198. * @param[out] msg A pointer to an `msghdr` structure that specifies message buffers and
  5199. * will receive the incoming data. The structure also stores ancillary
  5200. * data for advanced socket operations.
  5201. * @param[in] flags Modifiers that control the behavior of the receive operation. Common
  5202. * flags include:
  5203. * - `MSG_PEEK`: Peek at the incoming data without removing it from the queue.
  5204. * - `MSG_WAITALL`: Wait for the full request to be satisfied before returning.
  5205. * - `MSG_DONTWAIT`: Perform a non-blocking receive operation.
  5206. *
  5207. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5208. *
  5209. * @note The `msghdr` structure should be initialized properly, including setting up buffers for
  5210. * receiving the data. The function can return fewer bytes than expected depending on socket
  5211. * type and flags. For stream-oriented sockets, partial data may be received.
  5212. *
  5213. * @warning The `socket` must be valid and in an appropriate state. If the socket is non-blocking
  5214. * and no data is available, the function will return immediately.
  5215. *
  5216. * @see sys_sendmsg()
  5217. */
  5218. sysret_t sys_recvmsg(int socket, struct msghdr *msg, int flags)
  5219. {
  5220. int flgs, ret = -1;
  5221. struct msghdr kmsg;
  5222. #ifdef ARCH_MM_MMU
  5223. void *msg_control;
  5224. struct iovec *uiov, *kiov;
  5225. #endif
  5226. if (!msg)
  5227. {
  5228. return -EPERM;
  5229. }
  5230. flgs = netflags_muslc_2_lwip(flags);
  5231. #ifdef ARCH_MM_MMU
  5232. ret = copy_msghdr_from_user(&kmsg, msg, &uiov, &msg_control);
  5233. if (!ret)
  5234. {
  5235. ret = recvmsg(socket, &kmsg, flgs);
  5236. if (ret < 0)
  5237. {
  5238. goto _free_res;
  5239. }
  5240. kiov = kmsg.msg_iov;
  5241. for (int i = 0; i < kmsg.msg_iovlen; ++i)
  5242. {
  5243. lwp_put_to_user(uiov->iov_base, kiov->iov_base, kiov->iov_len);
  5244. ++kiov;
  5245. ++uiov;
  5246. }
  5247. lwp_put_to_user(msg_control, kmsg.msg_control, kmsg.msg_controllen);
  5248. lwp_put_to_user(&msg->msg_flags, &kmsg.msg_flags, sizeof(kmsg.msg_flags));
  5249. _free_res:
  5250. kmem_put(kmsg.msg_iov->iov_base);
  5251. kmem_put(kmsg.msg_iov);
  5252. }
  5253. #else
  5254. rt_memcpy(&kmsg, msg, sizeof(kmsg));
  5255. ret = recvmsg(socket, &kmsg, flgs);
  5256. if (!ret)
  5257. {
  5258. msg->msg_flags = kmsg.msg_flags;
  5259. }
  5260. #endif /* ARCH_MM_MMU */
  5261. return (ret < 0 ? GET_ERRNO() : ret);
  5262. }
  5263. /**
  5264. * @brief Receives data from a socket, optionally capturing the source address.
  5265. *
  5266. * This system call is used to receive data from a socket. For connectionless sockets, it also
  5267. * retrieves the address of the sender. It supports both blocking and non-blocking operations
  5268. * depending on the socket configuration and the specified flags.
  5269. *
  5270. * @param[in] socket The socket descriptor from which the data will be received. The socket
  5271. * must be valid and appropriately configured (e.g., connected or bound).
  5272. * @param[out] mem A pointer to the buffer where the received data will be stored.
  5273. * @param[in] len The maximum number of bytes to receive. This defines the size of the `mem` buffer.
  5274. * @param[in] flags Modifiers that control the behavior of the receive operation. Common
  5275. * flags include:
  5276. * - `MSG_PEEK`: Peek at the incoming data without removing it from the queue.
  5277. * - `MSG_WAITALL`: Wait for the full request to be satisfied before returning.
  5278. * - `MSG_DONTWAIT`: Perform a non-blocking receive operation.
  5279. * @param[out] from A pointer to a `musl_sockaddr` structure that will hold the address of
  5280. * the sender. This parameter can be `NULL` if the sender's address is not needed.
  5281. * @param[in,out] fromlen A pointer to a `socklen_t` variable indicating the size of the `from` buffer.
  5282. * On return, it will be updated with the actual size of the sender's address.
  5283. * This parameter is ignored if `from` is `NULL`.
  5284. *
  5285. * @return sysret_t Returns `0` on success, or a negative error code on failure:
  5286. *
  5287. * @note For stream-oriented sockets, this function behaves like `sys_recv()`, and the `from` and
  5288. * `fromlen` parameters are ignored. For datagram-oriented sockets, the function fills `from`
  5289. * with the address of the sender.
  5290. *
  5291. * @warning The `socket` must be valid and configured for receiving data. If the `mem` buffer is
  5292. * smaller than the received data, excess data may be discarded. In non-blocking mode,
  5293. * if no data is available, the function returns immediately.
  5294. *
  5295. * @see sys_sendto(), sys_recv()
  5296. */
  5297. sysret_t sys_recvfrom(int socket, void *mem, size_t len, int flags,
  5298. struct musl_sockaddr *from, socklen_t *fromlen)
  5299. {
  5300. int flgs = 0;
  5301. #ifdef ARCH_MM_MMU
  5302. int ret = -1;
  5303. void *kmem = RT_NULL;
  5304. #endif
  5305. flgs = netflags_muslc_2_lwip(flags);
  5306. #ifdef ARCH_MM_MMU
  5307. if (!len)
  5308. {
  5309. return -EINVAL;
  5310. }
  5311. if (!lwp_user_accessable((void *)mem, len))
  5312. {
  5313. return -EFAULT;
  5314. }
  5315. kmem = kmem_get(len);
  5316. if (!kmem)
  5317. {
  5318. return -ENOMEM;
  5319. }
  5320. if (flags == 0x2)
  5321. {
  5322. flags = 0x1;
  5323. }
  5324. if (from)
  5325. {
  5326. struct sockaddr sa;
  5327. ret = recvfrom(socket, kmem, len, flgs, &sa, fromlen);
  5328. sockaddr_tomusl(&sa, from);
  5329. }
  5330. else
  5331. {
  5332. ret = recvfrom(socket, kmem, len, flgs, NULL, NULL);
  5333. }
  5334. if (ret > 0)
  5335. {
  5336. lwp_put_to_user(mem, kmem, len);
  5337. }
  5338. if (ret < 0)
  5339. {
  5340. ret = GET_ERRNO();
  5341. }
  5342. kmem_put(kmem);
  5343. return ret;
  5344. #else
  5345. int ret = -1;
  5346. if (from)
  5347. {
  5348. struct sockaddr sa = { 0 };
  5349. ret = recvfrom(socket, mem, len, flgs, &sa, fromlen);
  5350. sockaddr_tomusl(&sa, from);
  5351. }
  5352. else
  5353. {
  5354. ret = recvfrom(socket, mem, len, flags, NULL, NULL);
  5355. }
  5356. return (ret < 0 ? GET_ERRNO() : ret);
  5357. #endif
  5358. }
  5359. /**
  5360. * @brief Receives data from a connected socket.
  5361. *
  5362. * This system call is used to receive data from a socket that is in a connected state.
  5363. * It supports various flags to modify the behavior of the receive operation.
  5364. *
  5365. * @param[in] socket The socket descriptor from which the data will be received.
  5366. * The socket must be in a valid and connected state.
  5367. * @param[out] mem A pointer to the buffer where the received data will be stored.
  5368. * @param[in] len The maximum number of bytes to receive. This defines the size of the `mem` buffer.
  5369. * @param[in] flags Modifiers that control the behavior of the receive operation. Common flags include:
  5370. * - `MSG_PEEK`: Peek at the incoming data without removing it from the queue.
  5371. * - `MSG_WAITALL`: Wait for the full request to be satisfied before returning.
  5372. * - `MSG_DONTWAIT`: Perform a non-blocking receive operation.
  5373. *
  5374. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5375. *
  5376. * @note The function is designed for connected sockets, such as stream-oriented sockets (e.g., TCP).
  5377. * For datagram-oriented sockets (e.g., UDP), use `sys_recvfrom()` to capture the sender's address if needed.
  5378. *
  5379. * @warning The `socket` must be valid and in a connected state. If the `mem` buffer is smaller than the
  5380. * received data, excess data may be discarded. For non-blocking sockets, the function returns
  5381. * immediately if no data is available.
  5382. *
  5383. * @see sys_send(), sys_recvfrom()
  5384. */
  5385. sysret_t sys_recv(int socket, void *mem, size_t len, int flags)
  5386. {
  5387. int flgs = 0;
  5388. int ret;
  5389. void *kmem = RT_NULL;
  5390. if (!lwp_user_accessable((void *)mem, len))
  5391. return -EFAULT;
  5392. kmem = kmem_get(sizeof(*kmem));
  5393. if (kmem == RT_NULL)
  5394. {
  5395. return -ENOMEM;
  5396. }
  5397. flgs = netflags_muslc_2_lwip(flags);
  5398. ret = recvfrom(socket, kmem, len, flgs, NULL, NULL);
  5399. lwp_put_to_user((void *)mem, kmem, len);
  5400. kmem_put(kmem);
  5401. return (ret < 0 ? GET_ERRNO() : ret);
  5402. }
  5403. /**
  5404. * @brief Sends a message from a socket using scatter-gather I/O.
  5405. *
  5406. * This system call sends data from multiple buffers specified in the `msghdr` structure. It is particularly
  5407. * useful for advanced socket operations requiring ancillary data or scatter-gather I/O.
  5408. *
  5409. * @param[in] socket The socket descriptor through which the data will be sent. The socket must be
  5410. * valid and, for connection-oriented sockets, in a connected state.
  5411. * @param[in] msg A pointer to a `msghdr` structure that specifies the message to be sent. This structure includes:
  5412. * - `msg_name`: Optional address of the target (used for connectionless sockets like UDP).
  5413. * - `msg_namelen`: Length of the address in `msg_name`.
  5414. * - `msg_iov`: An array of `iovec` structures pointing to the data buffers.
  5415. * - `msg_iovlen`: The number of elements in the `msg_iov` array.
  5416. * - `msg_control`: Optional ancillary data (e.g., file descriptors).
  5417. * - `msg_controllen`: Length of the ancillary data.
  5418. * - `msg_flags`: Flags for the message (e.g., end-of-record markers).
  5419. * @param[in] flags Flags that modify the behavior of the send operation. Common flags include:
  5420. * - `MSG_DONTWAIT`: Perform a non-blocking send operation.
  5421. * - `MSG_EOR`: Indicates the end of a record.
  5422. * - `MSG_NOSIGNAL`: Prevent the function from raising `SIGPIPE` on errors.
  5423. *
  5424. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5425. *
  5426. * @note This function is versatile and supports both connection-oriented (e.g., TCP) and
  5427. * connectionless (e.g., UDP) sockets. For simpler use cases, consider using `sys_send()` or `sys_sendto()`.
  5428. *
  5429. * @warning The `socket` must be configured correctly for the intended communication. For non-blocking sockets,
  5430. * the function may return immediately if the send buffer is full. Ancillary data in `msg_control`
  5431. * must be formatted correctly to avoid undefined behavior.
  5432. *
  5433. * @see sys_send(), sys_sendto(), sys_recvmsg()
  5434. */
  5435. sysret_t sys_sendmsg(int socket, const struct msghdr *msg, int flags)
  5436. {
  5437. int flgs, ret = -1;
  5438. struct msghdr kmsg;
  5439. #ifdef ARCH_MM_MMU
  5440. void *msg_control;
  5441. struct iovec *uiov, *kiov;
  5442. #endif
  5443. if (!msg)
  5444. {
  5445. return -EPERM;
  5446. }
  5447. flgs = netflags_muslc_2_lwip(flags);
  5448. #ifdef ARCH_MM_MMU
  5449. ret = copy_msghdr_from_user(&kmsg, (struct msghdr *)msg, &uiov, &msg_control);
  5450. if (!ret)
  5451. {
  5452. kiov = kmsg.msg_iov;
  5453. for (int i = 0; i < kmsg.msg_iovlen; ++i)
  5454. {
  5455. lwp_get_from_user(kiov->iov_base, uiov->iov_base, kiov->iov_len);
  5456. ++kiov;
  5457. ++uiov;
  5458. }
  5459. lwp_get_from_user(kmsg.msg_control, msg_control, kmsg.msg_controllen);
  5460. ret = sendmsg(socket, &kmsg, flgs);
  5461. kmem_put(kmsg.msg_iov->iov_base);
  5462. kmem_put(kmsg.msg_iov);
  5463. }
  5464. #else
  5465. rt_memcpy(&kmsg, msg, sizeof(kmsg));
  5466. ret = sendmsg(socket, &kmsg, flgs);
  5467. if (!ret)
  5468. {
  5469. msg->msg_flags = kmsg.msg_flags;
  5470. }
  5471. #endif /* ARCH_MM_MMU */
  5472. return (ret < 0 ? GET_ERRNO() : ret);
  5473. }
  5474. /**
  5475. * @brief Sends data to a specific address using a socket.
  5476. *
  5477. * This system call is used to send data from a socket to a specified address. It is commonly
  5478. * used with connectionless sockets (e.g., UDP) but can also be used with connection-oriented
  5479. * sockets if the destination address needs to be overridden.
  5480. *
  5481. * @param[in] socket The socket descriptor used for sending data. It must be valid and
  5482. * properly configured for communication.
  5483. * @param[in] dataptr A pointer to the buffer containing the data to be sent.
  5484. * @param[in] size The size, in bytes, of the data to be sent.
  5485. * @param[in] flags Flags that modify the behavior of the send operation. Common flags include:
  5486. * - `MSG_DONTWAIT`: Perform a non-blocking send operation.
  5487. * - `MSG_NOSIGNAL`: Prevent the function from raising `SIGPIPE` on errors.
  5488. * @param[in] to A pointer to a `musl_sockaddr` structure that specifies the destination address.
  5489. * This parameter can be `NULL` if the socket is connection-oriented.
  5490. * @param[in] tolen The length of the address structure pointed to by `to`.
  5491. *
  5492. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5493. *
  5494. * @note For connectionless sockets (e.g., UDP), `to` and `tolen` must specify a valid destination address.
  5495. * For connection-oriented sockets (e.g., TCP), these parameters can be ignored if the connection
  5496. * is already established.
  5497. *
  5498. * @warning Ensure that the buffer size (`size`) matches the expected size for the data protocol in use.
  5499. * For non-blocking sockets, this function may return immediately if the send buffer is full.
  5500. *
  5501. * @see sys_send(), sys_sendmsg(), sys_recvfrom()
  5502. */
  5503. sysret_t sys_sendto(int socket, const void *dataptr, size_t size, int flags,
  5504. const struct musl_sockaddr *to, socklen_t tolen)
  5505. {
  5506. int flgs = 0;
  5507. #ifdef ARCH_MM_MMU
  5508. int ret = -1;
  5509. void *kmem = RT_NULL;
  5510. #endif
  5511. flgs = netflags_muslc_2_lwip(flags);
  5512. #ifdef ARCH_MM_MMU
  5513. if (!size)
  5514. {
  5515. return -EINVAL;
  5516. }
  5517. if (!lwp_user_accessable((void *)dataptr, size))
  5518. {
  5519. return -EFAULT;
  5520. }
  5521. kmem = kmem_get(size);
  5522. if (!kmem)
  5523. {
  5524. return -ENOMEM;
  5525. }
  5526. lwp_get_from_user(kmem, (void *)dataptr, size);
  5527. if (to)
  5528. {
  5529. struct sockaddr sa;
  5530. sockaddr_tolwip(to, &sa);
  5531. ret = sendto(socket, kmem, size, flgs, &sa, tolen);
  5532. }
  5533. else
  5534. {
  5535. ret = sendto(socket, kmem, size, flgs, NULL, tolen);
  5536. }
  5537. if (ret < 0)
  5538. {
  5539. ret = GET_ERRNO();
  5540. }
  5541. kmem_put(kmem);
  5542. return ret;
  5543. #else
  5544. int ret;
  5545. if (to)
  5546. {
  5547. struct sockaddr sa;
  5548. sockaddr_tolwip(to, &sa);
  5549. ret = sendto(socket, dataptr, size, flgs, &sa, tolen);
  5550. }
  5551. else
  5552. {
  5553. ret = sendto(socket, dataptr, size, flgs, NULL, tolen);
  5554. }
  5555. return (ret < 0 ? GET_ERRNO() : ret);
  5556. #endif
  5557. }
  5558. /**
  5559. * @brief Sends data over a connected socket.
  5560. *
  5561. * This system call sends data from the specified buffer through a connected socket. It is typically
  5562. * used with connection-oriented sockets (e.g., TCP) but can also work with connectionless sockets
  5563. * (e.g., UDP) if a connection is established using `sys_connect()`.
  5564. *
  5565. * @param[in] socket The socket descriptor used for sending data. It must be a valid socket
  5566. * and, for connection-oriented sockets, in a connected state.
  5567. * @param[in] dataptr A pointer to the buffer containing the data to be sent.
  5568. * @param[in] size The size, in bytes, of the data to be sent.
  5569. * @param[in] flags Flags that modify the behavior of the send operation. Common flags include:
  5570. * - `MSG_DONTWAIT`: Perform a non-blocking send operation.
  5571. * - `MSG_NOSIGNAL`: Prevent the function from raising `SIGPIPE` on errors.
  5572. *
  5573. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5574. *
  5575. * @note For connection-oriented sockets, the socket must already be connected using `sys_connect()` or
  5576. * `sys_accept()`. For connectionless sockets, use `sys_sendto()` to specify the destination address.
  5577. *
  5578. * @warning If the socket is in non-blocking mode and the send buffer is full, this function may return
  5579. * immediately with an error. Ensure that the size of the data (`size`) matches the protocol's
  5580. * expectations to avoid truncation or overflow issues.
  5581. *
  5582. * @see sys_sendto(), sys_sendmsg(), sys_recv()
  5583. */
  5584. sysret_t sys_send(int socket, const void *dataptr, size_t size, int flags)
  5585. {
  5586. int flgs = 0;
  5587. int ret = 0;
  5588. void *kdataptr = RT_NULL;
  5589. if (!lwp_user_accessable((void *)dataptr, size))
  5590. return -EFAULT;
  5591. kdataptr = kmem_get(size);
  5592. if (kdataptr == RT_NULL)
  5593. {
  5594. return -ENOMEM;
  5595. }
  5596. if (lwp_get_from_user(kdataptr, (void *)dataptr, size) != size)
  5597. {
  5598. kmem_put(kdataptr);
  5599. return -EINVAL;
  5600. }
  5601. flgs = netflags_muslc_2_lwip(flags);
  5602. ret = sendto(socket, kdataptr, size, flgs, NULL, 0);
  5603. kmem_put(kdataptr);
  5604. return (ret < 0 ? GET_ERRNO() : ret);
  5605. }
  5606. /**
  5607. * @brief Creates a new socket for communication.
  5608. *
  5609. * This system call creates a new socket endpoint for communication and returns a file descriptor
  5610. * that can be used for subsequent socket operations, such as binding, connecting, or data transfer.
  5611. *
  5612. * @param[in] domain Specifies the protocol family to be used for the socket. Common values include:
  5613. * - `AF_INET`: IPv4 Internet protocols.
  5614. * - `AF_INET6`: IPv6 Internet protocols.
  5615. * - `AF_UNIX`: Local communication using UNIX domain sockets.
  5616. * @param[in] type Specifies the type of socket to be created. Common values include:
  5617. * - `SOCK_STREAM`: Provides sequenced, reliable, two-way, connection-based byte streams.
  5618. * - `SOCK_DGRAM`: Supports datagrams (connectionless, unreliable messages of fixed maximum length).
  5619. * - `SOCK_RAW`: Provides raw network protocol access.
  5620. * @param[in] protocol Specifies the specific protocol to be used. Typically set to `0` to use the default
  5621. * protocol for the specified domain and type.
  5622. *
  5623. * @return sysret_t Returns the socket file descriptor on success, or a negative error code on failure.
  5624. *
  5625. * @note The returned socket descriptor must be closed using `sys_close()` to release system resources.
  5626. *
  5627. * @warning Ensure the combination of `domain`, `type`, and `protocol` is valid. Invalid combinations
  5628. * may result in errors. For example, specifying `AF_INET` with `SOCK_DGRAM` is valid for UDP,
  5629. * but with `SOCK_STREAM` it is used for TCP.
  5630. *
  5631. * @see sys_bind(), sys_connect(), sys_accept(), sys_close()
  5632. */
  5633. sysret_t sys_socket(int domain, int type, int protocol)
  5634. {
  5635. int fd = -1;
  5636. int nonblock = 0;
  5637. /* not support SOCK_CLOEXEC type */
  5638. if (type & SOCK_CLOEXEC)
  5639. {
  5640. type &= ~SOCK_CLOEXEC;
  5641. }
  5642. if (type & SOCK_NONBLOCK)
  5643. {
  5644. nonblock = 1;
  5645. type &= ~SOCK_NONBLOCK;
  5646. }
  5647. fd = socket(domain, type, protocol);
  5648. if (fd < 0)
  5649. {
  5650. goto out;
  5651. }
  5652. if (nonblock)
  5653. {
  5654. fcntl(fd, F_SETFL, O_NONBLOCK);
  5655. }
  5656. out:
  5657. return (fd < 0 ? GET_ERRNO() : fd);
  5658. }
  5659. /**
  5660. * @brief Creates a pair of connected sockets.
  5661. *
  5662. * This system call creates two connected sockets that can be used for bidirectional communication
  5663. * between processes or threads. The sockets are returned as file descriptors in the `fd` array.
  5664. *
  5665. * @param[in] domain Specifies the protocol family to be used for the sockets. Common values include:
  5666. * - `AF_UNIX`: Local communication using UNIX domain sockets.
  5667. * @param[in] type Specifies the type of socket to be created. Common values include:
  5668. * - `SOCK_STREAM`: Provides sequenced, reliable, two-way, connection-based byte streams.
  5669. * - `SOCK_DGRAM`: Supports datagrams (connectionless, unreliable messages of fixed maximum length).
  5670. * @param[in] protocol Specifies the specific protocol to be used. Typically set to `0` to use the default
  5671. * protocol for the specified domain and type.
  5672. * @param[out] fd An array of two integers where the connected socket descriptors will be stored.
  5673. * After a successful call:
  5674. * - `fd[0]`: The first socket descriptor.
  5675. * - `fd[1]`: The second socket descriptor.
  5676. *
  5677. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5678. *
  5679. * @note The sockets in the pair are connected and can be used for inter-process communication
  5680. * (IPC) or between threads in the same process.
  5681. *
  5682. * @warning Ensure the `domain`, `type`, and `protocol` combination is valid. This function is typically
  5683. * supported only for `AF_UNIX` domain.
  5684. *
  5685. * @see sys_socket(), sys_close()
  5686. */
  5687. sysret_t sys_socketpair(int domain, int type, int protocol, int fd[2])
  5688. {
  5689. #ifdef RT_USING_SAL
  5690. int ret = 0;
  5691. int k_fd[2];
  5692. if (!lwp_user_accessable((void *)fd, sizeof(int[2])))
  5693. {
  5694. return -EFAULT;
  5695. }
  5696. ret = socketpair(domain, type, protocol, k_fd);
  5697. if (ret == 0)
  5698. {
  5699. lwp_put_to_user(fd, k_fd, sizeof(int[2]));
  5700. }
  5701. return ret;
  5702. #else
  5703. return -ELIBACC;
  5704. #endif
  5705. }
  5706. /**
  5707. * @brief Closes an open socket.
  5708. *
  5709. * This system call is used to close a previously opened socket. Once the socket is closed, it is no longer
  5710. * valid for any further operations, such as sending, receiving, or other socket-related functions.
  5711. *
  5712. * @param[in] socket The socket descriptor to be closed. This descriptor must be a valid socket that was
  5713. * previously created with `sys_socket()` or related functions.
  5714. *
  5715. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5716. *
  5717. * @note Once a socket is closed, any attempts to use the socket for communication will result in an error.
  5718. * The system will release any resources associated with the socket.
  5719. *
  5720. * @warning Make sure that no data is being transferred or pending on the socket before closing it.
  5721. * Closing an active socket might lead to data loss.
  5722. *
  5723. * @see sys_socket(), sys_shutdown()
  5724. */
  5725. sysret_t sys_closesocket(int socket)
  5726. {
  5727. return closesocket(socket);
  5728. }
  5729. #endif
  5730. /**
  5731. * @brief Finds a thread by its name.
  5732. *
  5733. * This system call is used to search for a thread based on its name. It returns a reference to the
  5734. * thread if found, otherwise it returns `RT_NULL`. The name comparison is case-sensitive.
  5735. *
  5736. * @param[in] name The name of the thread to search for. This should be a valid string that
  5737. * uniquely identifies the thread within the system.
  5738. *
  5739. * @return rt_thread_t The thread object corresponding to the given name, or `RT_NULL` if no
  5740. * matching thread was found.
  5741. *
  5742. * @note The thread name is typically assigned when the thread is created, and it can be used to
  5743. * identify threads in the system.
  5744. *
  5745. * @warning Ensure that the `name` string is correctly set and unique within the system to avoid
  5746. * unexpected behavior.
  5747. *
  5748. * @see sys_thread_create(), sys_thread_delete()
  5749. */
  5750. rt_thread_t sys_thread_find(char *name)
  5751. {
  5752. int len = 0;
  5753. char *kname = RT_NULL;
  5754. rt_thread_t thread;
  5755. len = lwp_user_strlen(name);
  5756. if (len <= 0)
  5757. {
  5758. return RT_NULL;
  5759. }
  5760. kname = (char *)kmem_get(len + 1);
  5761. if (!kname)
  5762. {
  5763. return RT_NULL;
  5764. }
  5765. if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
  5766. {
  5767. kmem_put(kname);
  5768. return RT_NULL;
  5769. }
  5770. thread = rt_thread_find(name);
  5771. kmem_put(kname);
  5772. return thread;
  5773. }
  5774. /**
  5775. * @brief Gets the current system tick count.
  5776. *
  5777. * This system call returns the current value of the system tick counter, which is typically incremented
  5778. * at a fixed interval (e.g., every millisecond or microsecond). The tick count can be used for timing
  5779. * purposes, such as measuring the elapsed time or triggering time-based events.
  5780. *
  5781. * @return rt_tick_t The current value of the system tick counter.
  5782. *
  5783. * @note The system tick counter typically wraps around after reaching its maximum value, so the
  5784. * returned tick value may reset after a certain period of time, depending on the configuration
  5785. * of the system tick timer.
  5786. *
  5787. * @warning Be cautious when using the tick value for time-based calculations, as the counter may
  5788. * overflow and wrap around. Ensure that the code handling the tick count properly accounts
  5789. * for potential overflow.
  5790. *
  5791. * @see sys_tick_init(), sys_tick_delay()
  5792. */
  5793. rt_tick_t sys_tick_get(void)
  5794. {
  5795. return rt_tick_get();
  5796. }
  5797. /**
  5798. * @brief Delays the current thread for a specified number of milliseconds.
  5799. *
  5800. * This system call puts the calling thread to sleep for a given number of milliseconds. It is a blocking
  5801. * call, meaning the thread will not execute any further instructions until the specified delay has
  5802. * passed. The delay is achieved by the system's timer mechanism.
  5803. *
  5804. * @param[in] ms The number of milliseconds to delay. The value must be a positive integer.
  5805. *
  5806. * @return sysret_t Returns `0` on success, or a negative error code on failure.
  5807. *
  5808. * @note This function is useful for introducing a fixed delay in time-sensitive applications or when
  5809. * the thread needs to be paused before continuing execution.
  5810. *
  5811. * @warning Be cautious when using this function in real-time or time-critical applications, as
  5812. * excessive delays may affect overall system performance or responsiveness.
  5813. *
  5814. * @see sys_thread_delay(), sys_thread_sleep()
  5815. */
  5816. sysret_t sys_thread_mdelay(rt_int32_t ms)
  5817. {
  5818. return rt_thread_mdelay(ms);
  5819. }
  5820. struct k_sigaction
  5821. {
  5822. void (*handler)(int);
  5823. unsigned long flags;
  5824. void (*restorer)(void);
  5825. unsigned mask[2];
  5826. };
  5827. /**
  5828. * @brief Changes the action taken by the system on receiving a signal.
  5829. *
  5830. * This system call allows a process to specify how signals should be handled. It allows you to set a
  5831. * new action for a specific signal, retrieve the old action, and define the signal mask that should
  5832. * be applied during the execution of the signal handler.
  5833. *
  5834. * @param[in] sig The signal number for which the action is to be set or retrieved.
  5835. * Signal numbers are typically defined as constants (e.g., `SIGINT`, `SIGTERM`).
  5836. * @param[in] act A pointer to a `k_sigaction` structure that specifies the new action for the signal.
  5837. * If `act` is `NULL`, the signal's action is not changed.
  5838. * @param[out] oact A pointer to a `k_sigaction` structure where the old action will be stored.
  5839. * If `oact` is `NULL`, the old action is not retrieved.
  5840. * @param[in] sigsetsize The size of the `sigset_t` structure used in `k_sigaction`. This is to ensure the
  5841. * compatibility with the signal mask size.
  5842. *
  5843. * @return sysret_t Returns `0` on success or a negative error code on failure.
  5844. *
  5845. * @note The `k_sigaction` structure allows you to specify the signal handler, signal mask, and flags for
  5846. * the signal action. It is important to correctly configure the handler to prevent unexpected
  5847. * behavior in the signal handling process.
  5848. *
  5849. * @warning Be cautious when modifying signal handling behavior, as incorrect configuration may result
  5850. * in unhandled signals or undefined behavior. Signal handlers should be designed to perform
  5851. * minimal, safe operations.
  5852. *
  5853. * @see sys_signal(), sys_sigprocmask()
  5854. */
  5855. sysret_t sys_sigaction(int sig, const struct k_sigaction *act,
  5856. struct k_sigaction *oact, size_t sigsetsize)
  5857. {
  5858. int ret = -RT_EINVAL;
  5859. struct rt_lwp *lwp;
  5860. struct lwp_sigaction kact, *pkact = RT_NULL;
  5861. struct lwp_sigaction koact, *pkoact = RT_NULL;
  5862. if (!sigsetsize)
  5863. {
  5864. SET_ERRNO(EINVAL);
  5865. goto out;
  5866. }
  5867. if (sigsetsize > sizeof(lwp_sigset_t))
  5868. {
  5869. sigsetsize = sizeof(lwp_sigset_t);
  5870. }
  5871. if (!act && !oact)
  5872. {
  5873. SET_ERRNO(EINVAL);
  5874. goto out;
  5875. }
  5876. if (oact)
  5877. {
  5878. if (!lwp_user_accessable((void *)oact, sizeof(*oact)))
  5879. {
  5880. SET_ERRNO(EFAULT);
  5881. goto out;
  5882. }
  5883. pkoact = &koact;
  5884. }
  5885. if (act)
  5886. {
  5887. if (!lwp_user_accessable((void *)act, sizeof(*act)))
  5888. {
  5889. SET_ERRNO(EFAULT);
  5890. goto out;
  5891. }
  5892. kact.sa_flags = act->flags;
  5893. kact.__sa_handler._sa_handler = act->handler;
  5894. lwp_memcpy(&kact.sa_mask, &act->mask, sigsetsize);
  5895. kact.sa_restorer = act->restorer;
  5896. pkact = &kact;
  5897. }
  5898. lwp = lwp_self();
  5899. RT_ASSERT(lwp);
  5900. ret = lwp_signal_action(lwp, sig, pkact, pkoact);
  5901. #ifdef ARCH_MM_MMU
  5902. if (ret == 0 && oact)
  5903. {
  5904. lwp_put_to_user(&oact->handler, &pkoact->__sa_handler._sa_handler, sizeof(void (*)(int)));
  5905. lwp_put_to_user(&oact->mask, &pkoact->sa_mask, sigsetsize);
  5906. lwp_put_to_user(&oact->flags, &pkoact->sa_flags, sizeof(int));
  5907. lwp_put_to_user(&oact->restorer, &pkoact->sa_restorer, sizeof(void (*)(void)));
  5908. }
  5909. #endif /* ARCH_MM_MMU */
  5910. out:
  5911. return (ret < 0 ? GET_ERRNO() : ret);
  5912. }
  5913. static int mask_command_u2k[] = {
  5914. [SIG_BLOCK] = LWP_SIG_MASK_CMD_BLOCK,
  5915. [SIG_UNBLOCK] = LWP_SIG_MASK_CMD_UNBLOCK,
  5916. [SIG_SETMASK] = LWP_SIG_MASK_CMD_SET_MASK,
  5917. };
  5918. /**
  5919. * @brief Sets or retrieves the signal mask for the calling process.
  5920. *
  5921. * This system call allows the caller to block or unblock signals by modifying the signal mask. The signal
  5922. * mask determines which signals are blocked and which signals can be delivered to the process. The
  5923. * function can also be used to retrieve the current signal mask.
  5924. *
  5925. * @param[in] how The action to be taken on the signal mask. It can be one of the following values:
  5926. * - `SIG_BLOCK`: Add the signals in `sigset` to the current mask.
  5927. * - `SIG_UNBLOCK`: Remove the signals in `sigset` from the current mask.
  5928. * - `SIG_SETMASK`: Set the signal mask to the value in `sigset`, replacing the current mask.
  5929. * @param[in] sigset A pointer to a `sigset_t` structure that specifies the signals to be blocked or unblocked.
  5930. * This parameter is ignored when `how` is `SIG_SETMASK`, in which case `sigset` is used
  5931. * as the new signal mask.
  5932. * @param[out] oset A pointer to a `sigset_t` structure where the previous signal mask will be stored.
  5933. * If `oset` is `NULL`, the previous signal mask will not be returned.
  5934. * @param[in] size The size of the `sigset_t` structure, ensuring compatibility with the signal mask.
  5935. *
  5936. * @return sysret_t Returns `0` on success or a negative error code on failure.
  5937. *
  5938. * @note Modifying the signal mask prevents signals from being delivered to the process while they are blocked.
  5939. * Once the signals are unblocked, they will be delivered to the process if they are pending.
  5940. *
  5941. * @warning Be careful when blocking signals, especially critical ones like `SIGKILL`, as it may interfere
  5942. * with the normal operation of the system. Ensure that signal masks are managed carefully to avoid
  5943. * missing important signals.
  5944. *
  5945. * @see sys_sigaction(), sys_sigpending()
  5946. */
  5947. sysret_t sys_sigprocmask(int how, const sigset_t *sigset, sigset_t *oset, size_t size)
  5948. {
  5949. int ret = -1;
  5950. lwp_sigset_t *pnewset = RT_NULL, *poldset = RT_NULL;
  5951. #ifdef ARCH_MM_MMU
  5952. lwp_sigset_t newset, oldset;
  5953. #endif /* ARCH_MM_MMU*/
  5954. if (!size)
  5955. {
  5956. return -EINVAL;
  5957. }
  5958. if (!oset && !sigset)
  5959. {
  5960. return -EINVAL;
  5961. }
  5962. if (size > sizeof(lwp_sigset_t))
  5963. {
  5964. size = sizeof(lwp_sigset_t);
  5965. }
  5966. if (oset)
  5967. {
  5968. #ifdef ARCH_MM_MMU
  5969. if (!lwp_user_accessable((void *)oset, size))
  5970. {
  5971. return -EFAULT;
  5972. }
  5973. poldset = &oldset;
  5974. #else
  5975. if (!lwp_user_accessable((void *)oset, size))
  5976. {
  5977. return -EFAULT;
  5978. }
  5979. poldset = (lwp_sigset_t *)oset;
  5980. #endif
  5981. }
  5982. if (sigset)
  5983. {
  5984. #ifdef ARCH_MM_MMU
  5985. if (!lwp_user_accessable((void *)sigset, size))
  5986. {
  5987. return -EFAULT;
  5988. }
  5989. lwp_get_from_user(&newset, (void *)sigset, size);
  5990. pnewset = &newset;
  5991. #else
  5992. if (!lwp_user_accessable((void *)sigset, size))
  5993. {
  5994. return -EFAULT;
  5995. }
  5996. pnewset = (lwp_sigset_t *)sigset;
  5997. #endif /* ARCH_MM_MMU */
  5998. }
  5999. ret = lwp_thread_signal_mask(rt_thread_self(), mask_command_u2k[how], pnewset, poldset);
  6000. #ifdef ARCH_MM_MMU
  6001. if (ret < 0)
  6002. {
  6003. return ret;
  6004. }
  6005. if (oset)
  6006. {
  6007. lwp_put_to_user(oset, poldset, size);
  6008. }
  6009. #endif /* ARCH_MM_MMU */
  6010. return (ret < 0 ? -EFAULT : ret);
  6011. }
  6012. /**
  6013. * @brief Retrieves the set of signals that are pending for delivery to the calling process.
  6014. *
  6015. * This system call allows a process to query the set of signals that are pending, i.e., signals that have
  6016. * been sent to the process but have not yet been delivered because the process is blocking those signals
  6017. * or has not yet handled them. The function returns the set of signals that are waiting to be delivered.
  6018. *
  6019. * @param[out] sigset A pointer to a `sigset_t` structure where the set of pending signals will be stored.
  6020. * The `sigset_t` structure will contain the signals that are pending for delivery.
  6021. * @param[in] sigsize The size of the `sigset_t` structure, used to ensure compatibility with the signal set.
  6022. *
  6023. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6024. *
  6025. * @note The returned signal set will contain the signals that have been sent to the process but are blocked,
  6026. * or that are waiting to be handled. These signals will be delivered once they are unblocked or the
  6027. * process handles them.
  6028. *
  6029. * @warning Be cautious when querying pending signals, as unblocking too many signals at once may lead
  6030. * to unexpected behavior or a flood of signal deliveries. It's recommended to carefully manage
  6031. * the signals the process can accept at any given time.
  6032. *
  6033. * @see sys_sigaction(), sys_sigprocmask()
  6034. */
  6035. sysret_t sys_sigpending(sigset_t *sigset, size_t sigsize)
  6036. {
  6037. sysret_t ret = 0;
  6038. lwp_sigset_t lwpset;
  6039. /* Verify and Get sigset, timeout */
  6040. if (!sigset || !lwp_user_accessable((void *)sigset, sigsize))
  6041. {
  6042. ret = -EFAULT;
  6043. }
  6044. else
  6045. {
  6046. /* Fit sigset size to lwp set */
  6047. if (sizeof(lwpset) < sigsize)
  6048. {
  6049. LOG_I("%s: sigsize (%lx) extends lwp sigset chunk\n", __func__, sigsize);
  6050. sigsize = sizeof(lwpset);
  6051. }
  6052. lwp_thread_signal_pending(rt_thread_self(), &lwpset);
  6053. if (!lwp_put_to_user(sigset, &lwpset, sigsize))
  6054. RT_ASSERT(0); /* should never happened */
  6055. }
  6056. return ret;
  6057. }
  6058. /**
  6059. * @brief Waits for a signal to be delivered, with a timeout.
  6060. *
  6061. * This system call allows a process to wait for one of the signals specified in the `sigset` to be delivered.
  6062. * The process will block until a signal in the set is received or the specified timeout period expires.
  6063. * If the signal is received before the timeout, information about the signal will be returned in the `siginfo_t` structure.
  6064. * If the timeout expires without any signal being delivered, the function will return with an appropriate error code.
  6065. *
  6066. * @param[in] sigset A pointer to a `sigset_t` structure that specifies the set of signals to wait for.
  6067. * The function will block until a signal in this set is received, or the timeout expires.
  6068. * @param[out] info A pointer to a `siginfo_t` structure where information about the delivered signal will be stored.
  6069. * If no signal is received before the timeout, this structure will not be filled.
  6070. * @param[in] timeout A pointer to a `timespec` structure that specifies the maximum amount of time to wait
  6071. * for a signal to be delivered. If this value is `NULL`, the function will wait indefinitely.
  6072. * @param[in] sigsize The size of the `sigset_t` structure, ensuring compatibility with the signal set.
  6073. *
  6074. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6075. *
  6076. * @note If the `timeout` is `NULL`, the function will block indefinitely until a signal is delivered.
  6077. * If a signal is received, the corresponding information is returned in the `siginfo_t` structure.
  6078. * The `sigset` should contain only the signals you are interested in.
  6079. *
  6080. * @warning If the timeout expires, no signal will be delivered, and the function will return a timeout error.
  6081. * Make sure to handle the timeout case correctly to prevent any unexpected behavior.
  6082. *
  6083. * @see sys_sigaction(), sys_sigtimedwait()
  6084. */
  6085. sysret_t sys_sigtimedwait(const sigset_t *sigset, siginfo_t *info, const struct timespec *timeout, size_t sigsize)
  6086. {
  6087. int sig;
  6088. size_t ret;
  6089. lwp_sigset_t lwpset;
  6090. siginfo_t kinfo;
  6091. struct timespec ktimeout;
  6092. struct timespec *ptimeout;
  6093. /* for RT_ASSERT */
  6094. RT_UNUSED(ret);
  6095. /* Fit sigset size to lwp set */
  6096. if (sizeof(lwpset) < sigsize)
  6097. {
  6098. LOG_I("%s: sigsize (%lx) extends lwp sigset chunk\n", __func__, sigsize);
  6099. sigsize = sizeof(lwpset);
  6100. }
  6101. else
  6102. {
  6103. /* if sigset of user is smaller, clear extra space */
  6104. memset(&lwpset, 0, sizeof(lwpset));
  6105. }
  6106. /* Verify and Get sigset, timeout */
  6107. if (!sigset || !lwp_user_accessable((void *)sigset, sigsize))
  6108. {
  6109. return -EFAULT;
  6110. }
  6111. else
  6112. {
  6113. ret = lwp_get_from_user(&lwpset, (void *)sigset, sigsize);
  6114. RT_ASSERT(ret == sigsize);
  6115. }
  6116. if (timeout)
  6117. {
  6118. if (!lwp_user_accessable((void *)timeout, sizeof(*timeout)))
  6119. return -EFAULT;
  6120. else
  6121. {
  6122. ret = lwp_get_from_user(&ktimeout, (void *)timeout, sizeof(*timeout));
  6123. ptimeout = &ktimeout;
  6124. RT_ASSERT(ret == sizeof(*timeout));
  6125. }
  6126. }
  6127. else
  6128. {
  6129. ptimeout = RT_NULL;
  6130. }
  6131. sig = lwp_thread_signal_timedwait(rt_thread_self(), &lwpset, &kinfo, ptimeout);
  6132. if (sig > 0 && info)
  6133. {
  6134. if (!lwp_user_accessable((void *)info, sizeof(*info)))
  6135. return -EFAULT;
  6136. else
  6137. {
  6138. ret = lwp_put_to_user(info, &kinfo, sizeof(*info));
  6139. RT_ASSERT(ret == sizeof(*info));
  6140. }
  6141. }
  6142. return sig;
  6143. }
  6144. /**
  6145. * @brief Sends a signal to a specific thread.
  6146. *
  6147. * This system call allows a process to send a signal to a specific thread within the same process.
  6148. * The signal specified by the `sig` parameter will be delivered to the thread with the ID `tid`.
  6149. * This function is similar to `kill()`, but it targets a specific thread rather than a process.
  6150. *
  6151. * @param[in] tid The thread ID to which the signal will be sent. This ID identifies the target thread within the same process.
  6152. * @param[in] sig The signal number to be sent to the specified thread. The signal can be any valid signal number.
  6153. *
  6154. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6155. *
  6156. * @note The `sig` parameter must be a valid signal number. It can range from `1` to `31`, or be one of the predefined signal constants like `SIGKILL`, `SIGTERM`, etc.
  6157. * If the target thread does not exist or is not eligible to receive the signal, the function will fail.
  6158. *
  6159. * @warning If an invalid signal number is provided or the target thread does not exist, an error will be returned.
  6160. * Be careful when sending signals, as some signals (e.g., `SIGKILL`) can immediately terminate the target thread.
  6161. *
  6162. * @see sys_kill(), sys_sigaction()
  6163. */
  6164. sysret_t sys_tkill(int tid, int sig)
  6165. {
  6166. #ifdef ARCH_MM_MMU
  6167. rt_thread_t thread;
  6168. sysret_t ret;
  6169. /**
  6170. * Brief: Match a tid and do the kill
  6171. *
  6172. * Note: Critical Section
  6173. * - the thread (READ. may be released at the meantime; protected by locked)
  6174. */
  6175. thread = lwp_tid_get_thread_and_inc_ref(tid);
  6176. ret = lwp_thread_signal_kill(thread, sig, SI_USER, 0);
  6177. lwp_tid_dec_ref(thread);
  6178. return ret;
  6179. #else
  6180. return lwp_thread_kill((rt_thread_t)tid, sig);
  6181. #endif
  6182. }
  6183. /**
  6184. * @brief Manipulates the signal mask for the current thread.
  6185. *
  6186. * This function allows a thread to modify its signal mask, which controls which signals are blocked (prevented from delivery).
  6187. * The signal mask can be modified by adding, removing, or setting the signal set as a whole, depending on the `how` parameter.
  6188. * The `sigset` specifies the signals to be manipulated, and the current signal mask before modification can be retrieved in `oset`.
  6189. *
  6190. * @param[in] how The operation to perform on the signal mask. It can be one of the following values:
  6191. * - `SIG_BLOCK`: Add the signals in `sigset` to the current mask (block those signals).
  6192. * - `SIG_UNBLOCK`: Remove the signals in `sigset` from the current mask (unblock those signals).
  6193. * - `SIG_SETMASK`: Set the signal mask to the signals specified in `sigset` (replace the current mask).
  6194. * @param[in] sigset A pointer to an `lwp_sigset_t` structure that specifies the set of signals to be manipulated.
  6195. * Signals in this set will be added, removed, or set in the current thread's signal mask based on the `how` parameter.
  6196. * @param[out] oset A pointer to an `lwp_sigset_t` structure where the previous signal mask will be stored.
  6197. * This allows the caller to restore the previous mask if needed.
  6198. * @param[in] size The size of the `lwp_sigset_t` structure. This ensures that the correct structure size is used during signal mask manipulation.
  6199. *
  6200. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6201. *
  6202. * @note The `sigset` structure should contain only valid signal numbers. If `how` is `SIG_SETMASK`, the entire signal mask will be replaced by the contents of `sigset`.
  6203. * If `how` is `SIG_BLOCK` or `SIG_UNBLOCK`, the signals in `sigset` will be added or removed from the current mask, respectively.
  6204. *
  6205. * @warning Be cautious when modifying the signal mask, as blocking signals can cause the thread to miss important signals.
  6206. * If a signal is blocked, it will not be delivered to the thread until it is unblocked, or the thread is explicitly made to handle it.
  6207. *
  6208. * @see sys_sigaction(), sys_thread_sigpending()
  6209. */
  6210. sysret_t sys_thread_sigprocmask(int how, const lwp_sigset_t *sigset, lwp_sigset_t *oset, size_t size)
  6211. {
  6212. int ret = -1;
  6213. lwp_sigset_t *pnewset = RT_NULL, *poldset = RT_NULL;
  6214. #ifdef ARCH_MM_MMU
  6215. lwp_sigset_t newset, oldset;
  6216. #endif /* ARCH_MM_MMU */
  6217. if (!size)
  6218. {
  6219. return -EINVAL;
  6220. }
  6221. if (!oset && !sigset)
  6222. {
  6223. return -EINVAL;
  6224. }
  6225. if (size != sizeof(lwp_sigset_t))
  6226. {
  6227. return -EINVAL;
  6228. }
  6229. if (oset)
  6230. {
  6231. #ifdef ARCH_MM_MMU
  6232. if (!lwp_user_accessable((void *)oset, size))
  6233. {
  6234. return -EFAULT;
  6235. }
  6236. poldset = &oldset;
  6237. #else
  6238. if (!lwp_user_accessable((void *)oset, size))
  6239. {
  6240. return -EFAULT;
  6241. }
  6242. poldset = oset;
  6243. #endif
  6244. }
  6245. if (sigset)
  6246. {
  6247. #ifdef ARCH_MM_MMU
  6248. if (!lwp_user_accessable((void *)sigset, size))
  6249. {
  6250. return -EFAULT;
  6251. }
  6252. lwp_get_from_user(&newset, (void *)sigset, sizeof(lwp_sigset_t));
  6253. pnewset = &newset;
  6254. #else
  6255. if (!lwp_user_accessable((void *)sigset, size))
  6256. {
  6257. return -EFAULT;
  6258. }
  6259. pnewset = (lwp_sigset_t *)sigset;
  6260. #endif
  6261. }
  6262. ret = lwp_thread_signal_mask(rt_thread_self(), mask_command_u2k[how], pnewset, poldset);
  6263. if (ret < 0)
  6264. {
  6265. return ret;
  6266. }
  6267. #ifdef ARCH_MM_MMU
  6268. if (oset)
  6269. {
  6270. lwp_put_to_user(oset, poldset, sizeof(lwp_sigset_t));
  6271. }
  6272. #endif
  6273. return (ret < 0 ? -EFAULT : ret);
  6274. }
  6275. #ifndef ARCH_MM_MMU
  6276. /**
  6277. * @brief Sets the signal handler for a specific signal in the current thread.
  6278. *
  6279. * This function allows a thread to set a custom signal handler for a specific signal.
  6280. * When the specified signal is received, the corresponding handler function (`func`) will be invoked.
  6281. * The handler will be executed in the context of the current thread, allowing it to handle signals as needed.
  6282. *
  6283. * @param[in] sig The signal number for which the handler is being set. This should be a valid signal number.
  6284. * @param[in] func The signal handler function to be set. This function will be called when the specified signal is received.
  6285. * The signature of `func` should match the expected format for signal handlers.
  6286. *
  6287. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6288. *
  6289. * @note The `func` parameter must be a valid function pointer. It will be called when the signal specified by `sig` is received by the thread.
  6290. * The handler function typically has the signature: `void handler(int sig)`, where `sig` is the signal number.
  6291. *
  6292. * @warning Setting a custom signal handler may override any default actions for that signal.
  6293. * It is important to ensure that the handler function is properly designed to handle the signal appropriately.
  6294. * For example, some signals may require special handling (e.g., `SIGKILL` cannot be caught).
  6295. *
  6296. * @see sys_signal(), sys_lwp_sigaction()
  6297. */
  6298. sysret_t sys_lwp_sighandler_set(int sig, lwp_sighandler_t func)
  6299. {
  6300. if (!lwp_user_accessable((void *)func, sizeof(lwp_sighandler_t)))
  6301. {
  6302. return -EFAULT;
  6303. }
  6304. lwp_sighandler_set(sig, func);
  6305. return 0;
  6306. }
  6307. /**
  6308. * @brief Sets the signal handler for a specific signal in the target thread.
  6309. *
  6310. * This function allows setting a custom signal handler for a specific signal within a particular thread.
  6311. * When the specified signal is delivered to the thread, the corresponding handler function (`func`) will be invoked.
  6312. * The handler is executed in the context of the thread that receives the signal.
  6313. *
  6314. * @param[in] sig The signal number for which the handler is being set. This should be a valid signal number.
  6315. * @param[in] func The signal handler function to be set. This function will be called when the specified signal is delivered to the target thread.
  6316. * The handler function should have the signature `void func(int sig)`.
  6317. *
  6318. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6319. *
  6320. * @note The `func` parameter must be a valid function pointer, and it will be invoked when the signal specified by `sig` is delivered to the target thread.
  6321. * The handler function typically has the signature: `void handler(int sig)`, where `sig` is the signal number.
  6322. *
  6323. * @warning Setting a custom signal handler may override any default actions for that signal.
  6324. * It is important to ensure that the handler function is properly designed to handle the signal appropriately.
  6325. * For example, some signals may require special handling (e.g., `SIGKILL` cannot be caught).
  6326. *
  6327. * @see sys_thread_sigprocmask(), sys_thread_sigaction(), sys_signal()
  6328. */
  6329. sysret_t sys_thread_sighandler_set(int sig, lwp_sighandler_t func)
  6330. {
  6331. if (!lwp_user_accessable((void *)func, sizeof(lwp_sighandler_t)))
  6332. {
  6333. return -EFAULT;
  6334. }
  6335. lwp_thread_sighandler_set(sig, func);
  6336. return 0;
  6337. }
  6338. #endif /* not defined ARCH_MM_MMU */
  6339. /**
  6340. * @brief Waits for the termination of a child process.
  6341. *
  6342. * This function makes the calling process wait until one of its child processes terminates or until a
  6343. * specified condition is met. The function retrieves information about the terminated child process,
  6344. * including its exit status, and can also handle other process-related events, such as stopping or
  6345. * continuing execution.
  6346. *
  6347. * @param[in] pid The process ID of the child process to wait for. If `pid` is:
  6348. * - `-1`: Wait for any child process.
  6349. * - `0`: Wait for any child process in the same process group.
  6350. * - > 0: Wait for the child process with the specified process ID.
  6351. * @param[out] status A pointer to an integer where the exit status of the terminated child process will be stored.
  6352. * This value provides information about the child's termination status, such as normal exit,
  6353. * signal termination, etc.
  6354. * @param[in] options A bitmask of options that control the behavior of the function. It can include:
  6355. * - `WNOHANG`: Return immediately if no child has exited.
  6356. * - `WUNTRACED`: Report status of stopped child processes.
  6357. * - Other flags can be defined depending on the implementation.
  6358. *
  6359. * @return sysret_t Returns the process ID of the child process that terminated on success, or a negative error code on failure.
  6360. *
  6361. * @note The `status` argument provides detailed information about the termination of the child process. To interpret this
  6362. * status, macros such as `WIFEXITED()`, `WIFSIGNALED()`, and `WEXITSTATUS()` are commonly used.
  6363. *
  6364. * @warning This function should be used carefully when managing child processes, as not properly handling child processes
  6365. * may lead to zombie processes.
  6366. *
  6367. * @see sys_wait(), sys_waitid()
  6368. */
  6369. sysret_t sys_waitpid(int32_t pid, int *status, int options)
  6370. {
  6371. int ret = -1;
  6372. #ifdef ARCH_MM_MMU
  6373. if (!lwp_user_accessable((void *)status, sizeof(int)))
  6374. {
  6375. return -EFAULT;
  6376. }
  6377. else
  6378. {
  6379. ret = lwp_waitpid(pid, status, options, RT_NULL);
  6380. }
  6381. #else
  6382. if (!lwp_user_accessable((void *)status, sizeof(int)))
  6383. {
  6384. return -EFAULT;
  6385. }
  6386. ret = waitpid(pid, status, options);
  6387. #endif
  6388. return ret;
  6389. }
  6390. #if defined(RT_USING_SAL) && defined(SAL_USING_POSIX)
  6391. struct musl_addrinfo
  6392. {
  6393. int ai_flags;
  6394. int ai_family;
  6395. int ai_socktype;
  6396. int ai_protocol;
  6397. socklen_t ai_addrlen;
  6398. struct musl_sockaddr *ai_addr;
  6399. char *ai_canonname;
  6400. struct musl_addrinfo *ai_next;
  6401. };
  6402. /**
  6403. * @brief Resolves network addresses and service names into a list of address structures.
  6404. *
  6405. * This function provides a mechanism for resolving a host name and service name (or port number)
  6406. * into a list of address structures suitable for use with socket-based communication. The function
  6407. * can handle both IPv4 and IPv6 addresses and provides a flexible way to specify different types
  6408. * of address and service resolution options.
  6409. *
  6410. * @param[in] nodename The host name to be resolved. This can be a DNS name or an IP address in string format.
  6411. * If `nodename` is `NULL`, the function will resolve the local host.
  6412. * @param[in] servname The service name (e.g., "http") or port number to be resolved. If `servname` is `NULL`,
  6413. * the function will resolve the port number or address without any service association.
  6414. * @param[in] hints A pointer to a `struct musl_addrinfo` that provides hints for the address resolution.
  6415. * It can be used to specify criteria such as the desired address family (IPv4 or IPv6),
  6416. * socket type, protocol, and flags for resolution.
  6417. * @param[out] res A pointer to a `struct musl_addrinfo` that will be filled with the resolved address
  6418. * information. The resulting linked list will contain one or more `struct musl_sockaddr`
  6419. * structures, each representing a different address that can be used for communication.
  6420. *
  6421. * @return sysret_t Returns `0` on success, indicating that the address resolution was successful.
  6422. * On failure, returns a negative error code.
  6423. *
  6424. * @note The `res` parameter points to a linked list of resolved address structures. Each node in the list
  6425. * contains a different resolved address and can be used for socket connection purposes.
  6426. * It is important to free the memory allocated for the list after it is no longer needed, using `freeaddrinfo()`.
  6427. *
  6428. * @warning The `hints` structure allows you to specify various options for the resolution. However, incorrect
  6429. * hints may lead to unexpected or incorrect results. For example, if you request IPv6 addresses but
  6430. * the host only supports IPv4, the function may not return the expected results.
  6431. *
  6432. * @see freeaddrinfo(), sys_socket(), sys_connect(), sys_gethostbyname(), sys_gethostbyaddr()
  6433. */
  6434. sysret_t sys_getaddrinfo(const char *nodename,
  6435. const char *servname,
  6436. const struct musl_addrinfo *hints,
  6437. struct musl_addrinfo *res)
  6438. {
  6439. int ret = -1;
  6440. struct addrinfo *k_res = NULL;
  6441. char *k_nodename = NULL;
  6442. char *k_servname = NULL;
  6443. struct addrinfo *k_hints = NULL;
  6444. #ifdef ARCH_MM_MMU
  6445. int len = 0;
  6446. #endif
  6447. #ifdef ARCH_MM_MMU
  6448. if (!lwp_user_accessable((void *)res, sizeof(*res)))
  6449. {
  6450. SET_ERRNO(EFAULT);
  6451. goto exit;
  6452. }
  6453. #endif
  6454. if (nodename)
  6455. {
  6456. #ifdef ARCH_MM_MMU
  6457. len = lwp_user_strlen(nodename);
  6458. if (len <= 0)
  6459. {
  6460. SET_ERRNO(EFAULT);
  6461. goto exit;
  6462. }
  6463. k_nodename = (char *)kmem_get(len + 1);
  6464. if (!k_nodename)
  6465. {
  6466. SET_ERRNO(ENOMEM);
  6467. goto exit;
  6468. }
  6469. if (lwp_get_from_user(k_nodename, (void *)nodename, len + 1) != len + 1)
  6470. {
  6471. SET_ERRNO(EFAULT);
  6472. goto exit;
  6473. }
  6474. #else
  6475. k_nodename = rt_strdup(nodename);
  6476. if (!k_nodename)
  6477. {
  6478. SET_ERRNO(ENOMEM);
  6479. goto exit;
  6480. }
  6481. #endif
  6482. }
  6483. if (servname)
  6484. {
  6485. #ifdef ARCH_MM_MMU
  6486. len = lwp_user_strlen(servname);
  6487. if (len <= 0)
  6488. {
  6489. SET_ERRNO(EFAULT);
  6490. goto exit;
  6491. }
  6492. k_servname = (char *)kmem_get(len + 1);
  6493. if (!k_servname)
  6494. {
  6495. SET_ERRNO(ENOMEM);
  6496. goto exit;
  6497. }
  6498. if (lwp_get_from_user(k_servname, (void *)servname, len + 1) < 0)
  6499. {
  6500. SET_ERRNO(EFAULT);
  6501. goto exit;
  6502. }
  6503. #else
  6504. k_servname = rt_strdup(servname);
  6505. if (!k_servname)
  6506. {
  6507. SET_ERRNO(ENOMEM);
  6508. goto exit;
  6509. }
  6510. #endif
  6511. }
  6512. if (hints)
  6513. {
  6514. #ifdef ARCH_MM_MMU
  6515. if (!lwp_user_accessable((void *)hints, sizeof(*hints)))
  6516. {
  6517. SET_ERRNO(EFAULT);
  6518. goto exit;
  6519. }
  6520. #endif
  6521. k_hints = (struct addrinfo *)rt_malloc(sizeof *hints);
  6522. if (!k_hints)
  6523. {
  6524. SET_ERRNO(ENOMEM);
  6525. goto exit;
  6526. }
  6527. rt_memset(k_hints, 0x0, sizeof(struct addrinfo));
  6528. k_hints->ai_flags = hints->ai_flags;
  6529. k_hints->ai_family = hints->ai_family;
  6530. k_hints->ai_socktype = hints->ai_socktype;
  6531. k_hints->ai_protocol = hints->ai_protocol;
  6532. k_hints->ai_addrlen = hints->ai_addrlen;
  6533. }
  6534. ret = sal_getaddrinfo(k_nodename, k_servname, k_hints, &k_res);
  6535. if (ret == 0)
  6536. {
  6537. /* set sockaddr */
  6538. sockaddr_tomusl(k_res->ai_addr, res->ai_addr);
  6539. res->ai_addrlen = k_res->ai_addrlen;
  6540. /* set up addrinfo */
  6541. res->ai_family = k_res->ai_family;
  6542. res->ai_flags = k_res->ai_flags;
  6543. res->ai_next = NULL;
  6544. if (hints != NULL)
  6545. {
  6546. /* copy socktype & protocol from hints if specified */
  6547. res->ai_socktype = hints->ai_socktype;
  6548. res->ai_protocol = hints->ai_protocol;
  6549. }
  6550. sal_freeaddrinfo(k_res);
  6551. k_res = NULL;
  6552. }
  6553. exit:
  6554. if (ret < 0)
  6555. {
  6556. ret = GET_ERRNO();
  6557. }
  6558. #ifdef ARCH_MM_MMU
  6559. if (k_nodename)
  6560. {
  6561. kmem_put(k_nodename);
  6562. }
  6563. #else
  6564. if (k_nodename)
  6565. {
  6566. rt_free(k_nodename);
  6567. }
  6568. #endif
  6569. #ifdef ARCH_MM_MMU
  6570. if (k_servname)
  6571. {
  6572. kmem_put(k_servname);
  6573. }
  6574. #else
  6575. if (k_servname)
  6576. {
  6577. rt_free(k_servname);
  6578. }
  6579. #endif
  6580. if (k_hints)
  6581. {
  6582. rt_free(k_hints);
  6583. }
  6584. return ret;
  6585. }
  6586. #define HOSTENT_BUFSZ 512
  6587. /**
  6588. * @brief Resolves a host name to an address, with support for specifying the address family.
  6589. *
  6590. * This function performs a lookup of the specified host name, and resolves it to an address,
  6591. * while allowing the caller to specify the desired address family (e.g., IPv4 or IPv6). It is
  6592. * a reentrant version of `gethostbyname2`, meaning it is safe for use in multi-threaded applications.
  6593. * The results are returned in a user-provided buffer to avoid memory allocation overhead.
  6594. *
  6595. * @param[in] name The host name to be resolved. This can be a DNS name or an IP address in string format.
  6596. * @param[in] af The address family to use for the resolution. Common values are:
  6597. * - `AF_INET` for IPv4 addresses.
  6598. * - `AF_INET6` for IPv6 addresses.
  6599. * @param[out] ret A pointer to a `struct hostent` where the resolved host information will be stored.
  6600. * This includes the host name, alias names, address type, and the address itself.
  6601. * @param[in] buf A buffer to store additional information required for the `struct hostent` structure.
  6602. * This is needed to ensure the reentrant behavior and avoid memory allocation.
  6603. * @param[in] buflen The size of the buffer provided.
  6604. * @param[out] result A pointer to a `struct hostent*` that will point to the resolved host entry.
  6605. * This will be set to the value of `ret` upon success.
  6606. * @param[out] err A pointer to an integer where error codes will be stored. If the function fails,
  6607. * `err` will contain a non-zero value corresponding to the error.
  6608. *
  6609. * @return sysret_t Returns `0` on success, indicating the resolution was successful.
  6610. * On failure, returns a negative error code that indicates the failure reason.
  6611. *
  6612. * @note This function is reentrant and thread-safe, meaning it does not use static memory or global state.
  6613. * It relies on the buffers provided by the caller to store the resolved data.
  6614. *
  6615. * @see gethostbyname2(), sys_gethostbyname(), sys_socket(), sys_connect(), sys_getaddrinfo()
  6616. */
  6617. sysret_t sys_gethostbyname2_r(const char *name, int af, struct hostent *ret,
  6618. char *buf, size_t buflen,
  6619. struct hostent **result, int *err)
  6620. {
  6621. int ret_val = -1;
  6622. int sal_ret = -1, sal_err = -1;
  6623. struct hostent sal_he, sal_tmp;
  6624. struct hostent *sal_result = NULL;
  6625. char *sal_buf = NULL;
  6626. char *k_name = NULL;
  6627. int len = 0;
  6628. #ifdef ARCH_MM_MMU
  6629. if (!lwp_user_accessable((void *)err, sizeof(*err)))
  6630. {
  6631. SET_ERRNO(EFAULT);
  6632. goto __exit;
  6633. }
  6634. if (!lwp_user_accessable((void *)result, sizeof(*result)) || !lwp_user_accessable((void *)ret, sizeof(*ret)) || !lwp_user_accessable((void *)buf, buflen))
  6635. {
  6636. /* not all arguments given */
  6637. *err = EFAULT;
  6638. SET_ERRNO(EFAULT);
  6639. goto __exit;
  6640. }
  6641. len = lwp_user_strlen(name);
  6642. if (len <= 0)
  6643. {
  6644. *err = EFAULT;
  6645. SET_ERRNO(EFAULT);
  6646. goto __exit;
  6647. }
  6648. k_name = (char *)kmem_get(len + 1);
  6649. if (!k_name)
  6650. {
  6651. SET_ERRNO(ENOMEM);
  6652. goto __exit;
  6653. }
  6654. if (lwp_get_from_user(k_name, (void *)name, len + 1) < 0)
  6655. {
  6656. SET_ERRNO(EFAULT);
  6657. goto __exit;
  6658. }
  6659. #else
  6660. k_name = rt_strdup(name);
  6661. if (k_name == NULL)
  6662. {
  6663. SET_ERRNO(ENOMEM);
  6664. goto __exit;
  6665. }
  6666. #endif
  6667. *result = ret;
  6668. sal_buf = (char *)malloc(HOSTENT_BUFSZ);
  6669. if (sal_buf == NULL)
  6670. {
  6671. SET_ERRNO(ENOMEM);
  6672. goto __exit;
  6673. }
  6674. /* get host by name in SAL */
  6675. sal_ret = sal_gethostbyname_r(k_name, &sal_he, sal_buf, HOSTENT_BUFSZ, &sal_result, &sal_err);
  6676. if (sal_ret == 0)
  6677. {
  6678. int index = 0, cnt = 0;
  6679. char *ptr = buf;
  6680. /* get counter */
  6681. index = 0;
  6682. while (sal_he.h_addr_list[index] != NULL)
  6683. {
  6684. index++;
  6685. }
  6686. cnt = index + 1;
  6687. #ifdef ARCH_MM_MMU
  6688. /* update user space hostent */
  6689. lwp_put_to_user(buf, k_name, buflen - (ptr - buf));
  6690. lwp_memcpy(&sal_tmp, &sal_he, sizeof(sal_he));
  6691. sal_tmp.h_name = ptr;
  6692. ptr += rt_strlen(k_name);
  6693. sal_tmp.h_addr_list = (char **)ptr;
  6694. ptr += cnt * sizeof(char *);
  6695. index = 0;
  6696. while (sal_he.h_addr_list[index] != NULL)
  6697. {
  6698. sal_tmp.h_addr_list[index] = ptr;
  6699. lwp_memcpy(ptr, sal_he.h_addr_list[index], sal_he.h_length);
  6700. ptr += sal_he.h_length;
  6701. index++;
  6702. }
  6703. sal_tmp.h_addr_list[index] = NULL;
  6704. lwp_put_to_user(ret, &sal_tmp, sizeof(sal_tmp));
  6705. #else
  6706. /* update user space hostent */
  6707. ret->h_addrtype = sal_he.h_addrtype;
  6708. ret->h_length = sal_he.h_length;
  6709. rt_strncpy(ptr, k_name, buflen - (ptr - buf));
  6710. ret->h_name = ptr;
  6711. ptr += strlen(k_name);
  6712. ret->h_addr_list = (char **)ptr;
  6713. ptr += cnt * sizeof(char *);
  6714. index = 0;
  6715. while (sal_he.h_addr_list[index] != NULL)
  6716. {
  6717. ret->h_addr_list[index] = ptr;
  6718. lwp_memcpy(ptr, sal_he.h_addr_list[index], sal_he.h_length);
  6719. ptr += sal_he.h_length;
  6720. index++;
  6721. }
  6722. ret->h_addr_list[index] = NULL;
  6723. #endif
  6724. ret_val = 0;
  6725. }
  6726. else
  6727. {
  6728. SET_ERRNO(EINVAL);
  6729. }
  6730. __exit:
  6731. if (ret_val < 0)
  6732. {
  6733. ret_val = GET_ERRNO();
  6734. }
  6735. /* release buffer */
  6736. if (sal_buf)
  6737. {
  6738. free(sal_buf);
  6739. }
  6740. #ifdef ARCH_MM_MMU
  6741. if (k_name)
  6742. {
  6743. kmem_put(k_name);
  6744. }
  6745. #else
  6746. if (k_name)
  6747. {
  6748. free(k_name);
  6749. }
  6750. #endif
  6751. return ret_val;
  6752. }
  6753. #endif
  6754. /**
  6755. * @brief Gets the current working directory.
  6756. *
  6757. * This function retrieves the absolute pathname of the current working directory
  6758. * and stores it in the provided buffer. The buffer must be large enough to hold
  6759. * the directory path, including the null-terminator. If the buffer is too small,
  6760. * the function will return an error.
  6761. *
  6762. * @param[out] buf A pointer to a buffer where the current working directory
  6763. * path will be stored. The buffer should be large enough
  6764. * to hold the path, including the null-terminator.
  6765. * @param[in] size The size of the buffer in bytes. The buffer must be large enough
  6766. * to accommodate the full path.
  6767. *
  6768. * @return long On success, returns the number of bytes written to the buffer
  6769. * (not including the null-terminator). If the buffer is not large
  6770. * enough, returns a negative error code.
  6771. *
  6772. * @note The maximum path length depends on the system's configuration.
  6773. * Ensure the buffer size is sufficient to hold the entire path.
  6774. *
  6775. * @see sys_chdir(), sys_getcwd_r(), sys_realpath()
  6776. */
  6777. long sys_getcwd(char *buf, size_t size)
  6778. {
  6779. char *tmp = RT_NULL;
  6780. long ret = -1;
  6781. if (!lwp_user_accessable((void *)buf, size))
  6782. {
  6783. return ret;
  6784. }
  6785. tmp = (char *)rt_malloc(size);
  6786. if (!tmp)
  6787. {
  6788. return ret;
  6789. }
  6790. if (getcwd(tmp, size) != RT_NULL)
  6791. {
  6792. if (lwp_put_to_user(buf, tmp, size) > 0)
  6793. {
  6794. if (buf != RT_NULL)
  6795. ret = strlen(buf);
  6796. else
  6797. ret = -EFAULT;
  6798. }
  6799. }
  6800. rt_free(tmp);
  6801. return ret;
  6802. }
  6803. /**
  6804. * @brief Changes the current working directory.
  6805. *
  6806. * This function changes the current working directory of the calling process
  6807. * to the directory specified by the given path. The path can be absolute or
  6808. * relative. If the specified path does not exist or the process does not have
  6809. * sufficient permissions, the function will return an error.
  6810. *
  6811. * @param[in] path The path to the new working directory. This can be either
  6812. * an absolute or a relative path.
  6813. *
  6814. * @return sysret_t Returns `0` on success, indicating that the working
  6815. * directory was successfully changed. On failure, returns a
  6816. * negative error code indicating the reason for failure.
  6817. *
  6818. * @note If the specified path is a relative path, it is interpreted relative
  6819. * to the current working directory.
  6820. *
  6821. * @see sys_getcwd(), sys_chdir() for changing directories, sys_opendir(), sys_stat()
  6822. */
  6823. sysret_t sys_chdir(const char *path)
  6824. {
  6825. #ifdef ARCH_MM_MMU
  6826. int err = 0;
  6827. int len = 0;
  6828. int errcode;
  6829. char *kpath = RT_NULL;
  6830. len = lwp_user_strlen(path);
  6831. if (len <= 0)
  6832. {
  6833. return -EFAULT;
  6834. }
  6835. kpath = (char *)kmem_get(len + 1);
  6836. if (!kpath)
  6837. {
  6838. return -ENOMEM;
  6839. }
  6840. if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
  6841. {
  6842. kmem_put(kpath);
  6843. return -EINVAL;
  6844. }
  6845. err = chdir(kpath);
  6846. errcode = err != 0 ? GET_ERRNO() : 0;
  6847. kmem_put(kpath);
  6848. return errcode;
  6849. #else
  6850. int ret = chdir(path);
  6851. return (ret < 0 ? GET_ERRNO() : ret);
  6852. #endif
  6853. }
  6854. /**
  6855. * @brief Changes the current working directory to the one associated with the specified file descriptor.
  6856. *
  6857. * This function changes the current working directory of the calling process
  6858. * to the directory associated with the file descriptor `fd`. The file descriptor
  6859. * should refer to an open directory. If the file descriptor does not refer to a
  6860. * directory, or if the process lacks the necessary permissions, the function will
  6861. * return an error.
  6862. *
  6863. * @param[in] fd The file descriptor referring to the directory to which the current
  6864. * working directory should be changed.
  6865. *
  6866. * @return sysret_t Returns `0` on success, indicating the current working directory
  6867. * was successfully changed. On failure, returns a negative error code.
  6868. *
  6869. * @note The file descriptor must refer to a directory. If it refers to a file or other
  6870. * non-directory object, the operation will fail.
  6871. *
  6872. * @see sys_chdir(), sys_getcwd(), sys_opendir(), sys_open()
  6873. */
  6874. sysret_t sys_fchdir(int fd)
  6875. {
  6876. int errcode = -ENOSYS;
  6877. #ifdef ARCH_MM_MMU
  6878. #ifdef RT_USING_DFS_V2
  6879. int err = -1;
  6880. struct dfs_file *d;
  6881. char *kpath;
  6882. d = fd_get(fd);
  6883. if (!d || !d->vnode)
  6884. {
  6885. return -EBADF;
  6886. }
  6887. kpath = dfs_dentry_full_path(d->dentry);
  6888. if (!kpath)
  6889. {
  6890. return -EACCES;
  6891. }
  6892. err = chdir(kpath);
  6893. errcode = err != 0 ? GET_ERRNO() : 0;
  6894. kmem_put(kpath);
  6895. #endif
  6896. #endif
  6897. return errcode;
  6898. }
  6899. /**
  6900. * @brief Creates a new directory with the specified path and mode.
  6901. *
  6902. * This function creates a new directory with the specified path and mode.
  6903. * The directory is created with the permissions specified by the `mode` parameter.
  6904. * If the directory already exists, the function will return an error.
  6905. *
  6906. * @param[in] path The path of the directory to be created. This can be an absolute
  6907. * or relative path. If the directory does not exist, it will be created.
  6908. * @param[in] mode The permissions to be set for the new directory. This parameter
  6909. * specifies the access permissions for the directory owner, group, and others.
  6910. *
  6911. * @return sysret_t Returns `0` on success, indicating that the directory was successfully
  6912. * created. On failure, returns a negative error code indicating the reason for failure.
  6913. *
  6914. * @note The `mode` parameter specifies the permissions for the new directory. The permissions
  6915. * are typically specified using the `S_IRWXU`, `S_IRWXG`, and `S_IRWXO` macros, which
  6916. * define the read, write, and execute permissions for the owner, group, and others.
  6917. *
  6918. * @see sys_rmdir(), sys_chdir(), sys_mkdirat()
  6919. */
  6920. sysret_t sys_mkdir(const char *path, mode_t mode)
  6921. {
  6922. #ifdef ARCH_MM_MMU
  6923. int err = 0;
  6924. int len = 0;
  6925. char *kpath = RT_NULL;
  6926. len = lwp_user_strlen(path);
  6927. if (len <= 0)
  6928. {
  6929. return -EFAULT;
  6930. }
  6931. kpath = (char *)kmem_get(len + 1);
  6932. if (!kpath)
  6933. {
  6934. return -ENOMEM;
  6935. }
  6936. if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
  6937. {
  6938. kmem_put(kpath);
  6939. return -EINVAL;
  6940. }
  6941. err = _SYS_WRAP(mkdir(kpath, mode));
  6942. kmem_put(kpath);
  6943. return err;
  6944. #else
  6945. int ret = mkdir(path, mode);
  6946. return (ret < 0 ? GET_ERRNO() : ret);
  6947. #endif
  6948. }
  6949. /**
  6950. * @brief Removes the specified directory.
  6951. *
  6952. * This function removes the directory specified by the given path. The directory
  6953. * must be empty for the operation to succeed. If the directory is not empty, the
  6954. * function will return an error. If the directory does not exist or the process
  6955. * lacks the necessary permissions, the function will also return an error.
  6956. *
  6957. * @param[in] path The path of the directory to be removed. This can be an absolute
  6958. * or relative path. The directory must be empty for the operation to succeed.
  6959. *
  6960. * @return sysret_t Returns `0` on success, indicating that the directory was successfully
  6961. * removed. On failure, returns a negative error code indicating the reason for failure.
  6962. *
  6963. * @note The directory must be empty for the operation to succeed. If the directory contains
  6964. * files or subdirectories, the operation will fail. To remove a non-empty directory,
  6965. * the contents must be deleted first.
  6966. *
  6967. * @see sys_mkdir(), sys_chdir(), sys_rmdirat()
  6968. */
  6969. sysret_t sys_rmdir(const char *path)
  6970. {
  6971. int err = 0;
  6972. int ret = 0;
  6973. #ifdef ARCH_MM_MMU
  6974. int len = 0;
  6975. char *kpath = RT_NULL;
  6976. len = lwp_user_strlen(path);
  6977. if (len <= 0)
  6978. {
  6979. return -EFAULT;
  6980. }
  6981. kpath = (char *)kmem_get(len + 1);
  6982. if (!kpath)
  6983. {
  6984. return -ENOMEM;
  6985. }
  6986. if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
  6987. {
  6988. kmem_put(kpath);
  6989. return -EINVAL;
  6990. }
  6991. ret = rmdir(kpath);
  6992. if (ret < 0)
  6993. {
  6994. err = GET_ERRNO();
  6995. }
  6996. kmem_put(kpath);
  6997. return (err < 0 ? err : ret);
  6998. #else
  6999. ret = rmdir(path);
  7000. if (ret < 0)
  7001. {
  7002. err = GET_ERRNO();
  7003. }
  7004. return (err < 0 ? err : ret);
  7005. #endif
  7006. }
  7007. /**
  7008. * @brief Reads directory entries.
  7009. *
  7010. * This function reads the directory entries from the directory stream specified by the file descriptor `fd`.
  7011. * It stores the directory entries in the buffer pointed to by `dirp`, up to the specified number of bytes (`nbytes`).
  7012. * The entries are returned in a format compatible with the `struct libc_dirent` structure.
  7013. *
  7014. * @param[in] fd The file descriptor referring to an open directory. This descriptor must be obtained
  7015. * from a call to `sys_open()` with the appropriate flags for directory reading.
  7016. * @param[out] dirp A pointer to a buffer where the directory entries will be stored.
  7017. * The buffer must be large enough to hold at least `nbytes` bytes of directory entries.
  7018. * @param[in] nbytes The size of the buffer (`dirp`) in bytes. It limits the number of directory entries
  7019. * that can be read in a single call. The function will return as many entries as possible
  7020. * that fit within the buffer size.
  7021. *
  7022. * @return sysret_t Returns the number of bytes read on success, which may be less than `nbytes` if there
  7023. * are fewer entries in the directory or if the buffer is too small.
  7024. * On failure, returns a negative error code.
  7025. *
  7026. * @note If the function returns 0, it indicates the end of the directory stream. A negative return value
  7027. * indicates an error. The caller can use the returned number of bytes to process the entries in `dirp`.
  7028. *
  7029. * @see sys_open(), sys_close(), sys_readdir(), sys_stat()
  7030. */
  7031. sysret_t sys_getdents(int fd, struct libc_dirent *dirp, size_t nbytes)
  7032. {
  7033. int ret = -1;
  7034. struct dfs_file *file;
  7035. size_t cnt = (nbytes / sizeof(struct libc_dirent));
  7036. size_t rtt_nbytes = 0;
  7037. struct dirent *rtt_dirp;
  7038. #ifdef ARCH_MM_MMU
  7039. if (!lwp_user_accessable((void *)dirp, sizeof(struct libc_dirent)))
  7040. {
  7041. return -EFAULT;
  7042. }
  7043. #endif
  7044. if (cnt == 0)
  7045. {
  7046. return -EINVAL;
  7047. }
  7048. rtt_nbytes = cnt * sizeof(struct dirent);
  7049. rtt_dirp = (struct dirent *)rt_malloc(rtt_nbytes);
  7050. if (!rtt_dirp)
  7051. {
  7052. return -ENOMEM;
  7053. }
  7054. file = fd_get(fd);
  7055. ret = dfs_file_getdents(file, rtt_dirp, rtt_nbytes);
  7056. if (ret > 0)
  7057. {
  7058. size_t i = 0;
  7059. cnt = ret / sizeof(struct dirent);
  7060. for (i = 0; i < cnt; i++)
  7061. {
  7062. dirp[i].d_ino = 0;
  7063. dirp[i].d_off = i * sizeof(struct libc_dirent);
  7064. dirp[i].d_type = rtt_dirp[i].d_type;
  7065. dirp[i].d_reclen = sizeof(struct libc_dirent);
  7066. strcpy(dirp[i].d_name, rtt_dirp[i].d_name);
  7067. }
  7068. ret = cnt * sizeof(struct libc_dirent);
  7069. }
  7070. if (ret < 0)
  7071. {
  7072. ret = GET_ERRNO();
  7073. }
  7074. rt_free(rtt_dirp);
  7075. return ret;
  7076. }
  7077. /**
  7078. * @brief Retrieves the current value of the error code.
  7079. *
  7080. * This function returns the most recent error code set by a system call. The error code is typically set
  7081. * when a system call fails. This function allows users to retrieve the last error that occurred, helping to
  7082. * diagnose issues or handle errors in a more controlled manner.
  7083. *
  7084. * @return sysret_t The current error code. A value of `0` indicates no error, while a non-zero value
  7085. * represents the most recent error. The error codes are system-specific and can
  7086. * represent various failure conditions (e.g., `EINVAL`, `ENOMEM`, `EIO`).
  7087. *
  7088. * @note The error code returned is specific to the current thread or process and is typically updated
  7089. * each time a system call fails. The error code is persistent until it is overwritten by the next
  7090. * failed system call or explicitly reset.
  7091. *
  7092. * @see sys_set_errno(), sys_perror(), sys_strerror()
  7093. */
  7094. sysret_t sys_get_errno(void)
  7095. {
  7096. return rt_get_errno();
  7097. }
  7098. #ifdef ARCH_MM_MMU
  7099. /**
  7100. * @brief Sets the thread-specific data area.
  7101. *
  7102. * This function is used to associate a specific area of memory with the current thread. The area pointed to
  7103. * by `p` is set as the thread's local storage. Thread-specific data is used to store data that is unique to
  7104. * each thread, allowing different threads to maintain independent state information.
  7105. *
  7106. * @param[in] p A pointer to the memory area that is to be set as the thread's local storage. This area
  7107. * will be used by the thread to store its specific data. The structure and size of the data
  7108. * area depend on the implementation and use case.
  7109. *
  7110. * @return sysret_t Returns `0` on success. On failure, it returns a negative error code.
  7111. *
  7112. * @note This function is typically used to set up thread-specific storage for managing data that should
  7113. * not be shared between threads. The data area is accessible only by the thread that set it, ensuring
  7114. * thread safety for the stored information.
  7115. *
  7116. * @see sys_get_thread_area(), sys_thread_create(), sys_thread_self()
  7117. */
  7118. sysret_t sys_set_thread_area(void *p)
  7119. {
  7120. rt_thread_t thread;
  7121. thread = rt_thread_self();
  7122. thread->thread_idr = p;
  7123. arch_set_thread_area(p);
  7124. return 0;
  7125. }
  7126. /**
  7127. * @brief Sets the address at which the thread ID is stored.
  7128. *
  7129. * This function sets the address of a variable that will store the thread ID for the calling thread.
  7130. * The specified address `tidptr` will hold the thread's unique identifier. This can be useful for
  7131. * managing thread-specific state or for synchronization mechanisms where the thread's ID needs to be
  7132. * shared or checked by other parts of the system.
  7133. *
  7134. * @param[in] tidptr A pointer to an integer where the thread ID will be stored. This value will
  7135. * hold the calling thread's ID, and it can be accessed to identify the thread
  7136. * later. The value of the thread ID can be used in various thread management
  7137. * operations.
  7138. *
  7139. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7140. *
  7141. * @note This function is typically used in systems that require associating a specific address with the
  7142. * thread ID, often in real-time or embedded systems where managing and accessing thread IDs is
  7143. * crucial for scheduling or resource allocation.
  7144. *
  7145. * @see sys_get_tid(), sys_thread_self(), sys_thread_create()
  7146. */
  7147. sysret_t sys_set_tid_address(int *tidptr)
  7148. {
  7149. rt_thread_t thread;
  7150. #ifdef ARCH_MM_MMU
  7151. if (!lwp_user_accessable((void *)tidptr, sizeof(int)))
  7152. {
  7153. return -EFAULT;
  7154. }
  7155. #endif
  7156. thread = rt_thread_self();
  7157. thread->clear_child_tid = tidptr;
  7158. return thread->tid;
  7159. }
  7160. #endif /* ARCH_MM_MMU */
  7161. /**
  7162. * @brief Gets the thread ID of the calling thread.
  7163. *
  7164. * This function returns the unique thread identifier (thread ID) for the calling thread. The thread ID
  7165. * can be used to uniquely identify the thread within the system and is typically used for debugging,
  7166. * thread management, or scheduling purposes.
  7167. *
  7168. * @return sysret_t The thread ID of the calling thread. The value is typically a positive integer
  7169. * representing the unique ID assigned to the thread. In case of failure, an error code
  7170. * may be returned.
  7171. *
  7172. * @note The thread ID returned by this function is unique within the system, and it may be used to
  7173. * reference or manipulate the specific thread associated with the ID.
  7174. *
  7175. * @see sys_set_tid_address(), sys_thread_self(), sys_thread_create()
  7176. */
  7177. sysret_t sys_gettid(void)
  7178. {
  7179. return rt_thread_self()->tid;
  7180. }
  7181. /**
  7182. * @brief Checks the accessibility of a file or directory.
  7183. *
  7184. * This function checks whether the calling process has the specified access rights for the given file or directory.
  7185. * The check is performed based on the provided `mode`, which can indicate whether read, write, or execute permissions
  7186. * are required.
  7187. *
  7188. * @param[in] filename The path to the file or directory whose accessibility is being checked.
  7189. * @param[in] mode The access mode to check for. This can be a combination of the following:
  7190. * - `R_OK`: Check for read permission.
  7191. * - `W_OK`: Check for write permission.
  7192. * - `X_OK`: Check for execute permission.
  7193. * - `F_OK`: Check if the file exists.
  7194. *
  7195. * @return sysret_t Returns `0` if the specified access is allowed. On failure, returns a negative error code.
  7196. *
  7197. * @note This function does not modify the file or directory, it only checks if the specified access rights are granted.
  7198. *
  7199. * @see sys_open(), sys_stat(), sys_fstat(), sys_chmod(), sys_chown()
  7200. */
  7201. sysret_t sys_access(const char *filename, int mode)
  7202. {
  7203. int ret = 0;
  7204. #ifdef ARCH_MM_MMU
  7205. rt_size_t len = 0;
  7206. char *kfilename = RT_NULL;
  7207. len = lwp_user_strlen(filename);
  7208. if (len <= 0)
  7209. {
  7210. return -EINVAL;
  7211. }
  7212. kfilename = (char *)kmem_get(len + 1);
  7213. if (!kfilename)
  7214. {
  7215. return -ENOMEM;
  7216. }
  7217. if (lwp_get_from_user(kfilename, (void *)filename, len + 1) != (len + 1))
  7218. {
  7219. kmem_put(kfilename);
  7220. return -EFAULT;
  7221. }
  7222. ret = access(kfilename, mode);
  7223. if (ret < 0)
  7224. {
  7225. ret = GET_ERRNO();
  7226. }
  7227. kmem_put(kfilename);
  7228. return ret;
  7229. #else
  7230. ret = access(filename, mode);
  7231. return (ret < 0 ? GET_ERRNO() : ret);
  7232. #endif
  7233. }
  7234. /**
  7235. * @brief Creates a pipe, a unidirectional data channel.
  7236. *
  7237. * This function creates a pipe, which is a unidirectional data channel used for inter-process communication.
  7238. * The pipe consists of two file descriptors: one for reading from the pipe and one for writing to the pipe.
  7239. * The pipe is used for passing data between processes or threads, typically in a producer-consumer scenario.
  7240. *
  7241. * @param[out] fd An array of two integers where the file descriptors for the read and write ends of the pipe will be stored.
  7242. * - `fd[0]`: The file descriptor for reading from the pipe.
  7243. * - `fd[1]`: The file descriptor for writing to the pipe.
  7244. *
  7245. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7246. *
  7247. * @note The pipe created by this function is typically used for simple communication between processes or threads.
  7248. * The data written to `fd[1]` can be read from `fd[0]`. After usage, both file descriptors should be closed.
  7249. *
  7250. * @see sys_read(), sys_write(), sys_close(), sys_fork(), sys_execve()
  7251. */
  7252. sysret_t sys_pipe(int fd[2])
  7253. {
  7254. int ret;
  7255. int kfd[2] = { 0, 0 };
  7256. if (!lwp_user_accessable((void *)fd, sizeof(int[2])))
  7257. {
  7258. return -EFAULT;
  7259. }
  7260. ret = pipe(kfd);
  7261. lwp_put_to_user((void *)fd, kfd, sizeof(int[2]));
  7262. return (ret < 0 ? GET_ERRNO() : ret);
  7263. }
  7264. /**
  7265. * @brief Waits for a process to change state.
  7266. *
  7267. * This function suspends the execution of the calling process until one of its child processes terminates
  7268. * or a specified process (identified by `pid`) changes its state. The function returns the process ID of the child
  7269. * process that terminated, and provides information about its exit status and resource usage.
  7270. *
  7271. * @param[in] pid The process ID of the child process to wait for. The behavior of this parameter can be one of the following:
  7272. * - `pid > 0`: Wait for the child process with the specified PID.
  7273. * - `pid == 0`: Wait for any child process in the same process group.
  7274. * - `pid == -1`: Wait for any child process (default behavior).
  7275. * - `pid < -1`: Wait for any child process in the specified process group.
  7276. *
  7277. * @param[out] status A pointer to an integer where the exit status of the terminated child process will be stored.
  7278. * This status can be interpreted using macros such as `WIFEXITED` or `WIFSIGNALED`.
  7279. *
  7280. * @param[in] options Options for the wait operation, which can include:
  7281. * - `WNOHANG`: Return immediately if no child has exited.
  7282. * - `WUNTRACED`: Return if a child has stopped, but not yet terminated.
  7283. *
  7284. * @param[out] ru A pointer to a `struct rusage` where resource usage information of the child process will be stored.
  7285. * This includes information such as CPU time consumed by the child process.
  7286. *
  7287. * @return sysret_t Returns the process ID of the terminated child on success. In case of failure, a negative error code is returned.
  7288. *
  7289. * @note This function is useful for monitoring and cleaning up child processes in parent-child relationships.
  7290. * The `status` value can be further analyzed to determine if the child process terminated normally or due to a signal.
  7291. *
  7292. * @see sys_waitpid(), sys_fork(), sys_exit()
  7293. */
  7294. sysret_t sys_wait4(pid_t pid, int *status, int options, struct rusage *ru)
  7295. {
  7296. return lwp_waitpid(pid, status, options, ru);
  7297. }
  7298. /**
  7299. * @brief Sets the time of a specified clock.
  7300. *
  7301. * This function sets the time of the specified clock (identified by `clk`) to the given value. The time is provided
  7302. * as a `struct timespec` containing seconds and nanoseconds. This function can be used to set the system clock or
  7303. * other specific clocks, such as monotonic or real-time clocks.
  7304. *
  7305. * @param[in] clk The clock ID for which to set the time. The clock can be one of the following:
  7306. * - `CLOCK_REALTIME`: Set the system's real-time clock.
  7307. * - `CLOCK_MONOTONIC`: Set the monotonic clock, which measures time since some unspecified starting point.
  7308. * - `CLOCK_PROCESS_CPUTIME_ID`: Set the CPU time used by the process.
  7309. * - `CLOCK_THREAD_CPUTIME_ID`: Set the CPU time used by the current thread.
  7310. *
  7311. * @param[in] ts A pointer to a `struct timespec` containing the new time to set for the specified clock.
  7312. * - `ts->tv_sec`: Seconds since the epoch (for `CLOCK_REALTIME`) or since some unspecified start point (for other clocks).
  7313. * - `ts->tv_nsec`: Nanoseconds within the current second.
  7314. *
  7315. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7316. *
  7317. * @note This function requires appropriate permissions for setting the system's clock. In some systems, only privileged users
  7318. * may change the `CLOCK_REALTIME` clock.
  7319. *
  7320. * @see sys_clock_gettime(), sys_clock_getres()
  7321. */
  7322. sysret_t sys_clock_settime(clockid_t clk, const struct timespec *ts)
  7323. {
  7324. int ret = 0;
  7325. #ifdef ARCH_MM_MMU
  7326. size_t size = sizeof(struct timespec);
  7327. struct timespec *kts = NULL;
  7328. if (!lwp_user_accessable((void *)ts, size))
  7329. {
  7330. return -EFAULT;
  7331. }
  7332. kts = kmem_get(size);
  7333. if (!kts)
  7334. {
  7335. return -ENOMEM;
  7336. }
  7337. lwp_get_from_user(kts, (void *)ts, size);
  7338. ret = clock_settime(clk, kts);
  7339. if (ret < 0)
  7340. {
  7341. ret = GET_ERRNO();
  7342. }
  7343. kmem_put(kts);
  7344. return ret;
  7345. #else
  7346. if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
  7347. {
  7348. return -EFAULT;
  7349. }
  7350. ret = clock_settime(clk, ts);
  7351. return (ret < 0 ? GET_ERRNO() : ret);
  7352. #endif
  7353. }
  7354. /**
  7355. * @brief Retrieves the current time of a specified clock.
  7356. *
  7357. * This function retrieves the current time of the specified clock (identified by `clk`) and stores it in the
  7358. * `struct timespec` pointed to by `ts`. The time is expressed in seconds and nanoseconds. The clock can be
  7359. * one of several types, such as real-time, monotonic, or process-specific clocks.
  7360. *
  7361. * @param[in] clk The clock ID for which to get the time. The clock can be one of the following:
  7362. * - `CLOCK_REALTIME`: Get the system's real-time clock.
  7363. * - `CLOCK_MONOTONIC`: Get the monotonic clock, which measures time since some unspecified starting point.
  7364. * - `CLOCK_PROCESS_CPUTIME_ID`: Get the CPU time used by the process.
  7365. * - `CLOCK_THREAD_CPUTIME_ID`: Get the CPU time used by the current thread.
  7366. *
  7367. * @param[out] ts A pointer to a `struct timespec` where the current time for the specified clock will be stored.
  7368. * - `ts->tv_sec`: Seconds since the epoch (for `CLOCK_REALTIME`) or since some unspecified start point (for other clocks).
  7369. * - `ts->tv_nsec`: Nanoseconds within the current second.
  7370. *
  7371. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7372. *
  7373. * @note This function requires appropriate permissions for retrieving certain clocks (e.g., `CLOCK_REALTIME`).
  7374. *
  7375. * @see sys_clock_settime(), sys_clock_getres()
  7376. */
  7377. sysret_t sys_clock_gettime(clockid_t clk, struct timespec *ts)
  7378. {
  7379. int ret = 0;
  7380. #ifdef ARCH_MM_MMU
  7381. size_t size = sizeof(struct timespec);
  7382. struct timespec *kts = NULL;
  7383. if (!lwp_user_accessable((void *)ts, size))
  7384. {
  7385. return -EFAULT;
  7386. }
  7387. kts = kmem_get(size);
  7388. if (!kts)
  7389. {
  7390. return -ENOMEM;
  7391. }
  7392. ret = clock_gettime(clk, kts);
  7393. if (ret != -1)
  7394. lwp_put_to_user(ts, kts, size);
  7395. if (ret < 0)
  7396. {
  7397. ret = GET_ERRNO();
  7398. }
  7399. kmem_put(kts);
  7400. return ret;
  7401. #else
  7402. if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
  7403. {
  7404. return -EFAULT;
  7405. }
  7406. ret = clock_gettime(clk, ts);
  7407. return (ret < 0 ? GET_ERRNO() : ret);
  7408. #endif
  7409. }
  7410. /**
  7411. * @brief Suspends the execution of the calling thread for the specified time duration.
  7412. *
  7413. * This function causes the calling thread to sleep for the specified time duration, which is provided as a
  7414. * `struct timespec` containing seconds and nanoseconds. The sleep is done based on the specified clock (identified by `clk`).
  7415. * If the `flags` parameter is set to `TIMER_ABSTIME`, the specified time represents an absolute time, otherwise,
  7416. * it represents a relative time interval.
  7417. *
  7418. * @param[in] clk The clock ID for which to perform the sleep. The clock can be one of the following:
  7419. * - `CLOCK_REALTIME`: Use the system's real-time clock.
  7420. * - `CLOCK_MONOTONIC`: Use the monotonic clock, which measures time since some unspecified starting point.
  7421. * - `CLOCK_PROCESS_CPUTIME_ID`: Use the CPU time used by the process.
  7422. * - `CLOCK_THREAD_CPUTIME_ID`: Use the CPU time used by the current thread.
  7423. *
  7424. * @param[in] flags The sleep behavior flags. The possible flags are:
  7425. * - `0`: The sleep duration is relative to the current time.
  7426. * - `TIMER_ABSTIME`: The sleep duration is absolute (measured from the specified clock).
  7427. *
  7428. * @param[in] rqtp A pointer to a `struct timespec` containing the requested sleep time.
  7429. * - `rqtp->tv_sec`: Seconds to sleep.
  7430. * - `rqtp->tv_nsec`: Nanoseconds to sleep (0 ≤ `rqtp->tv_nsec` < 1 billion).
  7431. *
  7432. * @param[out] rmtp A pointer to a `struct timespec` where the remaining time will be stored if the sleep is interrupted.
  7433. * If the sleep completes successfully, `rmtp` will not be modified.
  7434. * - `rmtp->tv_sec`: Remaining seconds.
  7435. * - `rmtp->tv_nsec`: Remaining nanoseconds.
  7436. *
  7437. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7438. *
  7439. * @note This function can be interrupted by signals. In that case, the remaining time is returned in `rmtp`.
  7440. * If the sleep is not interrupted, the function returns `SYSRET_OK` when the requested time has passed.
  7441. *
  7442. * @see sys_clock_gettime(), sys_clock_settime(), sys_nanosleep()
  7443. */
  7444. sysret_t sys_clock_nanosleep(clockid_t clk, int flags, const struct timespec *rqtp, struct timespec *rmtp)
  7445. {
  7446. int ret = 0;
  7447. LOG_D("sys_nanosleep\n");
  7448. if (!lwp_user_accessable((void *)rqtp, sizeof *rqtp))
  7449. return -EFAULT;
  7450. #ifdef ARCH_MM_MMU
  7451. struct timespec rqtp_k;
  7452. struct timespec rmtp_k;
  7453. lwp_get_from_user(&rqtp_k, (void *)rqtp, sizeof rqtp_k);
  7454. ret = clock_nanosleep(clk, flags, &rqtp_k, &rmtp_k);
  7455. if ((ret != -1 || rt_get_errno() == EINTR) && rmtp && lwp_user_accessable((void *)rmtp, sizeof *rmtp))
  7456. {
  7457. lwp_put_to_user(rmtp, (void *)&rmtp_k, sizeof rmtp_k);
  7458. if (ret != 0)
  7459. return -EINTR;
  7460. }
  7461. #else
  7462. if (rmtp)
  7463. {
  7464. if (!lwp_user_accessable((void *)rmtp, sizeof *rmtp))
  7465. return -EFAULT;
  7466. ret = clock_nanosleep(clk, flags, rqtp, rmtp);
  7467. }
  7468. #endif
  7469. return (ret < 0 ? GET_ERRNO() : ret);
  7470. }
  7471. /**
  7472. * @brief Get the resolution of the specified clock.
  7473. *
  7474. * This function retrieves the resolution of the specified clock, which is the smallest time interval that the clock can measure.
  7475. * The resolution is returned in a `struct timespec` which contains seconds and nanoseconds.
  7476. *
  7477. * @param[in] clk The clock ID for which to get the resolution. The clock can be one of the following:
  7478. * - `CLOCK_REALTIME`: System's real-time clock.
  7479. * - `CLOCK_MONOTONIC`: Monotonic clock (measures time since an unspecified point).
  7480. * - `CLOCK_PROCESS_CPUTIME_ID`: CPU time consumed by the current process.
  7481. * - `CLOCK_THREAD_CPUTIME_ID`: CPU time consumed by the current thread.
  7482. *
  7483. * @param[out] ts A pointer to a `struct timespec` where the clock's resolution will be stored.
  7484. * - `ts->tv_sec`: The number of seconds in the resolution.
  7485. * - `ts->tv_nsec`: The number of nanoseconds in the resolution (0 ≤ `ts->tv_nsec` < 1 billion).
  7486. *
  7487. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7488. *
  7489. * @note The resolution may be zero for some clocks, depending on the system's configuration.
  7490. * A clock's resolution determines the smallest unit of time the clock can measure.
  7491. *
  7492. * @see sys_clock_gettime(), sys_clock_settime(), sys_clock_nanosleep()
  7493. */
  7494. sysret_t sys_clock_getres(clockid_t clk, struct timespec *ts)
  7495. {
  7496. int ret = 0;
  7497. #ifdef ARCH_MM_MMU
  7498. struct timespec kts;
  7499. size_t size = sizeof(struct timespec);
  7500. if (!lwp_user_accessable((void *)ts, size))
  7501. {
  7502. return -EFAULT;
  7503. }
  7504. ret = clock_getres(clk, &kts);
  7505. if (ret != -1)
  7506. lwp_put_to_user(ts, &kts, size);
  7507. #else
  7508. if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
  7509. {
  7510. return -EFAULT;
  7511. }
  7512. ret = clock_getres(clk, ts);
  7513. #endif
  7514. return (ret < 0 ? GET_ERRNO() : ret);
  7515. }
  7516. /**
  7517. * @brief Rename or move a file or directory.
  7518. *
  7519. * This function renames or moves a file or directory from `oldpath` to `newpath`.
  7520. * If the `newpath` exists, it may be overwritten depending on the system's file system behavior and
  7521. * the permissions of the files involved.
  7522. *
  7523. * @param[in] oldpath The current path of the file or directory to rename or move.
  7524. * @param[in] newpath The new path or name to which the file or directory should be renamed or moved.
  7525. *
  7526. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7527. *
  7528. * @note If `oldpath` and `newpath` refer to different file systems, the behavior may vary,
  7529. * as the operation might involve copying and removing files instead of simply renaming them.
  7530. * The success of the operation also depends on the permissions of the source and destination.
  7531. *
  7532. * @see sys_unlink(), sys_mkdir(), sys_access()
  7533. */
  7534. sysret_t sys_rename(const char *oldpath, const char *newpath)
  7535. {
  7536. int ret = -1;
  7537. #ifdef ARCH_MM_MMU
  7538. int err;
  7539. err = lwp_user_strlen(oldpath);
  7540. if (err <= 0)
  7541. {
  7542. return -EFAULT;
  7543. }
  7544. err = lwp_user_strlen(newpath);
  7545. if (err <= 0)
  7546. {
  7547. return -EFAULT;
  7548. }
  7549. #endif
  7550. ret = rename(oldpath, newpath);
  7551. return (ret < 0 ? GET_ERRNO() : ret);
  7552. }
  7553. typedef unsigned long long rlim_t;
  7554. struct rlimit
  7555. {
  7556. rlim_t rlim_cur;
  7557. rlim_t rlim_max;
  7558. };
  7559. #define RLIMIT_CPU 0
  7560. #define RLIMIT_FSIZE 1
  7561. #define RLIMIT_DATA 2
  7562. #define RLIMIT_STACK 3
  7563. #define RLIMIT_CORE 4
  7564. #define RLIMIT_RSS 5
  7565. #define RLIMIT_NPROC 6
  7566. #define RLIMIT_NOFILE 7
  7567. #define RLIMIT_MEMLOCK 8
  7568. #define RLIMIT_AS 9
  7569. sysret_t sys_prlimit64(pid_t pid,
  7570. unsigned int resource,
  7571. const struct rlimit *new_rlim,
  7572. struct rlimit *old_rlim)
  7573. {
  7574. return -ENOSYS;
  7575. }
  7576. /**
  7577. * @brief Get resource limits.
  7578. *
  7579. * This function retrieves the current resource limits for the specified resource type.
  7580. * The resource limit specifies the maximum value for a particular resource that a process or thread can use.
  7581. * The limits are returned in an array `rlim` where:
  7582. * - `rlim[0]` represents the soft limit (the current value).
  7583. * - `rlim[1]` represents the hard limit (the maximum allowable value).
  7584. *
  7585. * @param[in] resource The resource for which to get the limits. It can be one of the following:
  7586. * - `RLIMIT_NOFILE`: Maximum number of file descriptors.
  7587. *
  7588. * @param[out] rlim An array to store the resource limits. The array should have at least 2 elements:
  7589. * - `rlim[0]`: The soft limit for the resource.
  7590. * - `rlim[1]`: The hard limit for the resource.
  7591. *
  7592. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7593. *
  7594. * @note The limits returned by `sys_getrlimit` are subject to system constraints and may vary across different systems.
  7595. *
  7596. * @see sys_setrlimit(), sys_getrlimit64(), sys_getrusage()
  7597. */
  7598. sysret_t sys_getrlimit(unsigned int resource, unsigned long rlim[2])
  7599. {
  7600. int ret = -1;
  7601. unsigned long krlim[2] = { 0, 0 };
  7602. if (!lwp_user_accessable((void *)rlim, sizeof(unsigned long[2])))
  7603. {
  7604. return -EFAULT;
  7605. }
  7606. if (lwp_get_from_user(krlim, rlim, sizeof(unsigned long[2])) != sizeof(unsigned long[2]))
  7607. {
  7608. return -EINVAL;
  7609. }
  7610. switch (resource)
  7611. {
  7612. case RLIMIT_NOFILE:
  7613. {
  7614. struct dfs_fdtable *fdt = dfs_fdtable_get();
  7615. dfs_file_lock();
  7616. krlim[0] = fdt->maxfd;
  7617. dfs_file_unlock();
  7618. krlim[1] = DFS_FD_MAX;
  7619. ret = 0;
  7620. }
  7621. break;
  7622. default:
  7623. return -EINVAL;
  7624. break;
  7625. }
  7626. lwp_put_to_user((void *)rlim, krlim, sizeof(unsigned long[2]));
  7627. return (ret < 0 ? GET_ERRNO() : ret);
  7628. }
  7629. sysret_t sys_setrlimit(unsigned int resource, struct rlimit *rlim)
  7630. {
  7631. return -ENOSYS;
  7632. }
  7633. /**
  7634. * @brief Get random data from the kernel's random number generator.
  7635. *
  7636. * This function retrieves cryptographically secure random data from the kernel's random number generator
  7637. * and stores it in the buffer provided by the user. The data can be used for cryptographic operations or
  7638. * other applications requiring randomization.
  7639. *
  7640. * @param[out] buf A pointer to the buffer where the random data will be stored. The buffer must be large
  7641. * enough to hold the requested amount of random data.
  7642. * @param[in] buflen The number of bytes of random data to retrieve. This value must be a positive integer.
  7643. * @param[in] flags Optional flags to modify the behavior of the random data retrieval. Possible values may include:
  7644. * - `GRND_RANDOM`: Requests random data from the system's non-blocking random source.
  7645. * - `GRND_NONBLOCK`: Instructs the function to return immediately even if insufficient entropy is available.
  7646. *
  7647. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7648. *
  7649. * @note
  7650. * - If the `GRND_NONBLOCK` flag is not set and there is insufficient entropy in the system's random pool,
  7651. * this function may block until enough entropy is available.
  7652. * - The function returns cryptographically secure random data, suitable for use in secure applications.
  7653. *
  7654. * @see sys_random(), sys_getentropy()
  7655. */
  7656. sysret_t sys_getrandom(void *buf, size_t buflen, unsigned int flags)
  7657. {
  7658. int ret = -1;
  7659. int count = 0;
  7660. void *kmem = RT_NULL;
  7661. rt_device_t rd_dev = RT_NULL;
  7662. if (flags & GRND_RANDOM)
  7663. rd_dev = rt_device_find("random");
  7664. else
  7665. rd_dev = rt_device_find("urandom");
  7666. if (rd_dev == RT_NULL)
  7667. {
  7668. return -EFAULT;
  7669. }
  7670. if (rt_device_open(rd_dev, RT_DEVICE_OFLAG_RDONLY) != RT_EOK)
  7671. {
  7672. return -EFAULT;
  7673. }
  7674. if (!lwp_user_accessable(buf, buflen))
  7675. {
  7676. rt_device_close(rd_dev);
  7677. return -EFAULT;
  7678. }
  7679. #ifdef ARCH_MM_MMU
  7680. kmem = kmem_get(buflen);
  7681. if (!kmem)
  7682. {
  7683. rt_device_close(rd_dev);
  7684. return -ENOMEM;
  7685. }
  7686. while (count < buflen)
  7687. {
  7688. ret = rt_device_read(rd_dev, count, (char *)kmem + count, buflen - count);
  7689. if (ret <= 0)
  7690. break;
  7691. count += ret;
  7692. }
  7693. rt_device_close(rd_dev);
  7694. ret = count;
  7695. if (count > 0)
  7696. {
  7697. ret = lwp_put_to_user(buf, kmem, count);
  7698. }
  7699. kmem_put(kmem);
  7700. #else
  7701. while (count < buflen)
  7702. {
  7703. ret = rt_device_read(rd_dev, count, (char *)kmem + count, buflen - count);
  7704. if (ret <= 0)
  7705. break;
  7706. count += ret;
  7707. }
  7708. rt_device_close(rd_dev);
  7709. ret = count;
  7710. #endif
  7711. return ret;
  7712. }
  7713. /**
  7714. * @brief Read the value of a symbolic link.
  7715. *
  7716. * This function reads the value of a symbolic link and stores it in the provided buffer. The value is the
  7717. * path to which the symbolic link points. If the symbolic link is too long to fit in the provided buffer,
  7718. * the function returns the number of bytes needed to store the entire path (not including the terminating null byte).
  7719. *
  7720. * @param[in] path The path of the symbolic link to read.
  7721. * @param[out] buf A buffer where the symbolic link's target will be stored. The buffer must be large enough
  7722. * to hold the path of the symbolic link.
  7723. * @param[in] bufsz The size of the buffer `buf`. It specifies the maximum number of bytes to read.
  7724. *
  7725. * @return ssize_t The number of bytes written to `buf` (excluding the terminating null byte) on success.
  7726. * On failure, it returns a negative error code:
  7727. * - `-EINVAL`: Invalid path.
  7728. * - `-ENOMEM`: Insufficient memory to read the link.
  7729. * - `-EFAULT`: Invalid address for the `buf`.
  7730. *
  7731. * @note It will (silently) truncate the contents(to a length of bufsiz characters),
  7732. * in case the buffer is too small to hold all of the contents.
  7733. *
  7734. * @see sys_symlink(), sys_lstat()
  7735. */
  7736. ssize_t sys_readlink(char *path, char *buf, size_t bufsz)
  7737. {
  7738. size_t len, copy_len;
  7739. int err, rtn;
  7740. char *copy_path;
  7741. len = lwp_user_strlen(path);
  7742. if (len <= 0)
  7743. {
  7744. return -EFAULT;
  7745. }
  7746. if (!lwp_user_accessable(buf, bufsz))
  7747. {
  7748. return -EINVAL;
  7749. }
  7750. copy_path = (char *)rt_malloc(len + 1);
  7751. if (!copy_path)
  7752. {
  7753. return -ENOMEM;
  7754. }
  7755. copy_len = lwp_get_from_user(copy_path, path, len);
  7756. copy_path[copy_len] = '\0';
  7757. char *link_fn = (char *)rt_malloc(DFS_PATH_MAX);
  7758. if (link_fn)
  7759. {
  7760. err = dfs_file_readlink(copy_path, link_fn, DFS_PATH_MAX);
  7761. if (err > 0)
  7762. {
  7763. buf[bufsz > err ? err : bufsz] = '\0';
  7764. rtn = lwp_put_to_user(buf, link_fn, bufsz > err ? err : bufsz);
  7765. }
  7766. else
  7767. {
  7768. rtn = -EIO;
  7769. }
  7770. rt_free(link_fn);
  7771. }
  7772. else
  7773. {
  7774. rtn = -ENOMEM;
  7775. }
  7776. rt_free(copy_path);
  7777. return rtn;
  7778. }
  7779. /**
  7780. * @brief Set the CPU affinity mask of a process.
  7781. *
  7782. * This function sets the CPU affinity mask for a specified process. The affinity mask determines which CPUs the
  7783. * process is allowed to execute on. The process will be restricted to the CPUs specified in the mask.
  7784. *
  7785. * @param[in] pid The process ID of the process whose CPU affinity is to be set. If the `pid` is `0`, the
  7786. * affinity of the calling process will be modified.
  7787. * @param[in] size The size (in bytes) of the CPU set, typically `sizeof(cpu_set_t)`.
  7788. * @param[in] set A pointer to the CPU set. The CPU set is a bitmask representing which CPUs the process
  7789. * is allowed to run on. The bitmask must have enough bits to cover the number of CPUs on the system.
  7790. *
  7791. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7792. *
  7793. * @note The CPU set is represented as a bitmask where each bit corresponds to a CPU. If the bit is set, the process
  7794. * can execute on that CPU. The number of CPUs is platform-dependent, and the size of `set` must be large enough
  7795. * to hold a bit for each CPU.
  7796. *
  7797. * @see sys_sched_getaffinity(), sys_setcpu()
  7798. */
  7799. sysret_t sys_sched_setaffinity(pid_t pid, size_t size, void *set)
  7800. {
  7801. void *kset = RT_NULL;
  7802. if (size <= 0 || size > sizeof(cpu_set_t))
  7803. {
  7804. return -EINVAL;
  7805. }
  7806. if (!lwp_user_accessable((void *)set, size))
  7807. return -EFAULT;
  7808. kset = kmem_get(size);
  7809. if (kset == RT_NULL)
  7810. {
  7811. return -ENOMEM;
  7812. }
  7813. if (lwp_get_from_user(kset, set, size) != size)
  7814. {
  7815. kmem_put(kset);
  7816. return -EINVAL;
  7817. }
  7818. for (int i = 0; i < size * 8; i++)
  7819. {
  7820. if (CPU_ISSET_S(i, size, kset))
  7821. {
  7822. kmem_put(kset);
  7823. /**
  7824. * yes it's tricky.
  7825. * But when we talk about 'pid' from GNU libc, it's the 'task-id'
  7826. * aka 'thread->tid' known in kernel.
  7827. */
  7828. return lwp_setaffinity(pid, i);
  7829. }
  7830. }
  7831. kmem_put(kset);
  7832. return -1;
  7833. }
  7834. /**
  7835. * @brief Get the CPU affinity mask of a process.
  7836. *
  7837. * This function retrieves the CPU affinity mask for a specified process. The affinity mask indicates which CPUs the
  7838. * process is allowed to execute on. The process can run on any of the CPUs represented by the bits set in the mask.
  7839. *
  7840. * @param[in] pid The process ID of the process whose CPU affinity is to be retrieved. If `pid` is `0`, the
  7841. * affinity mask of the calling process will be retrieved.
  7842. * @param[in] size The size (in bytes) of the CPU set, typically `sizeof(cpu_set_t)`.
  7843. * @param[out] set A pointer to a buffer where the CPU affinity mask will be stored. The mask is represented
  7844. * as a bitmask, where each bit corresponds to a CPU. The bit is set if the process can run on that CPU.
  7845. *
  7846. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7847. *
  7848. * @note The CPU set is represented as a bitmask where each bit corresponds to a CPU. If the bit is set, the process
  7849. * can execute on that CPU. The number of CPUs is platform-dependent, and the size of `set` must be large enough
  7850. * to hold a bit for each CPU.
  7851. *
  7852. * @see sys_sched_setaffinity(), sys_getcpu()
  7853. */
  7854. sysret_t sys_sched_getaffinity(const pid_t pid, size_t size, void *set)
  7855. {
  7856. #ifdef ARCH_MM_MMU
  7857. LWP_DEF_RETURN_CODE(rc);
  7858. void *mask;
  7859. struct rt_lwp *lwp;
  7860. if (size <= 0 || size > sizeof(cpu_set_t))
  7861. {
  7862. return -EINVAL;
  7863. }
  7864. if (!lwp_user_accessable(set, size))
  7865. {
  7866. return -EFAULT;
  7867. }
  7868. mask = kmem_get(size);
  7869. if (!mask)
  7870. {
  7871. return -ENOMEM;
  7872. }
  7873. CPU_ZERO_S(size, mask);
  7874. lwp_pid_lock_take();
  7875. lwp = lwp_from_pid_locked(pid);
  7876. if (!lwp)
  7877. {
  7878. rc = -ESRCH;
  7879. }
  7880. else
  7881. {
  7882. #ifdef RT_USING_SMP
  7883. if (lwp->bind_cpu == RT_CPUS_NR) /* not bind */
  7884. {
  7885. for (int i = 0; i < RT_CPUS_NR; i++)
  7886. {
  7887. CPU_SET_S(i, size, mask);
  7888. }
  7889. }
  7890. else /* set bind cpu */
  7891. {
  7892. /* TODO: only single-core bindings are now supported of rt-smart */
  7893. CPU_SET_S(lwp->bind_cpu, size, mask);
  7894. }
  7895. #else
  7896. CPU_SET_S(0, size, mask);
  7897. #endif
  7898. if (lwp_put_to_user(set, mask, size) != size)
  7899. rc = -EFAULT;
  7900. else
  7901. rc = size;
  7902. }
  7903. lwp_pid_lock_release();
  7904. kmem_put(mask);
  7905. LWP_RETURN(rc);
  7906. #else
  7907. return -1;
  7908. #endif
  7909. }
  7910. /**
  7911. * @brief Retrieve system information.
  7912. *
  7913. * This function provides details about the current state of the system, such as uptime, memory usage,
  7914. * load average, and other key statistics. The information is stored in a structure pointed to by `info`.
  7915. *
  7916. * @param[out] info A pointer to a buffer where system information will be stored. The structure should
  7917. * be compatible with the format expected by the system, typically `struct sysinfo`.
  7918. *
  7919. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7920. *
  7921. * @note The structure of `info` must be predefined and consistent with the system's expectations.
  7922. * This function does not allocate memory for `info`; the caller must provide sufficient
  7923. * memory for the structure.
  7924. */
  7925. sysret_t sys_sysinfo(void *info)
  7926. {
  7927. #ifdef ARCH_MM_MMU
  7928. struct sysinfo kinfo = { 0 };
  7929. rt_size_t total_pages = 0, free_pages = 0;
  7930. if (!lwp_user_accessable(info, sizeof(struct sysinfo)))
  7931. {
  7932. return -EFAULT;
  7933. }
  7934. kinfo.uptime = rt_tick_get_millisecond() / 1000;
  7935. /* TODO: 1, 5, and 15 minute load averages */
  7936. kinfo.loads[0] = kinfo.loads[1] = kinfo.loads[2] = rt_object_get_length(RT_Object_Class_Thread);
  7937. rt_page_get_info(&total_pages, &free_pages);
  7938. kinfo.totalram = total_pages;
  7939. kinfo.freeram = free_pages;
  7940. /* TODO: implementation procfs, here is counter the lwp number */
  7941. struct lwp_avl_struct *pids = lwp_get_pid_ary();
  7942. for (int index = 0; index < RT_LWP_MAX_NR; index++)
  7943. {
  7944. struct rt_lwp *lwp = (struct rt_lwp *)pids[index].data;
  7945. if (lwp)
  7946. {
  7947. kinfo.procs++;
  7948. }
  7949. }
  7950. rt_page_high_get_info(&total_pages, &free_pages);
  7951. kinfo.totalhigh = total_pages;
  7952. kinfo.freehigh = free_pages;
  7953. kinfo.mem_unit = ARCH_PAGE_SIZE;
  7954. if (lwp_put_to_user(info, &kinfo, sizeof(struct sysinfo)) != sizeof(struct sysinfo))
  7955. {
  7956. return -EFAULT;
  7957. }
  7958. return 0;
  7959. #else
  7960. return -1;
  7961. #endif
  7962. }
  7963. static rt_bool_t _sys_sched_priority_is_valid(int priority);
  7964. /**
  7965. * @brief Set scheduling parameters for a specific thread.
  7966. *
  7967. * This function allows setting the scheduling parameters for a thread identified by its thread ID (`tid`).
  7968. * The parameters are provided via the `param` argument, which should be a structure compatible with the
  7969. * system's scheduling policies.
  7970. *
  7971. * @param[in] tid The thread ID of the target thread for which the scheduling parameters are to be set.
  7972. * @param[in] param A pointer to a structure containing the new scheduling parameters. The structure
  7973. * typically includes fields like priority and policy.
  7974. *
  7975. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7976. *
  7977. * @note The caller must have appropriate permissions to change the scheduling parameters of the specified thread.
  7978. * The exact structure and fields of `param` depend on the system's implementation and scheduling policies.
  7979. */
  7980. sysret_t sys_sched_setparam(pid_t tid, void *param)
  7981. {
  7982. struct sched_param *sched_param = RT_NULL;
  7983. rt_thread_t thread;
  7984. int ret = -1;
  7985. if (!lwp_user_accessable(param, sizeof(struct sched_param)))
  7986. {
  7987. return -EFAULT;
  7988. }
  7989. sched_param = kmem_get(sizeof(struct sched_param));
  7990. if (sched_param == RT_NULL)
  7991. {
  7992. return -ENOMEM;
  7993. }
  7994. if (lwp_get_from_user(sched_param, param, sizeof(struct sched_param)) != sizeof(struct sched_param))
  7995. {
  7996. kmem_put(sched_param);
  7997. return -EINVAL;
  7998. }
  7999. if (!_sys_sched_priority_is_valid(sched_param->sched_priority))
  8000. {
  8001. kmem_put(sched_param);
  8002. return -EINVAL;
  8003. }
  8004. thread = lwp_tid_get_thread_and_inc_ref(tid);
  8005. if (thread)
  8006. {
  8007. ret = rt_thread_control(thread, RT_THREAD_CTRL_RESET_PRIORITY, (void *)&sched_param->sched_priority);
  8008. }
  8009. lwp_tid_dec_ref(thread);
  8010. kmem_put(sched_param);
  8011. return ret;
  8012. }
  8013. /**
  8014. * @brief Relinquish the processor voluntarily.
  8015. *
  8016. * This function causes the calling thread to yield the processor, allowing other threads
  8017. * that are ready to run to execute. The thread will be placed back into the scheduler's
  8018. * ready queue and may be rescheduled according to its priority and the system's scheduling policy.
  8019. *
  8020. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8021. *
  8022. * @note This function is typically used in cooperative multitasking scenarios or when a thread
  8023. * explicitly determines it no longer needs the processor at the moment.
  8024. */
  8025. sysret_t sys_sched_yield(void)
  8026. {
  8027. rt_thread_yield();
  8028. return 0;
  8029. }
  8030. /**
  8031. * @brief Retrieve the scheduling parameters of a specific thread.
  8032. *
  8033. * This function retrieves the scheduling parameters of the thread identified by the thread ID (`tid`).
  8034. * The retrieved parameters are stored in the structure pointed to by the `param` argument.
  8035. *
  8036. * @param[in] tid The thread ID of the target thread whose scheduling parameters are to be retrieved.
  8037. * @param[out] param A pointer to a structure where the scheduling parameters will be stored. The structure
  8038. * typically includes fields like priority and policy.
  8039. *
  8040. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8041. *
  8042. * @note The caller must have appropriate permissions to query the scheduling parameters of the specified thread.
  8043. * The exact structure and fields of `param` depend on the system's implementation and scheduling policies.
  8044. */
  8045. sysret_t sys_sched_getparam(const pid_t tid, void *param)
  8046. {
  8047. struct sched_param *sched_param = RT_NULL;
  8048. rt_thread_t thread;
  8049. int ret = -1;
  8050. if (!lwp_user_accessable(param, sizeof(struct sched_param)))
  8051. {
  8052. return -EFAULT;
  8053. }
  8054. sched_param = kmem_get(sizeof(struct sched_param));
  8055. if (sched_param == RT_NULL)
  8056. {
  8057. return -ENOMEM;
  8058. }
  8059. thread = lwp_tid_get_thread_and_inc_ref(tid);
  8060. if (thread)
  8061. {
  8062. sched_param->sched_priority = RT_SCHED_PRIV(thread).current_priority;
  8063. ret = 0;
  8064. }
  8065. lwp_tid_dec_ref(thread);
  8066. lwp_put_to_user((void *)param, sched_param, sizeof(struct sched_param));
  8067. kmem_put(sched_param);
  8068. return ret;
  8069. }
  8070. /**
  8071. * @brief Get the maximum priority for a given scheduling policy.
  8072. *
  8073. * This function retrieves the maximum priority value that can be used with the specified
  8074. * scheduling policy.
  8075. *
  8076. * @param[in] policy The scheduling policy for which to retrieve the maximum priority.
  8077. *
  8078. * @return sysret_t Returns the maximum priority value on success. On failure, returns a
  8079. * negative error code.
  8080. *
  8081. * @note The valid priority range depends on the system's configuration and the selected
  8082. * scheduling policy. The returned value represents the highest priority that can
  8083. * be assigned to a thread using the given policy.
  8084. */
  8085. sysret_t sys_sched_get_priority_max(int policy)
  8086. {
  8087. if (policy < 0)
  8088. {
  8089. SET_ERRNO(EINVAL);
  8090. return -rt_get_errno();
  8091. }
  8092. return RT_THREAD_PRIORITY_MAX;
  8093. }
  8094. /**
  8095. * @brief Get the minimum priority for a given scheduling policy.
  8096. *
  8097. * This function retrieves the minimum priority value that can be used with the specified
  8098. * scheduling policy.
  8099. *
  8100. * @param[in] policy The scheduling policy for which to retrieve the minimum priority.
  8101. *
  8102. * @return sysret_t Returns the minimum priority value on success. On failure, returns a
  8103. * negative error code.
  8104. *
  8105. * @note The valid priority range depends on the system's configuration and the selected
  8106. * scheduling policy. The returned value represents the lowest priority that can
  8107. * be assigned to a thread using the given policy.
  8108. */
  8109. sysret_t sys_sched_get_priority_min(int policy)
  8110. {
  8111. if (policy < 0)
  8112. {
  8113. SET_ERRNO(EINVAL);
  8114. return -rt_get_errno();
  8115. }
  8116. return 0;
  8117. }
  8118. static rt_bool_t _sys_sched_priority_is_valid(int priority)
  8119. {
  8120. return (priority >= 0) && (priority < RT_THREAD_PRIORITY_MAX);
  8121. }
  8122. #if defined(RT_USING_UTESTCASES) && defined(RT_USING_SMART)
  8123. rt_bool_t rt_utest_sys_sched_priority_is_valid(int priority)
  8124. {
  8125. return _sys_sched_priority_is_valid(priority);
  8126. }
  8127. #endif
  8128. /**
  8129. * @brief Set the scheduling policy and parameters for a thread.
  8130. *
  8131. * This function sets the scheduling policy and associated parameters for the specified thread.
  8132. * It allows controlling the scheduling behavior of threads.
  8133. *
  8134. * @param[in] tid The thread ID of the target thread.
  8135. * @param[in] policy The scheduling policy to be applied. Common values include:
  8136. * - `SCHED_FIFO`: First-in, first-out scheduling.
  8137. * - `SCHED_RR`: Round-robin scheduling.
  8138. * - `SCHED_OTHER`: Default or standard scheduling.
  8139. * @param[in] param Pointer to a structure containing scheduling parameters, such as priority.
  8140. * The structure type depends on the system implementation.
  8141. *
  8142. * @return sysret_t Returns 0 on success. On failure, returns a negative error code.
  8143. *
  8144. * @note This function requires appropriate permissions to modify the scheduling settings
  8145. * of another thread. For most systems, elevated privileges may be required.
  8146. * Ensure the `param` structure is properly initialized for the given `policy`.
  8147. */
  8148. sysret_t sys_sched_setscheduler(int tid, int policy, void *param)
  8149. {
  8150. sysret_t ret;
  8151. struct sched_param *sched_param = RT_NULL;
  8152. rt_thread_t thread = RT_NULL;
  8153. if (!lwp_user_accessable(param, sizeof(struct sched_param)))
  8154. {
  8155. return -EFAULT;
  8156. }
  8157. sched_param = kmem_get(sizeof(struct sched_param));
  8158. if (sched_param == RT_NULL)
  8159. {
  8160. return -ENOMEM;
  8161. }
  8162. if (lwp_get_from_user(sched_param, param, sizeof(struct sched_param)) != sizeof(struct sched_param))
  8163. {
  8164. kmem_put(sched_param);
  8165. return -EINVAL;
  8166. }
  8167. if (!_sys_sched_priority_is_valid(sched_param->sched_priority))
  8168. {
  8169. kmem_put(sched_param);
  8170. return -EINVAL;
  8171. }
  8172. thread = lwp_tid_get_thread_and_inc_ref(tid);
  8173. ret = rt_thread_control(thread, RT_THREAD_CTRL_RESET_PRIORITY, (void *)&sched_param->sched_priority);
  8174. lwp_tid_dec_ref(thread);
  8175. kmem_put(sched_param);
  8176. return ret;
  8177. }
  8178. /**
  8179. * @brief Get the scheduling policy of a thread.
  8180. *
  8181. * This function retrieves the current scheduling policy of the specified thread.
  8182. *
  8183. * @param[in] tid The thread ID of the target thread.
  8184. *
  8185. * @return sysret_t Returns the scheduling policy of the thread on success. On failure,
  8186. * returns a negative error code.
  8187. *
  8188. * @note The caller must have appropriate permissions to query the scheduling policy
  8189. * of the specified thread.
  8190. */
  8191. sysret_t sys_sched_getscheduler(int tid)
  8192. {
  8193. rt_thread_t thread = RT_NULL;
  8194. int rtn;
  8195. thread = lwp_tid_get_thread_and_inc_ref(tid);
  8196. lwp_tid_dec_ref(thread);
  8197. if (thread)
  8198. {
  8199. rtn = SCHED_RR;
  8200. }
  8201. else
  8202. {
  8203. rtn = -ESRCH;
  8204. }
  8205. return rtn;
  8206. }
  8207. /**
  8208. * @brief Flush the file descriptors' data to disk.
  8209. *
  8210. * This function flushes all modified data of the file associated with the specified
  8211. * file descriptor to disk, ensuring that any changes made to the file are committed
  8212. * to permanent storage.
  8213. *
  8214. * @param[in] fd The file descriptor associated with the file to be flushed. It should
  8215. * refer to an open file.
  8216. *
  8217. * @return sysret_t Returns `0` (0) on success. On failure, returns a negative
  8218. * error code.
  8219. *
  8220. * @note The `fsync` function ensures that all data written to the file is physically
  8221. * stored on disk, but it does not guarantee that all file metadata is flushed.
  8222. * To flush both data and metadata, `fdatasync` can be used.
  8223. */
  8224. sysret_t sys_fsync(int fd)
  8225. {
  8226. int res = fsync(fd);
  8227. if (res < 0)
  8228. res = rt_get_errno();
  8229. return res;
  8230. }
  8231. /**
  8232. * @brief Open a message queue.
  8233. *
  8234. * This function opens a message queue for communication between processes.
  8235. * It can create a new message queue or open an existing one, depending on the specified
  8236. * flags.
  8237. *
  8238. * @param[in] name The name of the message queue. The name should be a null-terminated
  8239. * string and is subject to system-specific naming conventions.
  8240. * @param[in] flags Flags that control the behavior of the message queue. Common flags include:
  8241. * - `O_CREAT`: Create the message queue if it does not exist.
  8242. * - `O_EXCL`: Fail if the message queue already exists.
  8243. * - `O_RDONLY`: Open the queue for reading.
  8244. * - `O_WRONLY`: Open the queue for writing.
  8245. * - `O_RDWR`: Open the queue for both reading and writing.
  8246. * @param[in] mode The mode to be applied when creating the message queue, which defines
  8247. * the permissions for the message queue (e.g., read, write).
  8248. * @param[in] attr A pointer to a `struct mq_attr` that defines the attributes of the
  8249. * message queue, such as the maximum number of messages and the size of
  8250. * each message. If `NULL`, default values are used.
  8251. *
  8252. * @return mqd_t Returns a non-negative file descriptor for the message queue on success.
  8253. * On failure, returns `-1` and sets `errno` to indicate the error.
  8254. *
  8255. * @note If the message queue is created, its attributes (such as the maximum number of
  8256. * messages and message size) must be defined in the `mq_attr` structure. If the
  8257. * `O_CREAT` flag is not specified and the queue does not exist, the function will
  8258. * return `-1`.
  8259. */
  8260. mqd_t sys_mq_open(const char *name, int flags, mode_t mode, struct mq_attr *attr)
  8261. {
  8262. mqd_t mqdes;
  8263. sysret_t ret = 0;
  8264. #ifdef ARCH_MM_MMU
  8265. char *kname = RT_NULL;
  8266. rt_size_t len = 0;
  8267. struct mq_attr attr_k;
  8268. len = lwp_user_strlen(name);
  8269. if (!len)
  8270. return (mqd_t)-EINVAL;
  8271. kname = (char *)kmem_get(len + 1);
  8272. if (!kname)
  8273. return (mqd_t)-ENOMEM;
  8274. if (attr == NULL)
  8275. {
  8276. attr_k.mq_maxmsg = 10;
  8277. attr_k.mq_msgsize = 8192;
  8278. attr_k.mq_flags = 0;
  8279. attr = &attr_k;
  8280. }
  8281. else
  8282. {
  8283. if (!lwp_get_from_user(&attr_k, (void *)attr, sizeof(struct mq_attr)))
  8284. return -EINVAL;
  8285. }
  8286. lwp_get_from_user(kname, (void *)name, len + 1);
  8287. mqdes = mq_open(kname, flags, mode, &attr_k);
  8288. if (mqdes == -1)
  8289. {
  8290. ret = GET_ERRNO();
  8291. }
  8292. lwp_put_to_user(attr, &attr_k, sizeof(struct mq_attr));
  8293. kmem_put(kname);
  8294. #else
  8295. mqdes = mq_open(name, flags, mode, attr);
  8296. #endif
  8297. if (mqdes == -1)
  8298. return (mqd_t)ret;
  8299. else
  8300. return mqdes;
  8301. }
  8302. /**
  8303. * @brief Remove a message queue.
  8304. *
  8305. * This function removes a message queue identified by its name. If the message queue
  8306. * is open by any process, it will be removed only when all the processes close their
  8307. * file descriptors associated with the message queue.
  8308. *
  8309. * @param[in] name The name of the message queue to be removed. It should be a null-terminated
  8310. * string that conforms to system-specific naming conventions.
  8311. *
  8312. * @return sysret_t Returns `0` on success. On failure, returns a negative
  8313. * error code.
  8314. *
  8315. * @note After a successful call, the message queue is removed from the system. However,
  8316. * the removal will not take effect until all processes close their file descriptors
  8317. * associated with the queue. The function will fail if the message queue is still
  8318. * open by other processes.
  8319. */
  8320. sysret_t sys_mq_unlink(const char *name)
  8321. {
  8322. int ret = 0;
  8323. #ifdef ARCH_MM_MMU
  8324. char *kname = RT_NULL;
  8325. rt_size_t len = 0;
  8326. len = lwp_user_strlen(name);
  8327. if (!len)
  8328. return -EINVAL;
  8329. kname = (char *)kmem_get(len + 1);
  8330. if (!kname)
  8331. return -ENOMEM;
  8332. lwp_get_from_user(kname, (void *)name, len + 1);
  8333. ret = mq_unlink(kname);
  8334. if (ret < 0)
  8335. {
  8336. ret = GET_ERRNO();
  8337. }
  8338. kmem_put(kname);
  8339. return ret;
  8340. #else
  8341. ret = mq_unlink(name);
  8342. return (ret < 0 ? GET_ERRNO() : ret);
  8343. #endif
  8344. }
  8345. /**
  8346. * @brief Send a message to a message queue with a timeout.
  8347. *
  8348. * This function sends a message to the specified message queue, but it allows the sender
  8349. * to specify a timeout. If the message queue is full, the function will block until either
  8350. * space becomes available or the specified timeout expires. If the timeout expires without
  8351. * space being available, the function returns an error.
  8352. *
  8353. * @param[in] mqd The message queue descriptor returned by `sys_mq_open`.
  8354. * @param[in] msg A pointer to the message to be sent.
  8355. * @param[in] len The length of the message to send.
  8356. * @param[in] prio The priority of the message (higher values indicate higher priority).
  8357. * @param[in] at A pointer to a `timespec` structure that specifies the absolute timeout.
  8358. * If the timeout expires before the message can be sent, the function returns
  8359. * an error.
  8360. *
  8361. * @return sysret_t Returns `0` on success. On failure, returns a negative error
  8362. * code.
  8363. *
  8364. * @note The function uses the `timespec` structure to specify the absolute timeout. The
  8365. * `at` parameter should indicate the time at which the operation should time out.
  8366. * If the timeout is `NULL`, the function will not apply any timeout (it will block
  8367. * indefinitely until the message is sent).
  8368. *
  8369. * @see sys_mq_send
  8370. */
  8371. sysret_t sys_mq_timedsend(mqd_t mqd, const char *msg, size_t len, unsigned prio, const struct timespec *at)
  8372. {
  8373. int ret = 0;
  8374. #ifdef ARCH_MM_MMU
  8375. char *kmsg = RT_NULL;
  8376. struct timespec at_k;
  8377. kmsg = (char *)kmem_get(len + 1);
  8378. if (!kmsg)
  8379. return -ENOMEM;
  8380. lwp_get_from_user(&at_k, (void *)at, sizeof(struct timespec));
  8381. lwp_get_from_user(kmsg, (void *)msg, len + 1);
  8382. ret = mq_timedsend(mqd, kmsg, len, prio, &at_k);
  8383. if (ret < 0)
  8384. {
  8385. ret = GET_ERRNO();
  8386. }
  8387. kmem_put(kmsg);
  8388. return ret;
  8389. #else
  8390. ret = mq_timedsend(mqd, msg, len, prio, at);
  8391. return (ret < 0 ? GET_ERRNO() : ret);
  8392. #endif
  8393. }
  8394. /**
  8395. * @brief Receive a message from a message queue with a timeout.
  8396. *
  8397. * This function attempts to receive a message from the specified message queue, but it
  8398. * allows the receiver to specify a timeout. If the queue is empty, the function will block
  8399. * until either a message becomes available or the specified timeout expires. If the timeout
  8400. * expires without receiving a message, the function returns an error.
  8401. *
  8402. * @param[in] mqd The message queue descriptor returned by `sys_mq_open`.
  8403. * @param[out] msg A pointer to the buffer where the received message will be stored.
  8404. * @param[in] len The maximum length of the buffer to store the received message.
  8405. * @param[out] prio A pointer to an unsigned integer that will be set to the priority
  8406. * of the received message.
  8407. * @param[in] at A pointer to a `timespec` structure that specifies the absolute timeout.
  8408. * If the timeout expires before a message is received, the function will
  8409. * return an error.
  8410. *
  8411. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8412. *
  8413. * @note The function uses the `timespec` structure to specify the absolute timeout. The
  8414. * `at` parameter should indicate the time at which the operation should time out.
  8415. * If the timeout is `NULL`, the function will block indefinitely until a message is
  8416. * received.
  8417. *
  8418. * @see sys_mq_receive
  8419. */
  8420. sysret_t sys_mq_timedreceive(mqd_t mqd, char * restrict msg, size_t len, unsigned * restrict prio, const struct timespec * restrict at)
  8421. {
  8422. int ret = 0;
  8423. #ifdef ARCH_MM_MMU
  8424. char * restrict kmsg = RT_NULL;
  8425. struct timespec at_k;
  8426. kmsg = (char * restrict)kmem_get(len + 1);
  8427. if (!kmsg)
  8428. return -ENOMEM;
  8429. lwp_get_from_user(kmsg, (void *)msg, len + 1);
  8430. if (at == RT_NULL)
  8431. {
  8432. ret = mq_timedreceive(mqd, kmsg, len, prio, RT_NULL);
  8433. }
  8434. else
  8435. {
  8436. if (!lwp_get_from_user(&at_k, (void *)at, sizeof(struct timespec)))
  8437. return -EINVAL;
  8438. ret = mq_timedreceive(mqd, kmsg, len, prio, &at_k);
  8439. }
  8440. if (ret > 0)
  8441. lwp_put_to_user(msg, kmsg, len + 1);
  8442. if (ret < 0)
  8443. {
  8444. ret = GET_ERRNO();
  8445. }
  8446. kmem_put(kmsg);
  8447. return ret;
  8448. #else
  8449. ret = mq_timedreceive(mqd, msg, len, prio, at);
  8450. return (ret < 0 ? GET_ERRNO() : ret);
  8451. #endif
  8452. }
  8453. /**
  8454. * @brief Set up asynchronous notification for a message queue.
  8455. *
  8456. * This function configures asynchronous notification for a message queue. When a message
  8457. * is available in the queue, the system can notify the calling process through a signal
  8458. * or another method specified in the `sigevent` structure. This is typically used to allow
  8459. * a process to be notified when a message arrives without having to block in the receive call.
  8460. *
  8461. * @param[in] mqd The message queue descriptor returned by `sys_mq_open`.
  8462. * @param[in] sev A pointer to a `sigevent` structure that specifies the notification
  8463. * mechanism to be used when a message is received. It could include
  8464. * signals or other notification types such as event flags or message passing.
  8465. *
  8466. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8467. *
  8468. * @note This function enables asynchronous notification, but the specific behavior depends
  8469. * on the configuration specified in the `sev` parameter, which could involve signals
  8470. * or other forms of notification.
  8471. *
  8472. * @see sys_mq_send, sys_mq_timedreceive
  8473. */
  8474. sysret_t sys_mq_notify(mqd_t mqd, const struct sigevent *sev)
  8475. {
  8476. int ret = 0;
  8477. #ifdef ARCH_MM_MMU
  8478. struct sigevent sev_k;
  8479. lwp_get_from_user(&sev_k, (void *)sev, sizeof(struct timespec));
  8480. ret = mq_notify(mqd, &sev_k);
  8481. #else
  8482. ret = mq_notify(mqd, sev);
  8483. #endif
  8484. return (ret < 0 ? GET_ERRNO() : ret);
  8485. }
  8486. /**
  8487. * @brief Get or set attributes of a message queue.
  8488. *
  8489. * This function allows you to get or set the attributes of an existing message queue.
  8490. * If the `new` attribute structure is non-NULL, it updates the message queue with the new
  8491. * attributes. Otherwise, If the `old` attribute structure is non-NULL, it will return the current
  8492. * attributes of the message queue.
  8493. *
  8494. * @param[in] mqd The message queue descriptor returned by `sys_mq_open`.
  8495. * @param[in] new A pointer to a `mq_attr` structure containing the new attributes to set.
  8496. * If `NULL`, the function will not modify the message queue attributes.
  8497. * @param[out] old A pointer to a `mq_attr` structure where the current message queue
  8498. * attributes will be returned. If `NULL`, the current attributes will not
  8499. * be returned.
  8500. *
  8501. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8502. *
  8503. * @note The `mq_attr` structure contains parameters like the maximum number of messages,
  8504. * the maximum message size, and other attributes that control the behavior of the
  8505. * message queue.
  8506. *
  8507. * @see sys_mq_open, sys_mq_notify
  8508. */
  8509. sysret_t sys_mq_getsetattr(mqd_t mqd, const struct mq_attr * restrict new, struct mq_attr * restrict old)
  8510. {
  8511. int ret = 0;
  8512. #ifdef ARCH_MM_MMU
  8513. size_t size = sizeof(struct mq_attr);
  8514. struct mq_attr * restrict knew = NULL;
  8515. struct mq_attr * restrict kold = NULL;
  8516. if (new != RT_NULL)
  8517. {
  8518. if (!lwp_user_accessable((void *)new, size))
  8519. return -EFAULT;
  8520. knew = kmem_get(size);
  8521. if (!knew)
  8522. return -ENOMEM;
  8523. lwp_get_from_user(knew, (void *)new, size);
  8524. }
  8525. if (!lwp_user_accessable((void *)old, size))
  8526. return -EFAULT;
  8527. kold = kmem_get(size);
  8528. if (!kold)
  8529. return -ENOMEM;
  8530. lwp_get_from_user(kold, (void *)old, size);
  8531. ret = mq_setattr(mqd, knew, kold);
  8532. if (ret != -1)
  8533. lwp_put_to_user(old, kold, size);
  8534. if (ret < 0)
  8535. {
  8536. ret = GET_ERRNO();
  8537. }
  8538. kmem_put(kold);
  8539. if (new != RT_NULL)
  8540. kmem_put(knew);
  8541. return ret;
  8542. #else
  8543. ret = mq_setattr(mqd, new, old);
  8544. return (ret < 0 ? GET_ERRNO() : ret);
  8545. #endif
  8546. }
  8547. /**
  8548. * @brief Close a message queue descriptor.
  8549. *
  8550. * This function closes a message queue descriptor. After calling this function, the
  8551. * descriptor can no longer be used to interact with the message queue. Any resources
  8552. * associated with the descriptor are released. If the message queue was opened with the
  8553. * `O_CLOEXEC` flag, it will be automatically closed when the calling process executes
  8554. * an `exec` system call.
  8555. *
  8556. * @param[in] mqd The message queue descriptor to be closed. It was previously returned
  8557. * by `sys_mq_open`.
  8558. *
  8559. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8560. *
  8561. * @see sys_mq_open, sys_mq_unlink
  8562. */
  8563. sysret_t sys_mq_close(mqd_t mqd)
  8564. {
  8565. int ret = 0;
  8566. #ifdef ARCH_MM_MMU
  8567. ret = mq_close(mqd);
  8568. #else
  8569. ret = mq_close(mqd);
  8570. #endif
  8571. return (ret < 0 ? GET_ERRNO() : ret);
  8572. }
  8573. #define ICACHE (1 << 0)
  8574. #define DCACHE (1 << 1)
  8575. #define BCACHE (ICACHE | DCACHE)
  8576. /**
  8577. * @brief Flush the cache for a specified memory region.
  8578. *
  8579. * This function flushes the cache for a specified memory region. It is commonly used
  8580. * to ensure that the contents of a memory region are written back to the main memory
  8581. * or that stale cache entries are invalidated. The cache operation can be controlled
  8582. * by the `cache` parameter to determine whether to clean or invalidate the cache.
  8583. *
  8584. * @param[in] addr The starting address of the memory region to flush.
  8585. * @param[in] size The size of the memory region to flush, in bytes.
  8586. * @param[in] cache A flag to specify the cache operation:
  8587. * - `CACHE_CLEAN`: Clean the cache (write back to memory).
  8588. * - `CACHE_INVALIDATE`: Invalidate the cache (discard cached data).
  8589. * - `CACHE_FLUSH`: Both clean and invalidate the cache.
  8590. *
  8591. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8592. *
  8593. * @note This function is typically used in low-level operations or in systems where
  8594. * cache coherence between memory and cache is critical.
  8595. */
  8596. rt_weak sysret_t sys_cacheflush(void *addr, int size, int cache)
  8597. {
  8598. if (!lwp_user_accessable(addr, size))
  8599. return -EFAULT;
  8600. if (((size_t)addr < (size_t)addr + size) &&
  8601. ((size_t)addr >= USER_VADDR_START) &&
  8602. ((size_t)addr + size < USER_VADDR_TOP))
  8603. {
  8604. if ((cache & DCACHE))
  8605. {
  8606. rt_hw_cpu_dcache_clean_and_invalidate(addr, size);
  8607. }
  8608. if ((cache & ICACHE))
  8609. {
  8610. rt_hw_cpu_icache_invalidate(addr, size);
  8611. }
  8612. return 0;
  8613. }
  8614. return -EFAULT;
  8615. }
  8616. /**
  8617. * @brief Get system information.
  8618. *
  8619. * This function retrieves information about the current system, such as the system name,
  8620. * version, release, architecture, and other details. The information is stored in the
  8621. * `utsname` structure pointed to by the `uts` parameter.
  8622. *
  8623. * @param[out] uts A pointer to a `utsname` structure where the system information will
  8624. * be stored. The structure includes fields such as:
  8625. * - `sysname`: Operating system name.
  8626. * - `nodename`: Network node hostname.
  8627. * - `release`: Operating system release version.
  8628. * - `version`: Operating system version.
  8629. * - `machine`: Hardware identifier (architecture).
  8630. *
  8631. * @return sysret_t Returns `SYSRET_OK` (0) on success. On failure, returns a negative error code.
  8632. *
  8633. * @note This function provides details about the system environment, which may be useful
  8634. * for applications needing to adapt to different system configurations.
  8635. *
  8636. * @see sys_gethostname, sys_uname
  8637. */
  8638. sysret_t sys_uname(struct utsname *uts)
  8639. {
  8640. struct utsname utsbuff = { 0 };
  8641. int ret = 0;
  8642. const char *machine;
  8643. if (!lwp_user_accessable((void *)uts, sizeof(struct utsname)))
  8644. {
  8645. return -EFAULT;
  8646. }
  8647. rt_strncpy(utsbuff.sysname, "RT-Thread", sizeof(utsbuff.sysname));
  8648. utsbuff.nodename[0] = '\0';
  8649. ret = rt_snprintf(utsbuff.release, sizeof(utsbuff.release), "%u.%u.%u",
  8650. RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH);
  8651. if (ret < 0)
  8652. {
  8653. return -EIO;
  8654. }
  8655. ret = rt_snprintf(utsbuff.version, sizeof(utsbuff.version), "RT-Thread %u.%u.%u %s %s",
  8656. RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH, __DATE__, __TIME__);
  8657. if (ret < 0)
  8658. {
  8659. return -EIO;
  8660. }
  8661. machine = rt_hw_cpu_arch();
  8662. rt_strncpy(utsbuff.machine, machine, sizeof(utsbuff.machine));
  8663. utsbuff.domainname[0] = '\0';
  8664. lwp_put_to_user(uts, &utsbuff, sizeof utsbuff);
  8665. return 0;
  8666. }
  8667. /**
  8668. * @brief Get filesystem statistics.
  8669. *
  8670. * This function retrieves statistics about the filesystem at the specified path,
  8671. * storing the results in the provided `statfs` structure. It can be used to obtain
  8672. * information such as the total number of blocks, free blocks, available inodes, etc.
  8673. *
  8674. * @param[in] path The path to the filesystem to query. If the path is the root directory
  8675. * (`"/"`), it returns statistics for the root filesystem.
  8676. * @param[out] buf A pointer to a `statfs` structure where the filesystem statistics will
  8677. * be stored. This structure includes information such as:
  8678. * - `f_type`: The type of the filesystem.
  8679. * - `f_bsize`: The optimal block size for I/O operations.
  8680. * - `f_blocks`: Total number of blocks in the filesystem.
  8681. * - `f_bfree`: Number of free blocks.
  8682. * - `f_bavail`: Number of free blocks available to non-superuser.
  8683. * - `f_files`: Total number of file nodes (inodes).
  8684. * - `f_ffree`: Number of free inodes.
  8685. * - `f_favail`: Number of inodes available to non-superuser.
  8686. * - `f_flag`: Flags describing the filesystem.
  8687. * - `f_namelen`: Maximum length of a filename.
  8688. *
  8689. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8690. *
  8691. * @note This function is useful for determining the available space and file system
  8692. * characteristics of a mounted filesystem.
  8693. *
  8694. * @see sys_fstatfs
  8695. */
  8696. sysret_t sys_statfs(const char *path, struct statfs *buf)
  8697. {
  8698. int ret = 0;
  8699. size_t len;
  8700. size_t copy_len;
  8701. char *copy_path;
  8702. struct statfs statfsbuff = { 0 };
  8703. if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
  8704. {
  8705. return -EFAULT;
  8706. }
  8707. len = lwp_user_strlen(path);
  8708. if (len <= 0)
  8709. {
  8710. return -EFAULT;
  8711. }
  8712. copy_path = (char *)rt_malloc(len + 1);
  8713. if (!copy_path)
  8714. {
  8715. return -ENOMEM;
  8716. }
  8717. copy_len = lwp_get_from_user(copy_path, (void *)path, len);
  8718. if (copy_len == 0)
  8719. {
  8720. rt_free(copy_path);
  8721. return -EFAULT;
  8722. }
  8723. copy_path[copy_len] = '\0';
  8724. ret = _SYS_WRAP(statfs(copy_path, &statfsbuff));
  8725. rt_free(copy_path);
  8726. if (ret == 0)
  8727. {
  8728. lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
  8729. }
  8730. return ret;
  8731. }
  8732. /**
  8733. * @brief Get extended filesystem statistics (64-bit).
  8734. *
  8735. * This function retrieves extended statistics about the filesystem at the specified path,
  8736. * using 64-bit values for larger filesystems or filesystems with a large number of blocks or inodes.
  8737. * The information is stored in the provided `statfs` structure, which includes details such as total
  8738. * blocks, free blocks, available inodes, etc.
  8739. *
  8740. * @param[in] path The path to the filesystem to query. Typically, this would be the root directory
  8741. * (`"/"`) for the root filesystem, or any other directory on the filesystem.
  8742. * @param[in] sz The size of the `statfs` structure. This parameter allows for future extensions
  8743. * of the `statfs` structure without breaking compatibility with older applications.
  8744. * @param[out] buf A pointer to a `statfs` structure where the extended filesystem statistics
  8745. * will be stored. This structure includes information such as:
  8746. * - `f_bsize`: The optimal block size for I/O operations.
  8747. * - `f_blocks`: Total number of blocks in the filesystem.
  8748. * - `f_bfree`: Number of free blocks.
  8749. * - `f_bavail`: Number of free blocks available to non-superuser.
  8750. *
  8751. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8752. *
  8753. * @note This function is particularly useful for querying large filesystems or filesystems with
  8754. * 64-bit addresses or data values, and is an extended version of the standard `sys_statfs`.
  8755. *
  8756. * @see sys_statfs
  8757. */
  8758. sysret_t sys_statfs64(const char *path, size_t sz, struct statfs *buf)
  8759. {
  8760. int ret = 0;
  8761. size_t len;
  8762. size_t copy_len;
  8763. char *copy_path;
  8764. struct statfs statfsbuff = { 0 };
  8765. if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
  8766. {
  8767. return -EFAULT;
  8768. }
  8769. if (sz != sizeof(struct statfs))
  8770. {
  8771. return -EINVAL;
  8772. }
  8773. len = lwp_user_strlen(path);
  8774. if (len <= 0)
  8775. {
  8776. return -EFAULT;
  8777. }
  8778. copy_path = (char *)rt_malloc(len + 1);
  8779. if (!copy_path)
  8780. {
  8781. return -ENOMEM;
  8782. }
  8783. copy_len = lwp_get_from_user(copy_path, (void *)path, len);
  8784. if (copy_len == 0)
  8785. {
  8786. rt_free(copy_path);
  8787. return -EFAULT;
  8788. }
  8789. copy_path[copy_len] = '\0';
  8790. ret = _SYS_WRAP(statfs(copy_path, &statfsbuff));
  8791. rt_free(copy_path);
  8792. if (ret == 0)
  8793. {
  8794. lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
  8795. }
  8796. return ret;
  8797. }
  8798. /**
  8799. * @brief Get filesystem statistics for a file descriptor.
  8800. *
  8801. * This function retrieves statistics about the filesystem containing the file referred to by the
  8802. * file descriptor `fd`. The information is stored in the provided `statfs` structure, which includes
  8803. * details such as total blocks, free blocks, available inodes, etc.
  8804. *
  8805. * @param[in] fd The file descriptor referring to an open file. The file descriptor must be
  8806. * valid and represent a file on a mounted filesystem.
  8807. * @param[out] buf A pointer to a `statfs` structure where the filesystem statistics will be
  8808. * stored. This structure includes information such as:
  8809. * - `f_bsize`: The optimal block size for I/O operations.
  8810. * - `f_blocks`: Total number of blocks in the filesystem.
  8811. * - `f_bfree`: Number of free blocks.
  8812. * - `f_bavail`: Number of free blocks available to non-superuser.
  8813. *
  8814. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8815. *
  8816. * @note This function is useful for obtaining filesystem information about a specific file
  8817. * represented by its file descriptor, rather than querying the filesystem associated with
  8818. * a specific path.
  8819. *
  8820. * @see sys_statfs
  8821. */
  8822. sysret_t sys_fstatfs(int fd, struct statfs *buf)
  8823. {
  8824. int ret = 0;
  8825. struct statfs statfsbuff = { 0 };
  8826. if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
  8827. {
  8828. return -EFAULT;
  8829. }
  8830. ret = _SYS_WRAP(fstatfs(fd, &statfsbuff));
  8831. if (ret == 0)
  8832. {
  8833. lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
  8834. }
  8835. return ret;
  8836. }
  8837. /**
  8838. * @brief Get 64-bit filesystem statistics for a file descriptor.
  8839. *
  8840. * This function retrieves 64-bit statistics about the filesystem containing the file referred to by
  8841. * the file descriptor `fd`. The statistics are stored in the provided `statfs` structure, which
  8842. * includes details such as total blocks, free blocks, available inodes, etc. The function differs
  8843. * from `sys_fstatfs` in that it supports 64-bit values for filesystem sizes and counts.
  8844. *
  8845. * @param[in] fd The file descriptor referring to an open file. The file descriptor must be
  8846. * valid and represent a file on a mounted filesystem.
  8847. * @param[in] sz The size of the `statfs` structure (typically used to ensure compatibility with
  8848. * different versions of the structure).
  8849. * @param[out] buf A pointer to a `statfs` structure where the filesystem statistics will be
  8850. * stored. This structure includes information such as:
  8851. * - `f_bsize`: The optimal block size for I/O operations.
  8852. * - `f_blocks`: Total number of blocks in the filesystem (64-bit).
  8853. * - `f_bfree`: Number of free blocks (64-bit).
  8854. * - `f_bavail`: Number of free blocks available to non-superuser (64-bit).
  8855. *
  8856. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8857. * @note This function is particularly useful for systems supporting 64-bit filesystem statistics.
  8858. * It provides extended accuracy for large filesystems, including those with very large
  8859. * numbers of blocks or inodes.
  8860. *
  8861. * @see sys_fstatfs
  8862. */
  8863. sysret_t sys_fstatfs64(int fd, size_t sz, struct statfs *buf)
  8864. {
  8865. int ret = 0;
  8866. struct statfs statfsbuff = { 0 };
  8867. if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
  8868. {
  8869. return -EFAULT;
  8870. }
  8871. if (sz != sizeof(struct statfs))
  8872. {
  8873. return -EINVAL;
  8874. }
  8875. ret = _SYS_WRAP(fstatfs(fd, &statfsbuff));
  8876. if (ret == 0)
  8877. {
  8878. lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
  8879. }
  8880. return ret;
  8881. }
  8882. static char *_cp_from_usr_string(char *dst, char *src, size_t length)
  8883. {
  8884. char *rc;
  8885. size_t copied_bytes;
  8886. if (length)
  8887. {
  8888. copied_bytes = lwp_get_from_user(dst, src, length);
  8889. dst[copied_bytes] = '\0';
  8890. rc = dst;
  8891. }
  8892. else
  8893. {
  8894. rc = RT_NULL;
  8895. }
  8896. return rc;
  8897. }
  8898. /**
  8899. * @brief Mount a filesystem.
  8900. *
  8901. * This function mounts a filesystem onto a specified directory. It allows for mounting various
  8902. * types of filesystems, including but not limited to `ext4`, `nfs`, and `tmpfs`. The function
  8903. * allows the specification of the source device, the target mount point, and additional parameters
  8904. * such as filesystem type, mount flags, and extra data.
  8905. *
  8906. * @param[in] source The source of the filesystem, which can be a device (e.g., `/dev/sda1`)
  8907. * or a network resource (e.g., a NFS share). For certain filesystems like
  8908. * `tmpfs`, this can be `NULL`.
  8909. * @param[in] target The target directory where the filesystem will be mounted.
  8910. * This should be an existing empty directory.
  8911. * @param[in] filesystemtype The type of filesystem to mount, e.g., `ext4`, `tmpfs`, `nfs`, etc.
  8912. * @param[in] mountflags Flags that control the mount operation, such as `MS_RDONLY` for read-only
  8913. * mounts or `MS_NODEV` to prevent device files from being created.
  8914. * @param[in] data Optional data that is passed to the filesystem's mount handler. This
  8915. * may be used for setting up specific parameters for the filesystem type.
  8916. *
  8917. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8918. *
  8919. * @note Mounting a filesystem on an existing mount point can replace the existing filesystem at that
  8920. * location. Make sure the target directory is empty before mounting to avoid any conflicts.
  8921. */
  8922. sysret_t sys_mount(char *source, char *target, char *filesystemtype,
  8923. unsigned long mountflags, void *data)
  8924. {
  8925. char *kbuffer, *ksource, *ktarget, *kfs;
  8926. size_t len_source, len_target, len_fs;
  8927. char *tmp = NULL;
  8928. int ret = 0;
  8929. struct stat buf = { 0 };
  8930. char *dev_fullpath = RT_NULL;
  8931. len_source = source ? lwp_user_strlen(source) : 0;
  8932. if (len_source < 0)
  8933. return -EINVAL;
  8934. len_target = target ? lwp_user_strlen(target) : 0;
  8935. if (len_target <= 0)
  8936. return -EINVAL;
  8937. len_fs = filesystemtype ? lwp_user_strlen(filesystemtype) : 0;
  8938. if (len_fs < 0)
  8939. return -EINVAL;
  8940. kbuffer = (char *)rt_malloc(len_source + 1 + len_target + 1 + len_fs + 1);
  8941. if (!kbuffer)
  8942. {
  8943. return -ENOMEM;
  8944. }
  8945. /* get parameters from user space */
  8946. ksource = kbuffer;
  8947. ktarget = ksource + len_source + 1;
  8948. kfs = ktarget + len_target + 1;
  8949. ksource = _cp_from_usr_string(ksource, source, len_source);
  8950. ktarget = _cp_from_usr_string(ktarget, target, len_target);
  8951. kfs = _cp_from_usr_string(kfs, filesystemtype, len_fs);
  8952. if (mountflags & MS_REMOUNT)
  8953. {
  8954. ret = dfs_remount(ktarget, mountflags, data);
  8955. }
  8956. else
  8957. {
  8958. if (strcmp(kfs, "nfs") == 0)
  8959. {
  8960. tmp = ksource;
  8961. ksource = NULL;
  8962. }
  8963. if (strcmp(kfs, "tmp") == 0)
  8964. {
  8965. ksource = NULL;
  8966. }
  8967. if (ksource && !dfs_file_stat(ksource, &buf) && S_ISBLK(buf.st_mode))
  8968. {
  8969. dev_fullpath = dfs_normalize_path(RT_NULL, ksource);
  8970. RT_ASSERT(rt_strncmp(dev_fullpath, "/dev/", sizeof("/dev/") - 1) == 0);
  8971. ret = dfs_mount(dev_fullpath + sizeof("/dev/") - 1, ktarget, kfs, 0, tmp);
  8972. }
  8973. else
  8974. {
  8975. ret = dfs_mount(ksource, ktarget, kfs, 0, tmp);
  8976. }
  8977. if (ret < 0)
  8978. {
  8979. ret = -rt_get_errno();
  8980. }
  8981. }
  8982. rt_free(kbuffer);
  8983. rt_free(dev_fullpath);
  8984. return ret;
  8985. }
  8986. /**
  8987. * @brief Unmount a filesystem.
  8988. *
  8989. * This function unmounts a previously mounted filesystem from a specified target directory or file.
  8990. * It removes the filesystem from the system, making the resources associated with it available for
  8991. * other uses. It can also support additional flags to control the unmounting behavior.
  8992. *
  8993. * @param[in] __special_file The target directory or mount point from which the filesystem is to be
  8994. * unmounted. This should be a valid mount point that was previously mounted.
  8995. * @param[in] __flags Flags that control the unmounting behavior. Common flags include:
  8996. * - `MNT_FORCE`: Forces the unmount even if the filesystem is busy.
  8997. * - `MNT_DETACH`: Detaches the filesystem, allowing it to be unmounted
  8998. * asynchronously.
  8999. *
  9000. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  9001. *
  9002. * @note The `MNT_FORCE` flag should be used with caution, as it may result in data loss or corruption
  9003. * if there are pending writes or active processes using the filesystem.
  9004. *
  9005. * @see sys_mount
  9006. */
  9007. sysret_t sys_umount2(char *__special_file, int __flags)
  9008. {
  9009. char *copy_special_file;
  9010. size_t len_special_file, copy_len_special_file;
  9011. int ret = 0;
  9012. len_special_file = lwp_user_strlen(__special_file);
  9013. if (len_special_file <= 0)
  9014. {
  9015. return -EFAULT;
  9016. }
  9017. copy_special_file = (char *)rt_malloc(len_special_file + 1);
  9018. if (!copy_special_file)
  9019. {
  9020. return -ENOMEM;
  9021. }
  9022. copy_len_special_file = lwp_get_from_user(copy_special_file, __special_file, len_special_file);
  9023. copy_special_file[copy_len_special_file] = '\0';
  9024. ret = dfs_unmount(copy_special_file);
  9025. rt_free(copy_special_file);
  9026. return ret;
  9027. }
  9028. /**
  9029. * @brief Create a new hard link to an existing file.
  9030. *
  9031. * This function creates a new hard link to an existing file, making the file accessible from
  9032. * multiple filenames. The new link points to the same inode as the existing file, meaning
  9033. * both names refer to the same underlying data. The link count for the file is incremented.
  9034. *
  9035. * @param[in] existing The path to the existing file. It must be an absolute or relative path
  9036. * to a file that already exists.
  9037. * @param[in] new The path to the new link to be created. This can be a new filename or
  9038. * an existing directory where the link will be placed.
  9039. *
  9040. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  9041. *
  9042. * @note Hard links share the same inode number, meaning changes to the data of the file via one
  9043. * link will be reflected in all hard links. Deleting any of the links will not remove the
  9044. * file data until all links are deleted.
  9045. */
  9046. sysret_t sys_link(const char *existing, const char *new)
  9047. {
  9048. int ret = -1;
  9049. int err = 0;
  9050. #ifdef RT_USING_DFS_V2
  9051. #ifdef ARCH_MM_MMU
  9052. int len = 0;
  9053. char *kexisting = RT_NULL;
  9054. char *knew = RT_NULL;
  9055. len = lwp_user_strlen(existing);
  9056. if (len <= 0)
  9057. {
  9058. return -EFAULT;
  9059. }
  9060. kexisting = (char *)kmem_get(len + 1);
  9061. if (!kexisting)
  9062. {
  9063. return -ENOMEM;
  9064. }
  9065. if (lwp_get_from_user(kexisting, (void *)existing, len + 1) != (len + 1))
  9066. {
  9067. kmem_put(kexisting);
  9068. return -EINVAL;
  9069. }
  9070. len = lwp_user_strlen(new);
  9071. if (len <= 0)
  9072. {
  9073. kmem_put(kexisting);
  9074. return -EFAULT;
  9075. }
  9076. knew = (char *)kmem_get(len + 1);
  9077. if (!knew)
  9078. {
  9079. kmem_put(kexisting);
  9080. return -ENOMEM;
  9081. }
  9082. if (lwp_get_from_user(knew, (void *)new, len + 1) != (len + 1))
  9083. {
  9084. kmem_put(knew);
  9085. kmem_put(kexisting);
  9086. return -EINVAL;
  9087. }
  9088. ret = dfs_file_link(kexisting, knew);
  9089. if (ret < 0)
  9090. {
  9091. err = GET_ERRNO();
  9092. }
  9093. kmem_put(knew);
  9094. kmem_put(kexisting);
  9095. #else
  9096. ret = dfs_file_link(existing, new);
  9097. #endif
  9098. #else
  9099. SET_ERRNO(EFAULT);
  9100. err = GET_ERRNO();
  9101. #endif
  9102. return (err < 0 ? err : ret);
  9103. }
  9104. /**
  9105. * @brief Create a symbolic link to an existing file or directory.
  9106. *
  9107. * This function creates a new symbolic link, which is a special file that contains a reference
  9108. * to another file or directory. The symbolic link allows for easy redirection or aliasing of
  9109. * file paths. Unlike a hard link, a symbolic link can point to a file or directory across
  9110. * different file systems.
  9111. *
  9112. * @param[in] existing The path to the existing file or directory that the symbolic link
  9113. * will refer to. It must be an absolute or relative path.
  9114. * @param[in] new The path to the new symbolic link to be created. This must be a valid
  9115. * path where the link will be placed.
  9116. *
  9117. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  9118. *
  9119. * @note A symbolic link is distinct from a hard link in that it points to the path of the target
  9120. * file or directory, rather than directly to the inode. If the target file or directory is
  9121. * removed or moved, the symbolic link will become "broken" and will not resolve to a valid
  9122. * location.
  9123. */
  9124. sysret_t sys_symlink(const char *existing, const char *new)
  9125. {
  9126. int ret = -1;
  9127. int err = 0;
  9128. #ifdef ARCH_MM_MMU
  9129. ret = lwp_user_strlen(existing);
  9130. if (ret <= 0)
  9131. {
  9132. return -EFAULT;
  9133. }
  9134. ret = lwp_user_strlen(new);
  9135. if (ret <= 0)
  9136. {
  9137. return -EFAULT;
  9138. }
  9139. #endif
  9140. #ifdef RT_USING_DFS_V2
  9141. ret = dfs_file_symlink(existing, new);
  9142. if (ret < 0)
  9143. {
  9144. err = GET_ERRNO();
  9145. }
  9146. #else
  9147. SET_ERRNO(EFAULT);
  9148. #endif
  9149. return (err < 0 ? err : ret);
  9150. }
  9151. /**
  9152. * @brief Create an event file descriptor.
  9153. *
  9154. * This function creates an eventfd, which is a file descriptor used for event notification.
  9155. * Eventfd is a simple mechanism to notify threads or processes about certain events using
  9156. * an integer counter. It is typically used for inter-process communication (IPC) or
  9157. * synchronization purposes, where one thread or process increments the counter to signal
  9158. * another thread or process.
  9159. *
  9160. * @param[in] count Initial value for the eventfd counter. It can be set to a non-zero
  9161. * value to initialize the counter to that value.
  9162. * @param[in] flags Flags that control the behavior of the eventfd. Valid flags include:
  9163. * - `EFD_CLOEXEC`: Set the close-on-exec flag for the eventfd.
  9164. * - `EFD_NONBLOCK`: Set the non-blocking flag for the eventfd.
  9165. *
  9166. * @return sysret_t On success, returns a valid file descriptor referring to the eventfd. On
  9167. * failure, returns a negative error code.
  9168. *
  9169. * @note Eventfd can be used for both counting and signaling purposes. It provides
  9170. * efficient signaling between threads or processes.
  9171. */
  9172. sysret_t sys_eventfd2(unsigned int count, int flags)
  9173. {
  9174. int ret;
  9175. ret = eventfd(count, flags);
  9176. return (ret < 0 ? GET_ERRNO() : ret);
  9177. }
  9178. /**
  9179. * @brief Create an epoll instance.
  9180. *
  9181. * This function creates an epoll instance, which is used for monitoring multiple file descriptors
  9182. * to see if I/O is possible on them. It allows a program to efficiently wait for events such as
  9183. * data being available for reading or space becoming available for writing. Epoll provides a scalable
  9184. * mechanism for managing large numbers of file descriptors.
  9185. *
  9186. * @param[in] flags Flags that control the behavior of the epoll instance. The valid flags include:
  9187. * - `EPOLL_CLOEXEC`: Set the close-on-exec flag for the epoll instance.
  9188. * - `EPOLL_NONBLOCK`: Set the non-blocking flag for the epoll instance.
  9189. *
  9190. * @return sysret_t On success, returns a file descriptor for the epoll instance. On failure,
  9191. * returns a negative error code.
  9192. *
  9193. * @note The `sys_epoll_create1` function is similar to `sys_epoll_create`, but it allows for
  9194. * additional control over the epoll instance creation via flags.
  9195. */
  9196. sysret_t sys_epoll_create1(int flags)
  9197. {
  9198. int ret;
  9199. ret = epoll_create(flags);
  9200. return (ret < 0 ? GET_ERRNO() : ret);
  9201. }
  9202. /**
  9203. * @brief Control an epoll instance.
  9204. *
  9205. * This function performs control operations on an epoll instance, such as adding, modifying,
  9206. * or removing file descriptors from the epoll instance's interest list.
  9207. *
  9208. * @param[in] fd The file descriptor of the epoll instance created using `sys_epoll_create` or `sys_epoll_create1`.
  9209. * @param[in] op The operation to perform on the epoll instance. It can be one of the following:
  9210. * - `EPOLL_CTL_ADD`: Add the specified file descriptor to the epoll interest list.
  9211. * - `EPOLL_CTL_MOD`: Modify the event mask of an existing file descriptor in the epoll interest list.
  9212. * - `EPOLL_CTL_DEL`: Remove the specified file descriptor from the epoll interest list.
  9213. * @param[in] fd2 The file descriptor to be added, modified, or removed from the epoll interest list.
  9214. * @param[in] ev A pointer to an `epoll_event` structure that describes the event to be associated with `fd2`.
  9215. * This parameter is required for `EPOLL_CTL_ADD` and `EPOLL_CTL_MOD`, but not for `EPOLL_CTL_DEL`.
  9216. *
  9217. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9218. *
  9219. * @note This function is typically used to manage the set of file descriptors monitored by an epoll instance.
  9220. */
  9221. sysret_t sys_epoll_ctl(int fd, int op, int fd2, struct epoll_event *ev)
  9222. {
  9223. int ret = 0;
  9224. struct epoll_event *kev = RT_NULL;
  9225. if (ev)
  9226. {
  9227. if (!lwp_user_accessable((void *)ev, sizeof(struct epoll_event)))
  9228. return -EFAULT;
  9229. kev = kmem_get(sizeof(struct epoll_event));
  9230. if (kev == RT_NULL)
  9231. {
  9232. return -ENOMEM;
  9233. }
  9234. if (lwp_get_from_user(kev, ev, sizeof(struct epoll_event)) != sizeof(struct epoll_event))
  9235. {
  9236. kmem_put(kev);
  9237. return -EINVAL;
  9238. }
  9239. ret = epoll_ctl(fd, op, fd2, kev);
  9240. kmem_put(kev);
  9241. }
  9242. else
  9243. {
  9244. ret = epoll_ctl(fd, op, fd2, RT_NULL);
  9245. }
  9246. return (ret < 0 ? GET_ERRNO() : ret);
  9247. }
  9248. /**
  9249. * @brief Wait for events on an epoll file descriptor, with the ability to block for specific signals.
  9250. *
  9251. * This function waits for events on an epoll file descriptor. It blocks until one or more events
  9252. * are available or a timeout occurs. In addition to waiting for events, it can also block for specific signals
  9253. * as specified by the `sigs` argument.
  9254. *
  9255. * @param[in] fd The file descriptor of the epoll instance, created using `sys_epoll_create` or `sys_epoll_create1`.
  9256. * @param[out] ev A pointer to an array of `epoll_event` structures that will receive the events that have occurred.
  9257. * @param[in] cnt The maximum number of events to return. This specifies the size of the `ev` array.
  9258. * @param[in] to The timeout in milliseconds. A negative value means no timeout, and `0` means non-blocking.
  9259. * @param[in] sigs A pointer to a signal set (`sigset_t`) that specifies the signals to block during the wait.
  9260. * If `NULL`, no signals are blocked.
  9261. * @param[in] sigsetsize The size of the signal set (`sigs`) in bytes. This should be the size of `sigset_t` if `sigs` is not `NULL`.
  9262. *
  9263. * @return sysret_t On success, returns the number of events returned (may be `0` if the timeout expires with no events).
  9264. * On failure, returns a negative error code.
  9265. *
  9266. * @note This function is similar to `sys_epoll_wait`, but it also allows for signal handling, blocking the calling thread
  9267. * from receiving signals specified in the `sigs` set while waiting for events.
  9268. */
  9269. sysret_t sys_epoll_pwait(int fd,
  9270. struct epoll_event *ev,
  9271. int cnt,
  9272. int to,
  9273. const sigset_t *sigs,
  9274. unsigned long sigsetsize)
  9275. {
  9276. int ret = 0;
  9277. struct epoll_event *kev = RT_NULL;
  9278. sigset_t *ksigs = RT_NULL;
  9279. if (!lwp_user_accessable((void *)ev, cnt * sizeof(struct epoll_event)))
  9280. return -EFAULT;
  9281. kev = kmem_get(cnt * sizeof(struct epoll_event));
  9282. if (kev == RT_NULL)
  9283. {
  9284. return -ENOMEM;
  9285. }
  9286. if (sigs != RT_NULL)
  9287. {
  9288. if (!lwp_user_accessable((void *)sigs, sizeof(sigset_t)))
  9289. {
  9290. kmem_put(kev);
  9291. return -EFAULT;
  9292. }
  9293. ksigs = kmem_get(sizeof(sigset_t));
  9294. if (ksigs == RT_NULL)
  9295. {
  9296. kmem_put(kev);
  9297. return -ENOMEM;
  9298. }
  9299. if (lwp_get_from_user(ksigs, (void *)sigs, sizeof(sigset_t)) != sizeof(sigset_t))
  9300. {
  9301. kmem_put(kev);
  9302. kmem_put(ksigs);
  9303. return -EINVAL;
  9304. }
  9305. }
  9306. ret = epoll_pwait(fd, kev, cnt, to, ksigs);
  9307. if (ret > 0)
  9308. {
  9309. lwp_put_to_user((void *)ev, kev, ret * sizeof(struct epoll_event));
  9310. }
  9311. if (sigs != RT_NULL)
  9312. kmem_put(ksigs);
  9313. kmem_put(kev);
  9314. return (ret < 0 ? GET_ERRNO() : ret);
  9315. }
  9316. /**
  9317. * @brief Truncate a file to a specified length.
  9318. *
  9319. * This function resizes the file associated with the given file descriptor `fd` to the specified length.
  9320. * If the current size of the file is greater than the specified length, the file is truncated. If the file is smaller,
  9321. * it is extended, and the new space is initialized to zero.
  9322. *
  9323. * @param[in] fd The file descriptor referring to the file to truncate. This must be a valid open file descriptor.
  9324. * @param[in] length The new length of the file. The file will be truncated or extended to this size.
  9325. *
  9326. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9327. *
  9328. * @note The file descriptor `fd` must be opened with write permissions for this operation to succeed.
  9329. */
  9330. sysret_t sys_ftruncate(int fd, size_t length)
  9331. {
  9332. int ret;
  9333. ret = ftruncate(fd, length);
  9334. return (ret < 0 ? GET_ERRNO() : ret);
  9335. }
  9336. /**
  9337. * @brief Set file access and modification times.
  9338. *
  9339. * This function updates the access and modification times of a file or directory referenced by `__fd` or `__path`.
  9340. * If `__fd` is a valid file descriptor, the times will be applied to the file or directory it refers to.
  9341. * If `__fd` is `AT_FDCWD`, the times will be applied to the file or directory specified by `__path`.
  9342. * The `__times` argument consists of two `timespec` values: the first represents the access time,
  9343. * and the second represents the modification time. If `__times` is `NULL`, the current time is used.
  9344. *
  9345. * @param[in] __fd The file descriptor of the file or directory to modify, or `AT_FDCWD` to modify using `__path`.
  9346. * @param[in] __path The path to the file or directory to modify. Ignored if `__fd` is not `AT_FDCWD`.
  9347. * @param[in] __times An array of two `timespec` structures. The first element is the access time, and the second is the modification time.
  9348. * If `__times` is `NULL`, the current time is used for both access and modification times.
  9349. * @param[in] __flags Flags to modify behavior. Supported flags include:
  9350. * - `AT_SYMLINK_NOFOLLOW`: Do not follow symbolic links.
  9351. * - `AT_NO_AUTOMOUNT`: Do not trigger automounting.
  9352. *
  9353. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9354. *
  9355. * @note This function modifies both access and modification times of files, and may affect file system timestamps.
  9356. */
  9357. sysret_t sys_utimensat(int __fd, const char *__path, const struct timespec __times[2], int __flags)
  9358. {
  9359. #ifdef RT_USING_DFS_V2
  9360. #ifdef ARCH_MM_MMU
  9361. int ret = -1;
  9362. rt_size_t len = 0;
  9363. char *kpath = RT_NULL;
  9364. len = lwp_user_strlen(__path);
  9365. if (len <= 0)
  9366. {
  9367. return -EINVAL;
  9368. }
  9369. kpath = (char *)kmem_get(len + 1);
  9370. if (!kpath)
  9371. {
  9372. return -ENOMEM;
  9373. }
  9374. lwp_get_from_user(kpath, (void *)__path, len + 1);
  9375. ret = utimensat(__fd, kpath, __times, __flags);
  9376. kmem_put(kpath);
  9377. return ret;
  9378. #else
  9379. if (!lwp_user_accessable((void *)__path, 1))
  9380. {
  9381. return -EFAULT;
  9382. }
  9383. int ret = utimensat(__fd, __path, __times, __flags);
  9384. return ret;
  9385. #endif
  9386. #else
  9387. return -1;
  9388. #endif
  9389. }
  9390. /**
  9391. * @brief Change file permissions.
  9392. *
  9393. * This function changes the permissions of a file or directory specified by the `pathname`.
  9394. * The new permissions are specified using the `mode` argument, which is a bitwise OR of permission bits.
  9395. * The permissions apply to the file owner, group, and others, depending on the value of `mode`.
  9396. *
  9397. * @param[in] pathname The path to the file or directory whose permissions are to be changed.
  9398. * @param[in] mode The new permissions to set, represented as a bitwise OR of permission flags.
  9399. * For example, `S_IRUSR`, `S_IWUSR`, `S_IRGRP`, etc.
  9400. *
  9401. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9402. *
  9403. * @note If the file or directory is a symbolic link, this function will modify the permissions of the symbolic link itself,
  9404. * not the target file or directory.
  9405. */
  9406. sysret_t sys_chmod(const char *pathname, mode_t mode)
  9407. {
  9408. char *copy_file;
  9409. size_t len_file, copy_len_file;
  9410. struct dfs_attr attr = { 0 };
  9411. int ret = 0;
  9412. len_file = lwp_user_strlen(pathname);
  9413. if (len_file <= 0)
  9414. {
  9415. return -EFAULT;
  9416. }
  9417. copy_file = (char *)rt_malloc(len_file + 1);
  9418. if (!copy_file)
  9419. {
  9420. return -ENOMEM;
  9421. }
  9422. copy_len_file = lwp_get_from_user(copy_file, (void *)pathname, len_file);
  9423. attr.st_mode = mode;
  9424. attr.ia_valid |= ATTR_MODE_SET;
  9425. copy_file[copy_len_file] = '\0';
  9426. ret = dfs_file_setattr(copy_file, &attr);
  9427. rt_free(copy_file);
  9428. return (ret < 0 ? GET_ERRNO() : ret);
  9429. }
  9430. /**
  9431. * @brief Change the ownership of a file or directory.
  9432. *
  9433. * This function changes the owner and/or group of the file or directory specified by `pathname`.
  9434. * The `owner` and `group` parameters represent the new owner and group IDs, respectively. If either
  9435. * parameter is set to `-1`, that aspect (owner or group) will remain unchanged.
  9436. *
  9437. * @param[in] pathname The path to the file or directory whose ownership is to be changed.
  9438. * @param[in] owner The new owner ID. If set to `-1`, the owner's ID is not changed.
  9439. * @param[in] group The new group ID. If set to `-1`, the group's ID is not changed.
  9440. *
  9441. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9442. *
  9443. * @note The caller must have the appropriate permissions (i.e., be the superuser or the file owner)
  9444. * to change the ownership of a file or directory.
  9445. */
  9446. sysret_t sys_chown(const char *pathname, uid_t owner, gid_t group)
  9447. {
  9448. char *copy_file;
  9449. size_t len_file, copy_len_file;
  9450. struct dfs_attr attr = { 0 };
  9451. int ret = 0;
  9452. len_file = lwp_user_strlen(pathname);
  9453. if (len_file <= 0)
  9454. {
  9455. return -EFAULT;
  9456. }
  9457. copy_file = (char *)rt_malloc(len_file + 1);
  9458. if (!copy_file)
  9459. {
  9460. return -ENOMEM;
  9461. }
  9462. copy_len_file = lwp_get_from_user(copy_file, (void *)pathname, len_file);
  9463. if (owner >= 0)
  9464. {
  9465. attr.st_uid = owner;
  9466. attr.ia_valid |= ATTR_UID_SET;
  9467. }
  9468. if (group >= 0)
  9469. {
  9470. attr.st_gid = group;
  9471. attr.ia_valid |= ATTR_GID_SET;
  9472. }
  9473. copy_file[copy_len_file] = '\0';
  9474. ret = dfs_file_setattr(copy_file, &attr);
  9475. rt_free(copy_file);
  9476. return (ret < 0 ? GET_ERRNO() : ret);
  9477. }
  9478. #ifndef LWP_USING_RUNTIME
  9479. sysret_t lwp_teardown(struct rt_lwp *lwp, void (*cb)(void))
  9480. {
  9481. /* if no LWP_USING_RUNTIME configured */
  9482. return -ENOSYS;
  9483. }
  9484. #endif
  9485. /**
  9486. * @brief Reboot the system.
  9487. *
  9488. * This function initiates a system reboot with a specific reboot type and optional arguments.
  9489. * The reboot process is performed by passing `magic` and `magic2` as security keys to validate the
  9490. * reboot request, along with the desired reboot type (`type`) and optional argument (`arg`) that
  9491. * may contain additional parameters depending on the reboot type.
  9492. *
  9493. * @param[in] magic A magic number for security validation, typically used to verify that the caller
  9494. * has sufficient privileges (e.g., root).
  9495. * @param[in] magic2 A second magic number for additional security verification, used in combination
  9496. * with `magic` to validate the reboot request.
  9497. * @param[in] type The type of reboot to perform, such as `RB_AUTOBOOT`, `RB_HALT`, `RB_RESTART`,
  9498. * etc. The exact values may depend on the platform.
  9499. * @param[in] arg An optional argument for the reboot process. This can provide additional data,
  9500. * such as a specific shutdown procedure, depending on the type of reboot.
  9501. *
  9502. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9503. *
  9504. * @note This operation is typically available to the system administrator (root) and should be used
  9505. * with caution as it can cause the system to restart or shut down.
  9506. */
  9507. sysret_t sys_reboot(int magic, int magic2, int type, void *arg)
  9508. {
  9509. sysret_t rc;
  9510. switch (type)
  9511. {
  9512. /* Hardware reset */
  9513. case RB_AUTOBOOT:
  9514. rc = lwp_teardown(lwp_self(), rt_hw_cpu_reset);
  9515. break;
  9516. /* Stop system and switch power off */
  9517. case RB_POWER_OFF:
  9518. rc = lwp_teardown(lwp_self(), rt_hw_cpu_shutdown);
  9519. break;
  9520. default:
  9521. rc = -ENOSYS;
  9522. }
  9523. return rc;
  9524. }
  9525. /**
  9526. * @brief Read data from a file descriptor at a specific offset.
  9527. *
  9528. * This function reads data from a file descriptor `fd` into the buffer `buf`, starting from the
  9529. * specified byte `offset`. Unlike a regular `read` call, `sys_pread64` allows the file pointer to
  9530. * remain unchanged after the read, as the operation directly accesses the file at the provided
  9531. * offset.
  9532. *
  9533. * @param[in] fd The file descriptor from which to read. It must be a valid open file descriptor.
  9534. * @param[out] buf A pointer to the buffer where the read data will be stored.
  9535. * @param[in] size The number of bytes to read from the file.
  9536. * @param[in] offset The offset in bytes from the beginning of the file to start reading from.
  9537. *
  9538. * @return ssize_t On success, returns the number of bytes read (which may be less than `size` if
  9539. * the end of the file is reached). On error, returns a negative error code.
  9540. *
  9541. * @note This function is particularly useful for random access to files, allowing for efficient
  9542. * reads from arbitrary positions without affecting the current file pointer.
  9543. */
  9544. ssize_t sys_pread64(int fd, void *buf, int size, size_t offset)
  9545. #ifdef RT_USING_DFS_V2
  9546. {
  9547. ssize_t pread(int fd, void *buf, size_t len, size_t offset);
  9548. #ifdef ARCH_MM_MMU
  9549. ssize_t ret = -1;
  9550. void *kmem = RT_NULL;
  9551. if (!size)
  9552. {
  9553. return -EINVAL;
  9554. }
  9555. if (!lwp_user_accessable((void *)buf, size))
  9556. {
  9557. return -EFAULT;
  9558. }
  9559. kmem = kmem_get(size);
  9560. if (!kmem)
  9561. {
  9562. return -ENOMEM;
  9563. }
  9564. ret = pread(fd, kmem, size, offset);
  9565. if (ret > 0)
  9566. {
  9567. lwp_put_to_user(buf, kmem, ret);
  9568. }
  9569. if (ret < 0)
  9570. {
  9571. ret = GET_ERRNO();
  9572. }
  9573. kmem_put(kmem);
  9574. return ret;
  9575. #else
  9576. if (!lwp_user_accessable((void *)buf, size))
  9577. {
  9578. return -EFAULT;
  9579. }
  9580. ssize_t ret = pread(fd, kmem, size, offset);
  9581. return (ret < 0 ? GET_ERRNO() : ret);
  9582. #endif
  9583. }
  9584. #else
  9585. {
  9586. ssize_t ret = -ENOSYS;
  9587. return (ret < 0 ? GET_ERRNO() : ret);
  9588. }
  9589. #endif
  9590. /**
  9591. * @brief Write data to a file descriptor at a specific offset.
  9592. *
  9593. * This function writes data from the buffer `buf` to the file descriptor `fd`, starting at the
  9594. * specified byte `offset`. Unlike a regular `write` call, `sys_pwrite64` allows the file pointer to
  9595. * remain unchanged after the write, as the operation directly writes the data to the file at the
  9596. * provided offset.
  9597. *
  9598. * @param[in] fd The file descriptor to which the data will be written. It must be a valid open
  9599. * file descriptor.
  9600. * @param[in] buf A pointer to the buffer containing the data to be written.
  9601. * @param[in] size The number of bytes to write to the file.
  9602. * @param[in] offset The offset in bytes from the beginning of the file to start writing to.
  9603. *
  9604. * @return ssize_t On success, returns the number of bytes written (which may be less than `size` if
  9605. * the write operation is partial). On error, returns a negative error code.
  9606. *
  9607. * @note This function is particularly useful for random access to files, allowing for efficient
  9608. * writes to arbitrary positions without affecting the current file pointer.
  9609. */
  9610. ssize_t sys_pwrite64(int fd, void *buf, int size, size_t offset)
  9611. #ifdef RT_USING_DFS_V2
  9612. {
  9613. ssize_t pwrite(int fd, const void *buf, size_t len, size_t offset);
  9614. #ifdef ARCH_MM_MMU
  9615. ssize_t ret = -1;
  9616. void *kmem = RT_NULL;
  9617. if (!size)
  9618. {
  9619. return -EINVAL;
  9620. }
  9621. if (!lwp_user_accessable((void *)buf, size))
  9622. {
  9623. return -EFAULT;
  9624. }
  9625. kmem = kmem_get(size);
  9626. if (!kmem)
  9627. {
  9628. return -ENOMEM;
  9629. }
  9630. lwp_get_from_user(kmem, (void *)buf, size);
  9631. ret = pwrite(fd, kmem, size, offset);
  9632. if (ret < 0)
  9633. {
  9634. ret = GET_ERRNO();
  9635. }
  9636. kmem_put(kmem);
  9637. return ret;
  9638. #else
  9639. if (!lwp_user_accessable((void *)buf, size))
  9640. {
  9641. return -EFAULT;
  9642. }
  9643. ssize_t ret = pwrite(fd, kmem, size, offset);
  9644. return (ret < 0 ? GET_ERRNO() : ret);
  9645. #endif
  9646. }
  9647. #else
  9648. {
  9649. ssize_t ret = -ENOSYS;
  9650. return (ret < 0 ? GET_ERRNO() : ret);
  9651. }
  9652. #endif
  9653. /**
  9654. * @brief Create a timer file descriptor.
  9655. *
  9656. * This function creates a timer that can be used to notify a process after a specified
  9657. * amount of time has passed. The timer is represented by a file descriptor, which can be
  9658. * used with functions such as `read` and `poll` to monitor and retrieve notifications
  9659. * about timer expirations.
  9660. *
  9661. * @param[in] clockid The clock to use for the timer. Possible values include:
  9662. * - `CLOCK_REALTIME`: The system's real-time clock.
  9663. * - `CLOCK_MONOTONIC`: A clock that cannot be set and is not affected by
  9664. * changes in the system time.
  9665. * @param[in] flags Flags that modify the behavior of the timer. The commonly used values are:
  9666. * - `TFD_CLOEXEC`: Set the close-on-exec flag for the file descriptor.
  9667. * - `TFD_NONBLOCK`: Set the non-blocking flag for the file descriptor.
  9668. *
  9669. * @return sysret_t On success, returns a non-negative file descriptor that refers to the timer.
  9670. * On failure, returns a negative error code.
  9671. *
  9672. * @note The timer created by this function can be used to create periodic or one-shot timers.
  9673. * The timer can be configured using `timerfd_settime` and notifications can be retrieved
  9674. * by reading from the returned file descriptor.
  9675. */
  9676. sysret_t sys_timerfd_create(int clockid, int flags)
  9677. {
  9678. int ret;
  9679. ret = timerfd_create(clockid, flags);
  9680. return (ret < 0 ? GET_ERRNO() : ret);
  9681. }
  9682. /**
  9683. * @brief Set or modify the expiration time for a timer.
  9684. *
  9685. * This function is used to arm or re-arm a timer associated with a file descriptor created
  9686. * by `sys_timerfd_create`. It allows setting a new expiration time and can also return
  9687. * the previous timer configuration.
  9688. *
  9689. * @param[in] fd The file descriptor referring to the timer, which was created using
  9690. * `sys_timerfd_create`.
  9691. * @param[in] flags Flags that modify the behavior of the timer. The commonly used values are:
  9692. * - `TFD_TIMER_ABSTIME`: If set, the `new` expiration time is an absolute time.
  9693. * - `TFD_TIMER_RELATIVE`: The default behavior, where `new` expiration time is
  9694. * a relative time from now.
  9695. * @param[in] new A pointer to a `struct itimerspec` specifying the new expiration time.
  9696. * It contains two fields:
  9697. * - `it_value`: The initial expiration time of the timer.
  9698. * - `it_interval`: The period of periodic timers (if zero, the timer is one-shot).
  9699. * @param[out] old A pointer to a `struct itimerspec` where the previous timer configuration
  9700. * will be stored. This can be `NULL` if the previous configuration is not needed.
  9701. *
  9702. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9703. *
  9704. * @note This function allows for both one-shot and periodic timers. If the timer is periodic,
  9705. * it will continue triggering at intervals specified in `it_interval` until canceled or modified.
  9706. * When a timer expires, the associated file descriptor becomes readable, and the application
  9707. * can retrieve the expiration event by reading from the file descriptor.
  9708. */
  9709. sysret_t sys_timerfd_settime(int fd, int flags, const struct itimerspec *new, struct itimerspec *old)
  9710. {
  9711. int ret = -1;
  9712. struct itimerspec *knew = RT_NULL;
  9713. struct itimerspec *kold = RT_NULL;
  9714. if (new == RT_NULL)
  9715. return -EINVAL;
  9716. if (!lwp_user_accessable((void *)new, sizeof(struct itimerspec)))
  9717. {
  9718. return -EFAULT;
  9719. }
  9720. knew = kmem_get(sizeof(struct itimerspec));
  9721. if (knew)
  9722. {
  9723. lwp_get_from_user(knew, (void *)new, sizeof(struct itimerspec));
  9724. if (old)
  9725. {
  9726. if (!lwp_user_accessable((void *)old, sizeof(struct itimerspec)))
  9727. {
  9728. kmem_put(knew);
  9729. return -EFAULT;
  9730. }
  9731. kold = kmem_get(sizeof(struct itimerspec));
  9732. if (kold == RT_NULL)
  9733. {
  9734. kmem_put(knew);
  9735. return -ENOMEM;
  9736. }
  9737. }
  9738. ret = timerfd_settime(fd, flags, knew, kold);
  9739. if (old)
  9740. {
  9741. lwp_put_to_user(old, kold, sizeof(*kold));
  9742. kmem_put(kold);
  9743. }
  9744. kmem_put(knew);
  9745. }
  9746. return (ret < 0 ? GET_ERRNO() : ret);
  9747. }
  9748. /**
  9749. * @brief Retrieve the current configuration of a timer.
  9750. *
  9751. * This function is used to obtain the current expiration time and interval of a timer associated
  9752. * with a file descriptor created by `sys_timerfd_create`. It allows querying the current state
  9753. * of the timer, including the time remaining until the next expiration and the period (for periodic timers).
  9754. *
  9755. * @param[in] fd The file descriptor referring to the timer, which was created using
  9756. * `sys_timerfd_create`.
  9757. * @param[out] cur A pointer to a `struct itimerspec` where the current timer configuration will
  9758. * be stored. This structure contains:
  9759. * - `it_value`: The time remaining until the timer expires.
  9760. * - `it_interval`: The period for periodic timers (zero for one-shot timers).
  9761. *
  9762. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9763. *
  9764. * @note The timer's `it_value` field will contain the time remaining until the next expiration.
  9765. * If the timer is periodic, the `it_interval` field will contain the period for the next expiration.
  9766. * If the timer has expired and there is no further interval (for one-shot timers), `it_value` will
  9767. * contain a value of `0`.
  9768. */
  9769. sysret_t sys_timerfd_gettime(int fd, struct itimerspec *cur)
  9770. {
  9771. int ret = -1;
  9772. struct itimerspec *kcur;
  9773. if (cur == RT_NULL)
  9774. return -EINVAL;
  9775. if (!lwp_user_accessable((void *)cur, sizeof(struct itimerspec)))
  9776. {
  9777. return -EFAULT;
  9778. }
  9779. kcur = kmem_get(sizeof(struct itimerspec));
  9780. if (kcur)
  9781. {
  9782. lwp_get_from_user(kcur, cur, sizeof(struct itimerspec));
  9783. ret = timerfd_gettime(fd, kcur);
  9784. lwp_put_to_user(cur, kcur, sizeof(struct itimerspec));
  9785. kmem_put(kcur);
  9786. }
  9787. return (ret < 0 ? GET_ERRNO() : ret);
  9788. }
  9789. /**
  9790. * @brief Create a file descriptor for receiving signals.
  9791. *
  9792. * This function creates a file descriptor that can be used to receive signals, similar to how a
  9793. * regular file descriptor is used. The signals specified in the provided signal mask are blocked
  9794. * for the calling thread, and any matching signals will be reported through the file descriptor.
  9795. * This allows signals to be handled in a more controlled, non-interrupt-driven way by using
  9796. * standard I/O operations (e.g., `read()` or `select()`) on the file descriptor.
  9797. *
  9798. * @param[in] fd A file descriptor associated with the process, typically obtained from
  9799. * `sys_signalfd()` or a similar mechanism. If `fd` is `-1`, a new file descriptor
  9800. * will be created.
  9801. * @param[in] mask A pointer to the signal mask (`sigset_t`) that specifies the signals that
  9802. * should be received by the file descriptor. Only signals in the mask will be
  9803. * reported.
  9804. * @param[in] flags Additional flags to control the behavior of the signalfd. Common flags
  9805. * include `O_NONBLOCK` for non-blocking operation.
  9806. *
  9807. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9808. *
  9809. * @note The caller must call `read()` on the resulting file descriptor to actually receive signals.
  9810. * Each read returns a `struct signalfd_siginfo` containing the signal number, and additional
  9811. * information, such as the signal source and sender.
  9812. *
  9813. * @see sys_read(), sigprocmask(), sigaction(), sigsuspend().
  9814. */
  9815. sysret_t sys_signalfd(int fd, const sigset_t *mask, int flags)
  9816. {
  9817. int ret = 0;
  9818. sigset_t *kmask = RT_NULL;
  9819. #ifdef RT_USING_MUSLLIBC
  9820. if (mask == RT_NULL)
  9821. return -EINVAL;
  9822. if (!lwp_user_accessable((void *)mask, sizeof(struct itimerspec)))
  9823. {
  9824. return -EFAULT;
  9825. }
  9826. kmask = kmem_get(sizeof(struct itimerspec));
  9827. if (kmask)
  9828. {
  9829. if (lwp_get_from_user(kmask, (void *)mask, sizeof(struct itimerspec)) != sizeof(struct itimerspec))
  9830. {
  9831. kmem_put(kmask);
  9832. return -EFAULT;
  9833. }
  9834. ret = signalfd(fd, mask, flags);
  9835. kmem_put(kmask);
  9836. }
  9837. #endif
  9838. return (ret < 0 ? GET_ERRNO() : ret);
  9839. }
  9840. sysret_t sys_memfd_create()
  9841. {
  9842. return 0;
  9843. }
  9844. /**
  9845. * @brief Set the value of an interval timer.
  9846. *
  9847. * This function is used to set the value of a specified timer that generates periodic signals
  9848. * after the specified intervals. The timer can be configured to generate a signal when it expires,
  9849. * and it can be used for tasks like scheduling periodic events.
  9850. *
  9851. * @param[in] which Specifies which timer to set. Possible values include:
  9852. * - `ITIMER_REAL`: Timer that decrements in real time and sends `SIGALRM` when expired.
  9853. * - `ITIMER_VIRTUAL`: Timer that decrements only while the process is executing.
  9854. * - `ITIMER_PROF`: Timer that decrements while the process is executing or when it is
  9855. * executing in the kernel.
  9856. * @param[in] new A pointer to a `struct itimerspec` containing the new value for the timer.
  9857. * The `itimerspec` structure contains two `timespec` fields: `it_value` for the initial
  9858. * expiration time and `it_interval` for the interval between successive expirations.
  9859. * @param[out] old A pointer to a `struct itimerspec` where the previous timer values (before the
  9860. * timer is set) will be stored.
  9861. *
  9862. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9863. *
  9864. * @note If the specified timer is already active, it will be updated with the new values. The timer
  9865. * will start at the `it_value` time and will repeat at the interval specified in `it_interval`.
  9866. * If `it_interval` is set to `0`, the timer will not repeat and will only expire once.
  9867. *
  9868. * @see sys_getitimer(), sigaction(), alarm(), setitimer().
  9869. */
  9870. sysret_t sys_setitimer(int which, const struct itimerspec * restrict new, struct itimerspec * restrict old)
  9871. {
  9872. sysret_t rc = 0;
  9873. rt_lwp_t lwp = lwp_self();
  9874. struct itimerspec new_value_k;
  9875. struct itimerspec old_value_k;
  9876. if (lwp_get_from_user(&new_value_k, (void *)new, sizeof(*new)) != sizeof(*new))
  9877. {
  9878. return -EFAULT;
  9879. }
  9880. rc = lwp_signal_setitimer(lwp, which, &new_value_k, &old_value_k);
  9881. if (old && lwp_put_to_user(old, (void *)&old_value_k, sizeof old_value_k) != sizeof old_value_k)
  9882. return -EFAULT;
  9883. return rc;
  9884. }
  9885. /**
  9886. * @brief Set the robust list for the current thread.
  9887. *
  9888. * The `sys_set_robust_list` function sets the robust list for the calling thread. The robust list is
  9889. * a list of `struct robust_list_head` elements that contain information about mutexes or other
  9890. * resources that need to be cleaned up if the thread dies unexpectedly.
  9891. *
  9892. * This function is typically used for thread safety in multi-threaded programs, where robust mutexes
  9893. * can be used to avoid leaving resources in an inconsistent state when a thread is terminated
  9894. * without properly unlocking locks or releasing resources.
  9895. *
  9896. * @param[in] head A pointer to the robust list to be set. This list contains `struct robust_list_head`
  9897. * entries which are used by the kernel to maintain information about robust mutexes.
  9898. * @param[in] len The length of the robust list (the number of entries in the list). This should correspond
  9899. * to the size of the list in memory, generally expressed in bytes.
  9900. *
  9901. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9902. *
  9903. * @note The robust list should be set during the initialization of a thread or task, and it may be
  9904. * used by the kernel to track which mutexes need to be cleaned up in case of failure.
  9905. * The list may be manipulated using related functions such as `sys_get_robust_list`.
  9906. *
  9907. * @see sys_get_robust_list(), robust_mutex, pthread_mutex, set_robust_list.
  9908. */
  9909. sysret_t sys_set_robust_list(struct robust_list_head *head, size_t len)
  9910. {
  9911. if (len != sizeof(*head))
  9912. return -EINVAL;
  9913. rt_thread_self()->robust_list = head;
  9914. return 0;
  9915. }
  9916. /**
  9917. * @brief Get the robust list for the specified thread.
  9918. *
  9919. * The `sys_get_robust_list` function retrieves the robust list associated with the given thread.
  9920. * The robust list contains `struct robust_list_head` entries used by the kernel to manage
  9921. * robust mutexes and other resources that need to be cleaned up if the thread terminates unexpectedly.
  9922. *
  9923. * This function is primarily used to retrieve the robust list for a specific thread, so that
  9924. * the caller can inspect or manipulate the robust list to handle clean-up operations in case
  9925. * the thread exits while holding resources.
  9926. *
  9927. * @param[in] tid The thread ID of the thread whose robust list is to be retrieved.
  9928. *
  9929. * @param[out] head_ptr A pointer to a pointer to `struct robust_list_head`. On success,
  9930. * this will point to the robust list for the specified thread.
  9931. *
  9932. * @param[out] len_ptr A pointer to a variable that will hold the length of the robust list
  9933. * (i.e., the number of entries in the list).
  9934. *
  9935. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9936. *
  9937. * @note The robust list is used to track mutexes and other resources that need to be cleaned up
  9938. * if a thread terminates without releasing the resources properly. It is typically used by
  9939. * the kernel for thread safety and resource management in multi-threaded programs.
  9940. *
  9941. * @see sys_set_robust_list(), robust_mutex, pthread_mutex, get_robust_list.
  9942. */
  9943. sysret_t sys_get_robust_list(int tid, struct robust_list_head **head_ptr, size_t *len_ptr)
  9944. {
  9945. rt_thread_t thread;
  9946. size_t len;
  9947. struct robust_list_head *head;
  9948. if (!lwp_user_accessable((void *)head_ptr, sizeof(struct robust_list_head *)))
  9949. {
  9950. return -EFAULT;
  9951. }
  9952. if (!lwp_user_accessable((void *)len_ptr, sizeof(size_t)))
  9953. {
  9954. return -EFAULT;
  9955. }
  9956. if (tid == 0)
  9957. {
  9958. thread = rt_thread_self();
  9959. head = thread->robust_list;
  9960. }
  9961. else
  9962. {
  9963. thread = lwp_tid_get_thread_and_inc_ref(tid);
  9964. if (thread)
  9965. {
  9966. head = thread->robust_list;
  9967. lwp_tid_dec_ref(thread);
  9968. }
  9969. else
  9970. {
  9971. return -ESRCH;
  9972. }
  9973. }
  9974. len = sizeof(*(head));
  9975. if (!lwp_put_to_user(len_ptr, &len, sizeof(size_t)))
  9976. return -EFAULT;
  9977. if (!lwp_put_to_user(head_ptr, &head, sizeof(struct robust_list_head *)))
  9978. return -EFAULT;
  9979. return 0;
  9980. }
  9981. const static struct rt_syscall_def func_table[] = {
  9982. SYSCALL_SIGN(sys_exit), /* 01 */
  9983. SYSCALL_SIGN(sys_read),
  9984. SYSCALL_SIGN(sys_write),
  9985. SYSCALL_SIGN(sys_lseek),
  9986. SYSCALL_SIGN(sys_open), /* 05 */
  9987. SYSCALL_SIGN(sys_close),
  9988. SYSCALL_SIGN(sys_ioctl),
  9989. SYSCALL_SIGN(sys_fstat),
  9990. SYSCALL_SIGN(sys_poll),
  9991. SYSCALL_SIGN(sys_nanosleep), /* 10 */
  9992. SYSCALL_SIGN(sys_gettimeofday),
  9993. SYSCALL_SIGN(sys_settimeofday),
  9994. SYSCALL_SIGN(sys_exec),
  9995. SYSCALL_SIGN(sys_kill),
  9996. SYSCALL_SIGN(sys_getpid), /* 15 */
  9997. SYSCALL_SIGN(sys_getpriority),
  9998. SYSCALL_SIGN(sys_setpriority),
  9999. SYSCALL_SIGN(sys_sem_create),
  10000. SYSCALL_SIGN(sys_sem_delete),
  10001. SYSCALL_SIGN(sys_sem_take), /* 20 */
  10002. SYSCALL_SIGN(sys_sem_release),
  10003. SYSCALL_SIGN(sys_mutex_create),
  10004. SYSCALL_SIGN(sys_mutex_delete),
  10005. SYSCALL_SIGN(sys_mutex_take),
  10006. SYSCALL_SIGN(sys_mutex_release), /* 25 */
  10007. SYSCALL_SIGN(sys_event_create),
  10008. SYSCALL_SIGN(sys_event_delete),
  10009. SYSCALL_SIGN(sys_event_send),
  10010. SYSCALL_SIGN(sys_event_recv),
  10011. SYSCALL_SIGN(sys_mb_create), /* 30 */
  10012. SYSCALL_SIGN(sys_mb_delete),
  10013. SYSCALL_SIGN(sys_mb_send),
  10014. SYSCALL_SIGN(sys_mb_send_wait),
  10015. SYSCALL_SIGN(sys_mb_recv),
  10016. SYSCALL_SIGN(sys_mq_create), /* 35 */
  10017. SYSCALL_SIGN(sys_mq_delete),
  10018. SYSCALL_SIGN(sys_mq_send),
  10019. SYSCALL_SIGN(sys_mq_urgent),
  10020. SYSCALL_SIGN(sys_mq_recv),
  10021. SYSCALL_SIGN(sys_thread_create), /* 40 */
  10022. SYSCALL_SIGN(sys_thread_delete),
  10023. SYSCALL_SIGN(sys_thread_startup),
  10024. SYSCALL_SIGN(sys_thread_self),
  10025. SYSCALL_SIGN(sys_channel_open),
  10026. SYSCALL_SIGN(sys_channel_close), /* 45 */
  10027. SYSCALL_SIGN(sys_channel_send),
  10028. SYSCALL_SIGN(sys_channel_send_recv_timeout),
  10029. SYSCALL_SIGN(sys_channel_reply),
  10030. SYSCALL_SIGN(sys_channel_recv_timeout),
  10031. SYSCALL_SIGN(sys_enter_critical), /* 50 */
  10032. SYSCALL_SIGN(sys_exit_critical),
  10033. SYSCALL_USPACE(SYSCALL_SIGN(sys_brk)),
  10034. SYSCALL_USPACE(SYSCALL_SIGN(sys_mmap2)),
  10035. SYSCALL_USPACE(SYSCALL_SIGN(sys_munmap)),
  10036. #ifdef ARCH_MM_MMU
  10037. SYSCALL_USPACE(SYSCALL_SIGN(sys_shmget)), /* 55 */
  10038. SYSCALL_USPACE(SYSCALL_SIGN(sys_shmrm)),
  10039. SYSCALL_USPACE(SYSCALL_SIGN(sys_shmat)),
  10040. SYSCALL_USPACE(SYSCALL_SIGN(sys_shmdt)),
  10041. #else
  10042. #ifdef RT_LWP_USING_SHM
  10043. SYSCALL_SIGN(sys_shm_alloc), /* 55 */
  10044. SYSCALL_SIGN(sys_shm_free),
  10045. SYSCALL_SIGN(sys_shm_retain),
  10046. SYSCALL_SIGN(sys_notimpl),
  10047. #else
  10048. SYSCALL_SIGN(sys_notimpl), /* 55 */
  10049. SYSCALL_SIGN(sys_notimpl),
  10050. SYSCALL_SIGN(sys_notimpl),
  10051. SYSCALL_SIGN(sys_notimpl),
  10052. #endif /* RT_LWP_USING_SHM */
  10053. #endif /* ARCH_MM_MMU */
  10054. SYSCALL_SIGN(sys_device_init),
  10055. SYSCALL_SIGN(sys_device_register), /* 60 */
  10056. SYSCALL_SIGN(sys_device_control),
  10057. SYSCALL_SIGN(sys_device_find),
  10058. SYSCALL_SIGN(sys_device_open),
  10059. SYSCALL_SIGN(sys_device_close),
  10060. SYSCALL_SIGN(sys_device_read), /* 65 */
  10061. SYSCALL_SIGN(sys_device_write),
  10062. SYSCALL_SIGN(sys_stat),
  10063. SYSCALL_SIGN(sys_thread_find),
  10064. SYSCALL_NET(SYSCALL_SIGN(sys_accept)),
  10065. SYSCALL_NET(SYSCALL_SIGN(sys_bind)), /* 70 */
  10066. SYSCALL_NET(SYSCALL_SIGN(sys_shutdown)),
  10067. SYSCALL_NET(SYSCALL_SIGN(sys_getpeername)),
  10068. SYSCALL_NET(SYSCALL_SIGN(sys_getsockname)),
  10069. SYSCALL_NET(SYSCALL_SIGN(sys_getsockopt)),
  10070. SYSCALL_NET(SYSCALL_SIGN(sys_setsockopt)), /* 75 */
  10071. SYSCALL_NET(SYSCALL_SIGN(sys_connect)),
  10072. SYSCALL_NET(SYSCALL_SIGN(sys_listen)),
  10073. SYSCALL_NET(SYSCALL_SIGN(sys_recv)),
  10074. SYSCALL_NET(SYSCALL_SIGN(sys_recvfrom)),
  10075. SYSCALL_NET(SYSCALL_SIGN(sys_send)), /* 80 */
  10076. SYSCALL_NET(SYSCALL_SIGN(sys_sendto)),
  10077. SYSCALL_NET(SYSCALL_SIGN(sys_socket)),
  10078. SYSCALL_NET(SYSCALL_SIGN(sys_closesocket)),
  10079. SYSCALL_NET(SYSCALL_SIGN(sys_getaddrinfo)),
  10080. SYSCALL_NET(SYSCALL_SIGN(sys_gethostbyname2_r)), /* 85 */
  10081. SYSCALL_NET(SYSCALL_SIGN(sys_sendmsg)),
  10082. SYSCALL_NET(SYSCALL_SIGN(sys_recvmsg)),
  10083. SYSCALL_SIGN(sys_notimpl), /* network */
  10084. SYSCALL_SIGN(sys_notimpl), /* network */
  10085. SYSCALL_SIGN(sys_notimpl), /* network, 90 */
  10086. SYSCALL_SIGN(sys_notimpl), /* network */
  10087. SYSCALL_SIGN(sys_notimpl), /* network */
  10088. SYSCALL_SIGN(sys_notimpl), /* network */
  10089. #ifdef RT_USING_DFS
  10090. SYSCALL_SIGN(sys_select),
  10091. #else
  10092. SYSCALL_SIGN(sys_notimpl),
  10093. #endif
  10094. SYSCALL_SIGN(sys_notimpl), /* SYSCALL_SIGN(sys_hw_interrupt_disable), 95 */
  10095. SYSCALL_SIGN(sys_notimpl), /* SYSCALL_SIGN(sys_hw_interrupt_enable) */
  10096. SYSCALL_SIGN(sys_tick_get),
  10097. SYSCALL_SIGN(sys_exit_group),
  10098. SYSCALL_SIGN(sys_notimpl), /* rt_delayed_work_init */
  10099. SYSCALL_SIGN(sys_notimpl), /* rt_work_submit, 100 */
  10100. SYSCALL_SIGN(sys_notimpl), /* rt_wqueue_wakeup */
  10101. SYSCALL_SIGN(sys_thread_mdelay),
  10102. SYSCALL_SIGN(sys_sigaction),
  10103. SYSCALL_SIGN(sys_sigprocmask),
  10104. SYSCALL_SIGN(sys_tkill), /* 105 */
  10105. SYSCALL_SIGN(sys_thread_sigprocmask),
  10106. #ifdef ARCH_MM_MMU
  10107. SYSCALL_SIGN(sys_cacheflush),
  10108. SYSCALL_SIGN(sys_notimpl),
  10109. SYSCALL_SIGN(sys_notimpl),
  10110. #else
  10111. SYSCALL_SIGN(sys_notimpl),
  10112. SYSCALL_SIGN(sys_lwp_sighandler_set),
  10113. SYSCALL_SIGN(sys_thread_sighandler_set),
  10114. #endif
  10115. SYSCALL_SIGN(sys_waitpid), /* 110 */
  10116. SYSCALL_SIGN(sys_rt_timer_create),
  10117. SYSCALL_SIGN(sys_rt_timer_delete),
  10118. SYSCALL_SIGN(sys_rt_timer_start),
  10119. SYSCALL_SIGN(sys_rt_timer_stop),
  10120. SYSCALL_SIGN(sys_rt_timer_control), /* 115 */
  10121. SYSCALL_SIGN(sys_getcwd),
  10122. SYSCALL_SIGN(sys_chdir),
  10123. SYSCALL_SIGN(sys_unlink),
  10124. SYSCALL_SIGN(sys_mkdir),
  10125. SYSCALL_SIGN(sys_rmdir), /* 120 */
  10126. SYSCALL_SIGN(sys_getdents),
  10127. SYSCALL_SIGN(sys_get_errno),
  10128. #ifdef ARCH_MM_MMU
  10129. SYSCALL_SIGN(sys_set_thread_area),
  10130. SYSCALL_SIGN(sys_set_tid_address),
  10131. #else
  10132. SYSCALL_SIGN(sys_notimpl),
  10133. SYSCALL_SIGN(sys_notimpl),
  10134. #endif
  10135. SYSCALL_SIGN(sys_access), /* 125 */
  10136. SYSCALL_SIGN(sys_pipe),
  10137. SYSCALL_SIGN(sys_clock_settime),
  10138. SYSCALL_SIGN(sys_clock_gettime),
  10139. SYSCALL_SIGN(sys_clock_getres),
  10140. SYSCALL_USPACE(SYSCALL_SIGN(sys_clone)), /* 130 */
  10141. SYSCALL_USPACE(SYSCALL_SIGN(sys_futex)),
  10142. SYSCALL_SIGN(sys_notimpl), /* discarded: sys_pmutex */
  10143. SYSCALL_SIGN(sys_dup),
  10144. SYSCALL_SIGN(sys_dup2),
  10145. SYSCALL_SIGN(sys_rename), /* 135 */
  10146. SYSCALL_USPACE(SYSCALL_SIGN(sys_fork)),
  10147. SYSCALL_USPACE(SYSCALL_SIGN(sys_execve)),
  10148. SYSCALL_USPACE(SYSCALL_SIGN(sys_vfork)),
  10149. SYSCALL_SIGN(sys_gettid),
  10150. SYSCALL_SIGN(sys_prlimit64), /* 140 */
  10151. SYSCALL_SIGN(sys_getrlimit),
  10152. SYSCALL_SIGN(sys_setrlimit),
  10153. SYSCALL_SIGN(sys_setsid),
  10154. SYSCALL_SIGN(sys_getrandom),
  10155. SYSCALL_SIGN(sys_readlink), /* 145 */
  10156. SYSCALL_USPACE(SYSCALL_SIGN(sys_mremap)),
  10157. SYSCALL_USPACE(SYSCALL_SIGN(sys_madvise)),
  10158. SYSCALL_SIGN(sys_sched_setparam),
  10159. SYSCALL_SIGN(sys_sched_getparam),
  10160. SYSCALL_SIGN(sys_sched_get_priority_max), /* 150 */
  10161. SYSCALL_SIGN(sys_sched_get_priority_min),
  10162. SYSCALL_SIGN(sys_sched_setscheduler),
  10163. SYSCALL_SIGN(sys_sched_getscheduler),
  10164. SYSCALL_SIGN(sys_sched_setaffinity),
  10165. SYSCALL_SIGN(sys_fsync), /* 155 */
  10166. SYSCALL_SIGN(sys_clock_nanosleep),
  10167. SYSCALL_SIGN(sys_timer_create),
  10168. SYSCALL_SIGN(sys_timer_delete),
  10169. SYSCALL_SIGN(sys_timer_settime),
  10170. SYSCALL_SIGN(sys_timer_gettime), /* 160 */
  10171. SYSCALL_SIGN(sys_timer_getoverrun),
  10172. SYSCALL_SIGN(sys_mq_open),
  10173. SYSCALL_SIGN(sys_mq_unlink),
  10174. SYSCALL_SIGN(sys_mq_timedsend),
  10175. SYSCALL_SIGN(sys_mq_timedreceive), /* 165 */
  10176. SYSCALL_SIGN(sys_mq_notify),
  10177. SYSCALL_SIGN(sys_mq_getsetattr),
  10178. SYSCALL_SIGN(sys_mq_close),
  10179. SYSCALL_SIGN(sys_lstat),
  10180. SYSCALL_SIGN(sys_uname), /* 170 */
  10181. SYSCALL_SIGN(sys_statfs),
  10182. SYSCALL_SIGN(sys_statfs64),
  10183. SYSCALL_SIGN(sys_fstatfs),
  10184. SYSCALL_SIGN(sys_fstatfs64),
  10185. SYSCALL_SIGN(sys_openat), /* 175 */
  10186. SYSCALL_SIGN(sys_mount),
  10187. SYSCALL_SIGN(sys_umount2),
  10188. SYSCALL_SIGN(sys_link),
  10189. SYSCALL_SIGN(sys_symlink),
  10190. SYSCALL_SIGN(sys_sched_getaffinity), /* 180 */
  10191. SYSCALL_SIGN(sys_sysinfo),
  10192. SYSCALL_SIGN(sys_chmod),
  10193. SYSCALL_SIGN(sys_reboot),
  10194. SYSCALL_SIGN(sys_sched_yield),
  10195. SYSCALL_SIGN(sys_pread64), /* 185 */
  10196. SYSCALL_SIGN(sys_pwrite64),
  10197. SYSCALL_SIGN(sys_sigpending),
  10198. SYSCALL_SIGN(sys_sigtimedwait),
  10199. SYSCALL_SIGN(sys_notimpl),
  10200. SYSCALL_SIGN(sys_notimpl), /* 190 */
  10201. SYSCALL_SIGN(sys_eventfd2),
  10202. SYSCALL_SIGN(sys_epoll_create1),
  10203. SYSCALL_SIGN(sys_epoll_ctl),
  10204. SYSCALL_SIGN(sys_epoll_pwait),
  10205. SYSCALL_SIGN(sys_notimpl), /* 195 */
  10206. SYSCALL_SIGN(sys_timerfd_create),
  10207. SYSCALL_SIGN(sys_timerfd_settime),
  10208. SYSCALL_SIGN(sys_timerfd_gettime),
  10209. SYSCALL_SIGN(sys_signalfd),
  10210. SYSCALL_SIGN(sys_memfd_create), /* 200 */
  10211. SYSCALL_SIGN(sys_ftruncate),
  10212. SYSCALL_SIGN(sys_setitimer),
  10213. SYSCALL_SIGN(sys_utimensat),
  10214. #ifdef RT_USING_POSIX_SOCKET
  10215. SYSCALL_SIGN(sys_syslog),
  10216. SYSCALL_SIGN(sys_socketpair), /* 205 */
  10217. #else
  10218. SYSCALL_SIGN(sys_notimpl),
  10219. SYSCALL_SIGN(sys_notimpl), /* 205 */
  10220. #endif
  10221. SYSCALL_SIGN(sys_wait4),
  10222. SYSCALL_SIGN(sys_set_robust_list),
  10223. SYSCALL_SIGN(sys_get_robust_list),
  10224. SYSCALL_SIGN(sys_setpgid),
  10225. SYSCALL_SIGN(sys_getpgid), /* 210 */
  10226. SYSCALL_SIGN(sys_getsid),
  10227. SYSCALL_SIGN(sys_getppid),
  10228. SYSCALL_SIGN(sys_fchdir),
  10229. SYSCALL_SIGN(sys_chown),
  10230. };
  10231. const void *lwp_get_sys_api(rt_uint32_t number)
  10232. {
  10233. const void *func = (const void *)sys_notimpl;
  10234. if (number == 0xff)
  10235. {
  10236. func = (void *)sys_log;
  10237. }
  10238. else
  10239. {
  10240. number -= 1;
  10241. if (number < sizeof(func_table) / sizeof(func_table[0]))
  10242. {
  10243. func = func_table[number].func;
  10244. }
  10245. else
  10246. {
  10247. if (__sys_log_enable)
  10248. {
  10249. LOG_I("Unimplement syscall %d", number);
  10250. }
  10251. }
  10252. }
  10253. return func;
  10254. }
  10255. const char *lwp_get_syscall_name(rt_uint32_t number)
  10256. {
  10257. const char *name = "sys_notimpl";
  10258. if (number == 0xff)
  10259. {
  10260. name = "sys_log";
  10261. }
  10262. else
  10263. {
  10264. number -= 1;
  10265. if (number < sizeof(func_table) / sizeof(func_table[0]))
  10266. {
  10267. name = (char *)func_table[number].name;
  10268. }
  10269. else
  10270. {
  10271. if (__sys_log_enable)
  10272. {
  10273. LOG_I("Unimplement syscall %d", number);
  10274. }
  10275. }
  10276. }
  10277. /* skip sys_ */
  10278. return name;
  10279. }