1
0

lwp_syscall.c 400 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297
  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))
  3086. != (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_THREAD | CLONE_SYSVSEM))
  3087. {
  3088. return -EINVAL;
  3089. }
  3090. user_stack = arg[1];
  3091. new_tid = (int *)arg[2];
  3092. tls = (void *)arg[3];
  3093. if ((flags & CLONE_PARENT_SETTID) == CLONE_PARENT_SETTID)
  3094. {
  3095. if (!lwp_user_accessable(new_tid, sizeof(int)))
  3096. {
  3097. return -EFAULT;
  3098. }
  3099. }
  3100. self = rt_thread_self();
  3101. lwp = self->lwp;
  3102. lwp_ref_inc(lwp);
  3103. if (!user_stack)
  3104. {
  3105. SET_ERRNO(EINVAL);
  3106. goto fail;
  3107. }
  3108. if ((tid = lwp_tid_get()) == 0)
  3109. {
  3110. SET_ERRNO(ENOMEM);
  3111. goto fail;
  3112. }
  3113. thread = rt_thread_create(self->parent.name,
  3114. RT_NULL,
  3115. RT_NULL,
  3116. self->stack_size,
  3117. RT_SCHED_PRIV(self).init_priority,
  3118. RT_SCHED_PRIV(self).init_tick);
  3119. if (!thread)
  3120. {
  3121. goto fail;
  3122. }
  3123. #ifdef RT_USING_SMP
  3124. RT_SCHED_CTX(self).bind_cpu = lwp->bind_cpu;
  3125. #endif
  3126. thread->cleanup = lwp_cleanup;
  3127. thread->user_entry = RT_NULL;
  3128. thread->user_stack = RT_NULL;
  3129. thread->user_stack_size = 0;
  3130. thread->lwp = (void *)lwp;
  3131. thread->tid = tid;
  3132. if ((flags & CLONE_SETTLS) == CLONE_SETTLS)
  3133. {
  3134. thread->thread_idr = tls;
  3135. }
  3136. if ((flags & CLONE_PARENT_SETTID) == CLONE_PARENT_SETTID)
  3137. {
  3138. *new_tid = (int)(tid);
  3139. }
  3140. if ((flags & CLONE_CHILD_CLEARTID) == CLONE_CHILD_CLEARTID)
  3141. {
  3142. thread->clear_child_tid = (int *)arg[4];
  3143. }
  3144. if (lwp->debug)
  3145. {
  3146. rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  3147. }
  3148. LWP_LOCK(lwp);
  3149. rt_list_insert_after(&lwp->t_grp, &thread->sibling);
  3150. LWP_UNLOCK(lwp);
  3151. /* copy origin stack */
  3152. lwp_memcpy(thread->stack_addr, self->stack_addr, thread->stack_size);
  3153. lwp_tid_set_thread(tid, thread);
  3154. arch_set_thread_context(arch_clone_exit,
  3155. (void *)((char *)thread->stack_addr + thread->stack_size),
  3156. user_stack, &thread->sp);
  3157. /* new thread never reach there */
  3158. rt_thread_startup(thread);
  3159. return (long)tid;
  3160. fail:
  3161. err = GET_ERRNO();
  3162. RT_ASSERT(err < 0);
  3163. lwp_tid_put(tid);
  3164. if (thread)
  3165. {
  3166. rt_thread_delete(thread);
  3167. }
  3168. if (lwp)
  3169. {
  3170. lwp_ref_dec(lwp);
  3171. }
  3172. return (long)err;
  3173. }
  3174. /**
  3175. * @brief Creates a new process or thread (clone).
  3176. *
  3177. * This system call creates a new process or thread by duplicating the calling process.
  3178. * The new process/thread begins execution by calling the function specified in the
  3179. * `arg[]` array, which typically contains the necessary arguments or function pointer.
  3180. * It is used to implement process/thread creation in the system and is often a lower-level
  3181. * operation in process management.
  3182. *
  3183. * @param[in] arg An array of arguments passed to the new process or thread. This could
  3184. * include function pointers, structures, or any necessary data the
  3185. * new process/thread will need to execute its work.
  3186. *
  3187. * @return long Returns a status code or the process/thread ID of the newly created
  3188. * process/thread. On success, it may return a positive value (such as a
  3189. * thread ID). On failure, a negative value indicating the error is returned.
  3190. *
  3191. * @warning Be cautious when using this function as improper management of process/thread
  3192. * creation can lead to resource exhaustion, deadlocks, or other synchronization issues.
  3193. */
  3194. rt_weak long sys_clone(void *arg[])
  3195. {
  3196. return _sys_clone(arg);
  3197. }
  3198. static void lwp_struct_copy(struct rt_lwp *dst, struct rt_lwp *src)
  3199. {
  3200. #ifdef ARCH_MM_MMU
  3201. dst->end_heap = src->end_heap;
  3202. #endif
  3203. dst->lwp_type = src->lwp_type;
  3204. dst->text_entry = src->text_entry;
  3205. dst->text_size = src->text_size;
  3206. dst->data_entry = src->data_entry;
  3207. dst->data_size = src->data_size;
  3208. dst->args = src->args;
  3209. dst->background = src->background;
  3210. dst->tty = src->tty;
  3211. /* terminal API */
  3212. dst->term_ctrlterm = src->term_ctrlterm;
  3213. rt_memcpy(dst->cmd, src->cmd, RT_NAME_MAX);
  3214. if (src->exe_file)
  3215. {
  3216. if (dst->exe_file)
  3217. {
  3218. rt_free(dst->exe_file);
  3219. }
  3220. dst->exe_file = strndup(src->exe_file, DFS_PATH_MAX);
  3221. }
  3222. rt_memcpy(&dst->signal.sig_action, &src->signal.sig_action, sizeof(dst->signal.sig_action));
  3223. rt_memcpy(&dst->signal.sig_action_mask, &src->signal.sig_action_mask, sizeof(dst->signal.sig_action_mask));
  3224. rt_memcpy(&dst->signal.sig_action_nodefer, &src->signal.sig_action_nodefer, sizeof(dst->signal.sig_action_nodefer));
  3225. rt_memcpy(&dst->signal.sig_action_onstack, &src->signal.sig_action_onstack, sizeof(dst->signal.sig_action_onstack));
  3226. rt_memcpy(&dst->signal.sig_action_restart, &dst->signal.sig_action_restart, sizeof(dst->signal.sig_action_restart));
  3227. rt_memcpy(&dst->signal.sig_action_siginfo, &dst->signal.sig_action_siginfo, sizeof(dst->signal.sig_action_siginfo));
  3228. rt_memcpy(&dst->signal.sig_action_nocldstop, &dst->signal.sig_action_nocldstop, sizeof(dst->signal.sig_action_nocldstop));
  3229. rt_memcpy(&dst->signal.sig_action_nocldwait, &dst->signal.sig_action_nocldwait, sizeof(dst->signal.sig_action_nocldwait));
  3230. rt_strcpy(dst->working_directory, src->working_directory);
  3231. }
  3232. static int lwp_copy_files(struct rt_lwp *dst, struct rt_lwp *src)
  3233. {
  3234. struct dfs_fdtable *dst_fdt;
  3235. struct dfs_fdtable *src_fdt;
  3236. src_fdt = &src->fdt;
  3237. dst_fdt = &dst->fdt;
  3238. /* init fds */
  3239. dst_fdt->fds = rt_calloc(src_fdt->maxfd, sizeof(void *));
  3240. if (dst_fdt->fds)
  3241. {
  3242. struct dfs_file *d_s;
  3243. int i;
  3244. dst_fdt->maxfd = src_fdt->maxfd;
  3245. dfs_file_lock();
  3246. /* dup files */
  3247. for (i = 0; i < src_fdt->maxfd; i++)
  3248. {
  3249. d_s = fdt_get_file(src_fdt, i);
  3250. if (d_s)
  3251. {
  3252. dst_fdt->fds[i] = d_s;
  3253. d_s->ref_count++;
  3254. }
  3255. }
  3256. dfs_file_unlock();
  3257. return 0;
  3258. }
  3259. return -RT_ERROR;
  3260. }
  3261. sysret_t _sys_fork(void)
  3262. {
  3263. int tid = 0;
  3264. sysret_t falival = 0;
  3265. struct rt_lwp *lwp = RT_NULL;
  3266. struct rt_lwp *self_lwp = RT_NULL;
  3267. rt_thread_t thread = RT_NULL;
  3268. rt_thread_t self_thread = RT_NULL;
  3269. void *user_stack = RT_NULL;
  3270. rt_processgroup_t group;
  3271. /* new lwp */
  3272. lwp = lwp_create(LWP_CREATE_FLAG_ALLOC_PID);
  3273. if (!lwp)
  3274. {
  3275. SET_ERRNO(ENOMEM);
  3276. goto fail;
  3277. }
  3278. /* new tid */
  3279. if ((tid = lwp_tid_get()) == 0)
  3280. {
  3281. SET_ERRNO(ENOMEM);
  3282. goto fail;
  3283. }
  3284. /* user space init */
  3285. if (lwp_user_space_init(lwp, 1) != 0)
  3286. {
  3287. SET_ERRNO(ENOMEM);
  3288. goto fail;
  3289. }
  3290. self_lwp = lwp_self();
  3291. /* copy address space of process from this proc to forked one */
  3292. if (lwp_fork_aspace(lwp, self_lwp) != 0)
  3293. {
  3294. SET_ERRNO(ENOMEM);
  3295. goto fail;
  3296. }
  3297. /* copy lwp struct data */
  3298. lwp_struct_copy(lwp, self_lwp);
  3299. /* copy files */
  3300. if (lwp_copy_files(lwp, self_lwp) != 0)
  3301. {
  3302. SET_ERRNO(ENOMEM);
  3303. goto fail;
  3304. }
  3305. /* create thread */
  3306. self_thread = rt_thread_self();
  3307. thread = rt_thread_create(self_thread->parent.name,
  3308. RT_NULL,
  3309. RT_NULL,
  3310. self_thread->stack_size,
  3311. RT_SCHED_PRIV(self_thread).init_priority,
  3312. RT_SCHED_PRIV(self_thread).init_tick);
  3313. if (!thread)
  3314. {
  3315. SET_ERRNO(ENOMEM);
  3316. goto fail;
  3317. }
  3318. thread->cleanup = self_thread->cleanup;
  3319. thread->user_entry = self_thread->user_entry;
  3320. thread->user_stack = self_thread->user_stack;
  3321. thread->user_stack_size = self_thread->user_stack_size;
  3322. thread->signal.sigset_mask = self_thread->signal.sigset_mask;
  3323. thread->thread_idr = self_thread->thread_idr;
  3324. thread->clear_child_tid = self_thread->clear_child_tid;
  3325. thread->lwp = (void *)lwp;
  3326. thread->tid = tid;
  3327. LWP_LOCK(self_lwp);
  3328. /* add thread to lwp process */
  3329. rt_list_insert_after(&lwp->t_grp, &thread->sibling);
  3330. LWP_UNLOCK(self_lwp);
  3331. lwp_children_register(self_lwp, lwp);
  3332. /* set pgid and sid */
  3333. group = lwp_pgrp_find(lwp_pgid_get_byprocess(self_lwp));
  3334. if (group)
  3335. {
  3336. lwp_pgrp_insert(group, lwp);
  3337. }
  3338. else
  3339. {
  3340. LOG_W("the process group of pid: %d cannot be found", lwp_pgid_get_byprocess(self_lwp));
  3341. }
  3342. /* copy kernel stack context from self thread */
  3343. lwp_memcpy(thread->stack_addr, self_thread->stack_addr, self_thread->stack_size);
  3344. lwp_tid_set_thread(tid, thread);
  3345. /* duplicate user objects */
  3346. lwp_user_object_dup(lwp, self_lwp);
  3347. user_stack = arch_get_user_sp();
  3348. arch_set_thread_context(arch_fork_exit,
  3349. (void *)((char *)thread->stack_addr + thread->stack_size),
  3350. user_stack, &thread->sp);
  3351. rt_thread_startup(thread);
  3352. return lwp_to_pid(lwp);
  3353. fail:
  3354. falival = GET_ERRNO();
  3355. if (tid != 0)
  3356. {
  3357. lwp_tid_put(tid);
  3358. }
  3359. if (thread)
  3360. {
  3361. rt_thread_delete(thread);
  3362. }
  3363. if (lwp)
  3364. {
  3365. lwp_ref_dec(lwp);
  3366. }
  3367. return falival;
  3368. }
  3369. /* arm needs to wrap fork/clone call to preserved lr & caller saved regs */
  3370. /**
  3371. * @brief Creates a child process by duplicating the calling process.
  3372. *
  3373. * This system call creates a new child process by duplicating the calling process. The
  3374. * new child process is a copy of the parent process, except for the returned value.
  3375. * The child process starts executing from the point of the fork, but the return value
  3376. * differs between the parent and child: the parent receives the process ID (PID) of the
  3377. * child, and the child receives a return value of 0.
  3378. *
  3379. * @return sysret_t Returns a status code indicating the result of the operation:
  3380. * - A positive value (the child's PID) is returned to the parent.
  3381. * - A value of 0 is returned to the child process.
  3382. * - A negative value indicates an error (e.g., resource limits exceeded).
  3383. *
  3384. * @note This function is commonly used in operating systems to create new processes.
  3385. *
  3386. * @warning Be aware that improper management of child processes (such as failing to handle
  3387. * process termination or excessive forking) can lead to resource exhaustion or
  3388. * other system issues. Ensure proper process handling in the parent and child
  3389. * processes to avoid leaks and inconsistencies.
  3390. */
  3391. rt_weak sysret_t sys_fork(void)
  3392. {
  3393. return _sys_fork();
  3394. }
  3395. rt_weak sysret_t sys_vfork(void)
  3396. {
  3397. return sys_fork();
  3398. }
  3399. #define _swap_lwp_data(lwp_used, lwp_new, type, member) \
  3400. do {\
  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. void (*handler)(int);
  5822. unsigned long flags;
  5823. void (*restorer)(void);
  5824. unsigned mask[2];
  5825. };
  5826. /**
  5827. * @brief Changes the action taken by the system on receiving a signal.
  5828. *
  5829. * This system call allows a process to specify how signals should be handled. It allows you to set a
  5830. * new action for a specific signal, retrieve the old action, and define the signal mask that should
  5831. * be applied during the execution of the signal handler.
  5832. *
  5833. * @param[in] sig The signal number for which the action is to be set or retrieved.
  5834. * Signal numbers are typically defined as constants (e.g., `SIGINT`, `SIGTERM`).
  5835. * @param[in] act A pointer to a `k_sigaction` structure that specifies the new action for the signal.
  5836. * If `act` is `NULL`, the signal's action is not changed.
  5837. * @param[out] oact A pointer to a `k_sigaction` structure where the old action will be stored.
  5838. * If `oact` is `NULL`, the old action is not retrieved.
  5839. * @param[in] sigsetsize The size of the `sigset_t` structure used in `k_sigaction`. This is to ensure the
  5840. * compatibility with the signal mask size.
  5841. *
  5842. * @return sysret_t Returns `0` on success or a negative error code on failure.
  5843. *
  5844. * @note The `k_sigaction` structure allows you to specify the signal handler, signal mask, and flags for
  5845. * the signal action. It is important to correctly configure the handler to prevent unexpected
  5846. * behavior in the signal handling process.
  5847. *
  5848. * @warning Be cautious when modifying signal handling behavior, as incorrect configuration may result
  5849. * in unhandled signals or undefined behavior. Signal handlers should be designed to perform
  5850. * minimal, safe operations.
  5851. *
  5852. * @see sys_signal(), sys_sigprocmask()
  5853. */
  5854. sysret_t sys_sigaction(int sig, const struct k_sigaction *act,
  5855. struct k_sigaction *oact, size_t sigsetsize)
  5856. {
  5857. int ret = -RT_EINVAL;
  5858. struct rt_lwp *lwp;
  5859. struct lwp_sigaction kact, *pkact = RT_NULL;
  5860. struct lwp_sigaction koact, *pkoact = RT_NULL;
  5861. if (!sigsetsize)
  5862. {
  5863. SET_ERRNO(EINVAL);
  5864. goto out;
  5865. }
  5866. if (sigsetsize > sizeof(lwp_sigset_t))
  5867. {
  5868. sigsetsize = sizeof(lwp_sigset_t);
  5869. }
  5870. if (!act && !oact)
  5871. {
  5872. SET_ERRNO(EINVAL);
  5873. goto out;
  5874. }
  5875. if (oact)
  5876. {
  5877. if (!lwp_user_accessable((void *)oact, sizeof(*oact)))
  5878. {
  5879. SET_ERRNO(EFAULT);
  5880. goto out;
  5881. }
  5882. pkoact = &koact;
  5883. }
  5884. if (act)
  5885. {
  5886. if (!lwp_user_accessable((void *)act, sizeof(*act)))
  5887. {
  5888. SET_ERRNO(EFAULT);
  5889. goto out;
  5890. }
  5891. kact.sa_flags = act->flags;
  5892. kact.__sa_handler._sa_handler = act->handler;
  5893. lwp_memcpy(&kact.sa_mask, &act->mask, sigsetsize);
  5894. kact.sa_restorer = act->restorer;
  5895. pkact = &kact;
  5896. }
  5897. lwp = lwp_self();
  5898. RT_ASSERT(lwp);
  5899. ret = lwp_signal_action(lwp, sig, pkact, pkoact);
  5900. #ifdef ARCH_MM_MMU
  5901. if (ret == 0 && oact)
  5902. {
  5903. lwp_put_to_user(&oact->handler, &pkoact->__sa_handler._sa_handler, sizeof(void (*)(int)));
  5904. lwp_put_to_user(&oact->mask, &pkoact->sa_mask, sigsetsize);
  5905. lwp_put_to_user(&oact->flags, &pkoact->sa_flags, sizeof(int));
  5906. lwp_put_to_user(&oact->restorer, &pkoact->sa_restorer, sizeof(void (*)(void)));
  5907. }
  5908. #endif /* ARCH_MM_MMU */
  5909. out:
  5910. return (ret < 0 ? GET_ERRNO() : ret);
  5911. }
  5912. static int mask_command_u2k[] = {
  5913. [SIG_BLOCK] = LWP_SIG_MASK_CMD_BLOCK,
  5914. [SIG_UNBLOCK] = LWP_SIG_MASK_CMD_UNBLOCK,
  5915. [SIG_SETMASK] = LWP_SIG_MASK_CMD_SET_MASK,
  5916. };
  5917. /**
  5918. * @brief Sets or retrieves the signal mask for the calling process.
  5919. *
  5920. * This system call allows the caller to block or unblock signals by modifying the signal mask. The signal
  5921. * mask determines which signals are blocked and which signals can be delivered to the process. The
  5922. * function can also be used to retrieve the current signal mask.
  5923. *
  5924. * @param[in] how The action to be taken on the signal mask. It can be one of the following values:
  5925. * - `SIG_BLOCK`: Add the signals in `sigset` to the current mask.
  5926. * - `SIG_UNBLOCK`: Remove the signals in `sigset` from the current mask.
  5927. * - `SIG_SETMASK`: Set the signal mask to the value in `sigset`, replacing the current mask.
  5928. * @param[in] sigset A pointer to a `sigset_t` structure that specifies the signals to be blocked or unblocked.
  5929. * This parameter is ignored when `how` is `SIG_SETMASK`, in which case `sigset` is used
  5930. * as the new signal mask.
  5931. * @param[out] oset A pointer to a `sigset_t` structure where the previous signal mask will be stored.
  5932. * If `oset` is `NULL`, the previous signal mask will not be returned.
  5933. * @param[in] size The size of the `sigset_t` structure, ensuring compatibility with the signal mask.
  5934. *
  5935. * @return sysret_t Returns `0` on success or a negative error code on failure.
  5936. *
  5937. * @note Modifying the signal mask prevents signals from being delivered to the process while they are blocked.
  5938. * Once the signals are unblocked, they will be delivered to the process if they are pending.
  5939. *
  5940. * @warning Be careful when blocking signals, especially critical ones like `SIGKILL`, as it may interfere
  5941. * with the normal operation of the system. Ensure that signal masks are managed carefully to avoid
  5942. * missing important signals.
  5943. *
  5944. * @see sys_sigaction(), sys_sigpending()
  5945. */
  5946. sysret_t sys_sigprocmask(int how, const sigset_t *sigset, sigset_t *oset, size_t size)
  5947. {
  5948. int ret = -1;
  5949. lwp_sigset_t *pnewset = RT_NULL, *poldset = RT_NULL;
  5950. #ifdef ARCH_MM_MMU
  5951. lwp_sigset_t newset, oldset;
  5952. #endif /* ARCH_MM_MMU*/
  5953. if (!size)
  5954. {
  5955. return -EINVAL;
  5956. }
  5957. if (!oset && !sigset)
  5958. {
  5959. return -EINVAL;
  5960. }
  5961. if (size > sizeof(lwp_sigset_t))
  5962. {
  5963. size = sizeof(lwp_sigset_t);
  5964. }
  5965. if (oset)
  5966. {
  5967. #ifdef ARCH_MM_MMU
  5968. if (!lwp_user_accessable((void *)oset, size))
  5969. {
  5970. return -EFAULT;
  5971. }
  5972. poldset = &oldset;
  5973. #else
  5974. if (!lwp_user_accessable((void *)oset, size))
  5975. {
  5976. return -EFAULT;
  5977. }
  5978. poldset = (lwp_sigset_t *)oset;
  5979. #endif
  5980. }
  5981. if (sigset)
  5982. {
  5983. #ifdef ARCH_MM_MMU
  5984. if (!lwp_user_accessable((void *)sigset, size))
  5985. {
  5986. return -EFAULT;
  5987. }
  5988. lwp_get_from_user(&newset, (void *)sigset, size);
  5989. pnewset = &newset;
  5990. #else
  5991. if (!lwp_user_accessable((void *)sigset, size))
  5992. {
  5993. return -EFAULT;
  5994. }
  5995. pnewset = (lwp_sigset_t *)sigset;
  5996. #endif /* ARCH_MM_MMU */
  5997. }
  5998. ret = lwp_thread_signal_mask(rt_thread_self(), mask_command_u2k[how], pnewset, poldset);
  5999. #ifdef ARCH_MM_MMU
  6000. if (ret < 0)
  6001. {
  6002. return ret;
  6003. }
  6004. if (oset)
  6005. {
  6006. lwp_put_to_user(oset, poldset, size);
  6007. }
  6008. #endif /* ARCH_MM_MMU */
  6009. return (ret < 0 ? -EFAULT: ret);
  6010. }
  6011. /**
  6012. * @brief Retrieves the set of signals that are pending for delivery to the calling process.
  6013. *
  6014. * This system call allows a process to query the set of signals that are pending, i.e., signals that have
  6015. * been sent to the process but have not yet been delivered because the process is blocking those signals
  6016. * or has not yet handled them. The function returns the set of signals that are waiting to be delivered.
  6017. *
  6018. * @param[out] sigset A pointer to a `sigset_t` structure where the set of pending signals will be stored.
  6019. * The `sigset_t` structure will contain the signals that are pending for delivery.
  6020. * @param[in] sigsize The size of the `sigset_t` structure, used to ensure compatibility with the signal set.
  6021. *
  6022. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6023. *
  6024. * @note The returned signal set will contain the signals that have been sent to the process but are blocked,
  6025. * or that are waiting to be handled. These signals will be delivered once they are unblocked or the
  6026. * process handles them.
  6027. *
  6028. * @warning Be cautious when querying pending signals, as unblocking too many signals at once may lead
  6029. * to unexpected behavior or a flood of signal deliveries. It's recommended to carefully manage
  6030. * the signals the process can accept at any given time.
  6031. *
  6032. * @see sys_sigaction(), sys_sigprocmask()
  6033. */
  6034. sysret_t sys_sigpending(sigset_t *sigset, size_t sigsize)
  6035. {
  6036. sysret_t ret = 0;
  6037. lwp_sigset_t lwpset;
  6038. /* Verify and Get sigset, timeout */
  6039. if (!sigset || !lwp_user_accessable((void *)sigset, sigsize))
  6040. {
  6041. ret = -EFAULT;
  6042. }
  6043. else
  6044. {
  6045. /* Fit sigset size to lwp set */
  6046. if (sizeof(lwpset) < sigsize)
  6047. {
  6048. LOG_I("%s: sigsize (%lx) extends lwp sigset chunk\n", __func__, sigsize);
  6049. sigsize = sizeof(lwpset);
  6050. }
  6051. lwp_thread_signal_pending(rt_thread_self(), &lwpset);
  6052. if (!lwp_put_to_user(sigset, &lwpset, sigsize))
  6053. RT_ASSERT(0); /* should never happened */
  6054. }
  6055. return ret;
  6056. }
  6057. /**
  6058. * @brief Waits for a signal to be delivered, with a timeout.
  6059. *
  6060. * This system call allows a process to wait for one of the signals specified in the `sigset` to be delivered.
  6061. * The process will block until a signal in the set is received or the specified timeout period expires.
  6062. * If the signal is received before the timeout, information about the signal will be returned in the `siginfo_t` structure.
  6063. * If the timeout expires without any signal being delivered, the function will return with an appropriate error code.
  6064. *
  6065. * @param[in] sigset A pointer to a `sigset_t` structure that specifies the set of signals to wait for.
  6066. * The function will block until a signal in this set is received, or the timeout expires.
  6067. * @param[out] info A pointer to a `siginfo_t` structure where information about the delivered signal will be stored.
  6068. * If no signal is received before the timeout, this structure will not be filled.
  6069. * @param[in] timeout A pointer to a `timespec` structure that specifies the maximum amount of time to wait
  6070. * for a signal to be delivered. If this value is `NULL`, the function will wait indefinitely.
  6071. * @param[in] sigsize The size of the `sigset_t` structure, ensuring compatibility with the signal set.
  6072. *
  6073. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6074. *
  6075. * @note If the `timeout` is `NULL`, the function will block indefinitely until a signal is delivered.
  6076. * If a signal is received, the corresponding information is returned in the `siginfo_t` structure.
  6077. * The `sigset` should contain only the signals you are interested in.
  6078. *
  6079. * @warning If the timeout expires, no signal will be delivered, and the function will return a timeout error.
  6080. * Make sure to handle the timeout case correctly to prevent any unexpected behavior.
  6081. *
  6082. * @see sys_sigaction(), sys_sigtimedwait()
  6083. */
  6084. sysret_t sys_sigtimedwait(const sigset_t *sigset, siginfo_t *info, const struct timespec *timeout, size_t sigsize)
  6085. {
  6086. int sig;
  6087. size_t ret;
  6088. lwp_sigset_t lwpset;
  6089. siginfo_t kinfo;
  6090. struct timespec ktimeout;
  6091. struct timespec *ptimeout;
  6092. /* for RT_ASSERT */
  6093. RT_UNUSED(ret);
  6094. /* Fit sigset size to lwp set */
  6095. if (sizeof(lwpset) < sigsize)
  6096. {
  6097. LOG_I("%s: sigsize (%lx) extends lwp sigset chunk\n", __func__, sigsize);
  6098. sigsize = sizeof(lwpset);
  6099. }
  6100. else
  6101. {
  6102. /* if sigset of user is smaller, clear extra space */
  6103. memset(&lwpset, 0, sizeof(lwpset));
  6104. }
  6105. /* Verify and Get sigset, timeout */
  6106. if (!sigset || !lwp_user_accessable((void *)sigset, sigsize))
  6107. {
  6108. return -EFAULT;
  6109. }
  6110. else
  6111. {
  6112. ret = lwp_get_from_user(&lwpset, (void *)sigset, sigsize);
  6113. RT_ASSERT(ret == sigsize);
  6114. }
  6115. if (timeout)
  6116. {
  6117. if (!lwp_user_accessable((void *)timeout, sizeof(*timeout)))
  6118. return -EFAULT;
  6119. else
  6120. {
  6121. ret = lwp_get_from_user(&ktimeout, (void *)timeout, sizeof(*timeout));
  6122. ptimeout = &ktimeout;
  6123. RT_ASSERT(ret == sizeof(*timeout));
  6124. }
  6125. }
  6126. else
  6127. {
  6128. ptimeout = RT_NULL;
  6129. }
  6130. sig = lwp_thread_signal_timedwait(rt_thread_self(), &lwpset, &kinfo, ptimeout);
  6131. if (sig > 0 && info)
  6132. {
  6133. if (!lwp_user_accessable((void *)info, sizeof(*info)))
  6134. return -EFAULT;
  6135. else
  6136. {
  6137. ret = lwp_put_to_user(info, &kinfo, sizeof(*info));
  6138. RT_ASSERT(ret == sizeof(*info));
  6139. }
  6140. }
  6141. return sig;
  6142. }
  6143. /**
  6144. * @brief Sends a signal to a specific thread.
  6145. *
  6146. * This system call allows a process to send a signal to a specific thread within the same process.
  6147. * The signal specified by the `sig` parameter will be delivered to the thread with the ID `tid`.
  6148. * This function is similar to `kill()`, but it targets a specific thread rather than a process.
  6149. *
  6150. * @param[in] tid The thread ID to which the signal will be sent. This ID identifies the target thread within the same process.
  6151. * @param[in] sig The signal number to be sent to the specified thread. The signal can be any valid signal number.
  6152. *
  6153. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6154. *
  6155. * @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.
  6156. * If the target thread does not exist or is not eligible to receive the signal, the function will fail.
  6157. *
  6158. * @warning If an invalid signal number is provided or the target thread does not exist, an error will be returned.
  6159. * Be careful when sending signals, as some signals (e.g., `SIGKILL`) can immediately terminate the target thread.
  6160. *
  6161. * @see sys_kill(), sys_sigaction()
  6162. */
  6163. sysret_t sys_tkill(int tid, int sig)
  6164. {
  6165. #ifdef ARCH_MM_MMU
  6166. rt_thread_t thread;
  6167. sysret_t ret;
  6168. /**
  6169. * Brief: Match a tid and do the kill
  6170. *
  6171. * Note: Critical Section
  6172. * - the thread (READ. may be released at the meantime; protected by locked)
  6173. */
  6174. thread = lwp_tid_get_thread_and_inc_ref(tid);
  6175. ret = lwp_thread_signal_kill(thread, sig, SI_USER, 0);
  6176. lwp_tid_dec_ref(thread);
  6177. return ret;
  6178. #else
  6179. return lwp_thread_kill((rt_thread_t)tid, sig);
  6180. #endif
  6181. }
  6182. /**
  6183. * @brief Manipulates the signal mask for the current thread.
  6184. *
  6185. * This function allows a thread to modify its signal mask, which controls which signals are blocked (prevented from delivery).
  6186. * The signal mask can be modified by adding, removing, or setting the signal set as a whole, depending on the `how` parameter.
  6187. * The `sigset` specifies the signals to be manipulated, and the current signal mask before modification can be retrieved in `oset`.
  6188. *
  6189. * @param[in] how The operation to perform on the signal mask. It can be one of the following values:
  6190. * - `SIG_BLOCK`: Add the signals in `sigset` to the current mask (block those signals).
  6191. * - `SIG_UNBLOCK`: Remove the signals in `sigset` from the current mask (unblock those signals).
  6192. * - `SIG_SETMASK`: Set the signal mask to the signals specified in `sigset` (replace the current mask).
  6193. * @param[in] sigset A pointer to an `lwp_sigset_t` structure that specifies the set of signals to be manipulated.
  6194. * Signals in this set will be added, removed, or set in the current thread's signal mask based on the `how` parameter.
  6195. * @param[out] oset A pointer to an `lwp_sigset_t` structure where the previous signal mask will be stored.
  6196. * This allows the caller to restore the previous mask if needed.
  6197. * @param[in] size The size of the `lwp_sigset_t` structure. This ensures that the correct structure size is used during signal mask manipulation.
  6198. *
  6199. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6200. *
  6201. * @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`.
  6202. * If `how` is `SIG_BLOCK` or `SIG_UNBLOCK`, the signals in `sigset` will be added or removed from the current mask, respectively.
  6203. *
  6204. * @warning Be cautious when modifying the signal mask, as blocking signals can cause the thread to miss important signals.
  6205. * 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.
  6206. *
  6207. * @see sys_sigaction(), sys_thread_sigpending()
  6208. */
  6209. sysret_t sys_thread_sigprocmask(int how, const lwp_sigset_t *sigset, lwp_sigset_t *oset, size_t size)
  6210. {
  6211. int ret = -1;
  6212. lwp_sigset_t *pnewset = RT_NULL, *poldset = RT_NULL;
  6213. #ifdef ARCH_MM_MMU
  6214. lwp_sigset_t newset, oldset;
  6215. #endif /* ARCH_MM_MMU */
  6216. if (!size)
  6217. {
  6218. return -EINVAL;
  6219. }
  6220. if (!oset && !sigset)
  6221. {
  6222. return -EINVAL;
  6223. }
  6224. if (size != sizeof(lwp_sigset_t))
  6225. {
  6226. return -EINVAL;
  6227. }
  6228. if (oset)
  6229. {
  6230. #ifdef ARCH_MM_MMU
  6231. if (!lwp_user_accessable((void *)oset, size))
  6232. {
  6233. return -EFAULT;
  6234. }
  6235. poldset = &oldset;
  6236. #else
  6237. if (!lwp_user_accessable((void *)oset, size))
  6238. {
  6239. return -EFAULT;
  6240. }
  6241. poldset = oset;
  6242. #endif
  6243. }
  6244. if (sigset)
  6245. {
  6246. #ifdef ARCH_MM_MMU
  6247. if (!lwp_user_accessable((void *)sigset, size))
  6248. {
  6249. return -EFAULT;
  6250. }
  6251. lwp_get_from_user(&newset, (void *)sigset, sizeof(lwp_sigset_t));
  6252. pnewset = &newset;
  6253. #else
  6254. if (!lwp_user_accessable((void *)sigset, size))
  6255. {
  6256. return -EFAULT;
  6257. }
  6258. pnewset = (lwp_sigset_t *)sigset;
  6259. #endif
  6260. }
  6261. ret = lwp_thread_signal_mask(rt_thread_self(), mask_command_u2k[how], pnewset, poldset);
  6262. if (ret < 0)
  6263. {
  6264. return ret;
  6265. }
  6266. #ifdef ARCH_MM_MMU
  6267. if (oset)
  6268. {
  6269. lwp_put_to_user(oset, poldset, sizeof(lwp_sigset_t));
  6270. }
  6271. #endif
  6272. return (ret < 0 ? -EFAULT: ret);
  6273. }
  6274. #ifndef ARCH_MM_MMU
  6275. /**
  6276. * @brief Sets the signal handler for a specific signal in the current thread.
  6277. *
  6278. * This function allows a thread to set a custom signal handler for a specific signal.
  6279. * When the specified signal is received, the corresponding handler function (`func`) will be invoked.
  6280. * The handler will be executed in the context of the current thread, allowing it to handle signals as needed.
  6281. *
  6282. * @param[in] sig The signal number for which the handler is being set. This should be a valid signal number.
  6283. * @param[in] func The signal handler function to be set. This function will be called when the specified signal is received.
  6284. * The signature of `func` should match the expected format for signal handlers.
  6285. *
  6286. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6287. *
  6288. * @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.
  6289. * The handler function typically has the signature: `void handler(int sig)`, where `sig` is the signal number.
  6290. *
  6291. * @warning Setting a custom signal handler may override any default actions for that signal.
  6292. * It is important to ensure that the handler function is properly designed to handle the signal appropriately.
  6293. * For example, some signals may require special handling (e.g., `SIGKILL` cannot be caught).
  6294. *
  6295. * @see sys_signal(), sys_lwp_sigaction()
  6296. */
  6297. sysret_t sys_lwp_sighandler_set(int sig, lwp_sighandler_t func)
  6298. {
  6299. if (!lwp_user_accessable((void *)func, sizeof(lwp_sighandler_t)))
  6300. {
  6301. return -EFAULT;
  6302. }
  6303. lwp_sighandler_set(sig, func);
  6304. return 0;
  6305. }
  6306. /**
  6307. * @brief Sets the signal handler for a specific signal in the target thread.
  6308. *
  6309. * This function allows setting a custom signal handler for a specific signal within a particular thread.
  6310. * When the specified signal is delivered to the thread, the corresponding handler function (`func`) will be invoked.
  6311. * The handler is executed in the context of the thread that receives the signal.
  6312. *
  6313. * @param[in] sig The signal number for which the handler is being set. This should be a valid signal number.
  6314. * @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.
  6315. * The handler function should have the signature `void func(int sig)`.
  6316. *
  6317. * @return sysret_t Returns `0` on success or a negative error code on failure.
  6318. *
  6319. * @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.
  6320. * The handler function typically has the signature: `void handler(int sig)`, where `sig` is the signal number.
  6321. *
  6322. * @warning Setting a custom signal handler may override any default actions for that signal.
  6323. * It is important to ensure that the handler function is properly designed to handle the signal appropriately.
  6324. * For example, some signals may require special handling (e.g., `SIGKILL` cannot be caught).
  6325. *
  6326. * @see sys_thread_sigprocmask(), sys_thread_sigaction(), sys_signal()
  6327. */
  6328. sysret_t sys_thread_sighandler_set(int sig, lwp_sighandler_t func)
  6329. {
  6330. if (!lwp_user_accessable((void *)func, sizeof(lwp_sighandler_t)))
  6331. {
  6332. return -EFAULT;
  6333. }
  6334. lwp_thread_sighandler_set(sig, func);
  6335. return 0;
  6336. }
  6337. #endif /* not defined ARCH_MM_MMU */
  6338. /**
  6339. * @brief Waits for the termination of a child process.
  6340. *
  6341. * This function makes the calling process wait until one of its child processes terminates or until a
  6342. * specified condition is met. The function retrieves information about the terminated child process,
  6343. * including its exit status, and can also handle other process-related events, such as stopping or
  6344. * continuing execution.
  6345. *
  6346. * @param[in] pid The process ID of the child process to wait for. If `pid` is:
  6347. * - `-1`: Wait for any child process.
  6348. * - `0`: Wait for any child process in the same process group.
  6349. * - > 0: Wait for the child process with the specified process ID.
  6350. * @param[out] status A pointer to an integer where the exit status of the terminated child process will be stored.
  6351. * This value provides information about the child's termination status, such as normal exit,
  6352. * signal termination, etc.
  6353. * @param[in] options A bitmask of options that control the behavior of the function. It can include:
  6354. * - `WNOHANG`: Return immediately if no child has exited.
  6355. * - `WUNTRACED`: Report status of stopped child processes.
  6356. * - Other flags can be defined depending on the implementation.
  6357. *
  6358. * @return sysret_t Returns the process ID of the child process that terminated on success, or a negative error code on failure.
  6359. *
  6360. * @note The `status` argument provides detailed information about the termination of the child process. To interpret this
  6361. * status, macros such as `WIFEXITED()`, `WIFSIGNALED()`, and `WEXITSTATUS()` are commonly used.
  6362. *
  6363. * @warning This function should be used carefully when managing child processes, as not properly handling child processes
  6364. * may lead to zombie processes.
  6365. *
  6366. * @see sys_wait(), sys_waitid()
  6367. */
  6368. sysret_t sys_waitpid(int32_t pid, int *status, int options)
  6369. {
  6370. int ret = -1;
  6371. #ifdef ARCH_MM_MMU
  6372. if (!lwp_user_accessable((void *)status, sizeof(int)))
  6373. {
  6374. return -EFAULT;
  6375. }
  6376. else
  6377. {
  6378. ret = lwp_waitpid(pid, status, options, RT_NULL);
  6379. }
  6380. #else
  6381. if (!lwp_user_accessable((void *)status, sizeof(int)))
  6382. {
  6383. return -EFAULT;
  6384. }
  6385. ret = waitpid(pid, status, options);
  6386. #endif
  6387. return ret;
  6388. }
  6389. #if defined(RT_USING_SAL) && defined(SAL_USING_POSIX)
  6390. struct musl_addrinfo
  6391. {
  6392. int ai_flags;
  6393. int ai_family;
  6394. int ai_socktype;
  6395. int ai_protocol;
  6396. socklen_t ai_addrlen;
  6397. struct musl_sockaddr *ai_addr;
  6398. char *ai_canonname;
  6399. struct musl_addrinfo *ai_next;
  6400. };
  6401. /**
  6402. * @brief Resolves network addresses and service names into a list of address structures.
  6403. *
  6404. * This function provides a mechanism for resolving a host name and service name (or port number)
  6405. * into a list of address structures suitable for use with socket-based communication. The function
  6406. * can handle both IPv4 and IPv6 addresses and provides a flexible way to specify different types
  6407. * of address and service resolution options.
  6408. *
  6409. * @param[in] nodename The host name to be resolved. This can be a DNS name or an IP address in string format.
  6410. * If `nodename` is `NULL`, the function will resolve the local host.
  6411. * @param[in] servname The service name (e.g., "http") or port number to be resolved. If `servname` is `NULL`,
  6412. * the function will resolve the port number or address without any service association.
  6413. * @param[in] hints A pointer to a `struct musl_addrinfo` that provides hints for the address resolution.
  6414. * It can be used to specify criteria such as the desired address family (IPv4 or IPv6),
  6415. * socket type, protocol, and flags for resolution.
  6416. * @param[out] res A pointer to a `struct musl_addrinfo` that will be filled with the resolved address
  6417. * information. The resulting linked list will contain one or more `struct musl_sockaddr`
  6418. * structures, each representing a different address that can be used for communication.
  6419. *
  6420. * @return sysret_t Returns `0` on success, indicating that the address resolution was successful.
  6421. * On failure, returns a negative error code.
  6422. *
  6423. * @note The `res` parameter points to a linked list of resolved address structures. Each node in the list
  6424. * contains a different resolved address and can be used for socket connection purposes.
  6425. * It is important to free the memory allocated for the list after it is no longer needed, using `freeaddrinfo()`.
  6426. *
  6427. * @warning The `hints` structure allows you to specify various options for the resolution. However, incorrect
  6428. * hints may lead to unexpected or incorrect results. For example, if you request IPv6 addresses but
  6429. * the host only supports IPv4, the function may not return the expected results.
  6430. *
  6431. * @see freeaddrinfo(), sys_socket(), sys_connect(), sys_gethostbyname(), sys_gethostbyaddr()
  6432. */
  6433. sysret_t sys_getaddrinfo(const char *nodename,
  6434. const char *servname,
  6435. const struct musl_addrinfo *hints,
  6436. struct musl_addrinfo *res)
  6437. {
  6438. int ret = -1;
  6439. struct addrinfo *k_res = NULL;
  6440. char *k_nodename = NULL;
  6441. char *k_servname = NULL;
  6442. struct addrinfo *k_hints = NULL;
  6443. #ifdef ARCH_MM_MMU
  6444. int len = 0;
  6445. #endif
  6446. #ifdef ARCH_MM_MMU
  6447. if (!lwp_user_accessable((void *)res, sizeof(*res)))
  6448. {
  6449. SET_ERRNO(EFAULT);
  6450. goto exit;
  6451. }
  6452. #endif
  6453. if (nodename)
  6454. {
  6455. #ifdef ARCH_MM_MMU
  6456. len = lwp_user_strlen(nodename);
  6457. if (len <= 0)
  6458. {
  6459. SET_ERRNO(EFAULT);
  6460. goto exit;
  6461. }
  6462. k_nodename = (char *)kmem_get(len + 1);
  6463. if (!k_nodename)
  6464. {
  6465. SET_ERRNO(ENOMEM);
  6466. goto exit;
  6467. }
  6468. if (lwp_get_from_user(k_nodename, (void *)nodename, len + 1) != len + 1)
  6469. {
  6470. SET_ERRNO(EFAULT);
  6471. goto exit;
  6472. }
  6473. #else
  6474. k_nodename = rt_strdup(nodename);
  6475. if (!k_nodename)
  6476. {
  6477. SET_ERRNO(ENOMEM);
  6478. goto exit;
  6479. }
  6480. #endif
  6481. }
  6482. if (servname)
  6483. {
  6484. #ifdef ARCH_MM_MMU
  6485. len = lwp_user_strlen(servname);
  6486. if (len <= 0)
  6487. {
  6488. SET_ERRNO(EFAULT);
  6489. goto exit;
  6490. }
  6491. k_servname = (char *)kmem_get(len + 1);
  6492. if (!k_servname)
  6493. {
  6494. SET_ERRNO(ENOMEM);
  6495. goto exit;
  6496. }
  6497. if (lwp_get_from_user(k_servname, (void *)servname, len + 1) < 0)
  6498. {
  6499. SET_ERRNO(EFAULT);
  6500. goto exit;
  6501. }
  6502. #else
  6503. k_servname = rt_strdup(servname);
  6504. if (!k_servname)
  6505. {
  6506. SET_ERRNO(ENOMEM);
  6507. goto exit;
  6508. }
  6509. #endif
  6510. }
  6511. if (hints)
  6512. {
  6513. #ifdef ARCH_MM_MMU
  6514. if (!lwp_user_accessable((void *)hints, sizeof(*hints)))
  6515. {
  6516. SET_ERRNO(EFAULT);
  6517. goto exit;
  6518. }
  6519. #endif
  6520. k_hints = (struct addrinfo *) rt_malloc(sizeof *hints);
  6521. if (!k_hints)
  6522. {
  6523. SET_ERRNO(ENOMEM);
  6524. goto exit;
  6525. }
  6526. rt_memset(k_hints, 0x0, sizeof(struct addrinfo));
  6527. k_hints->ai_flags = hints->ai_flags;
  6528. k_hints->ai_family = hints->ai_family;
  6529. k_hints->ai_socktype = hints->ai_socktype;
  6530. k_hints->ai_protocol = hints->ai_protocol;
  6531. k_hints->ai_addrlen = hints->ai_addrlen;
  6532. }
  6533. ret = sal_getaddrinfo(k_nodename, k_servname, k_hints, &k_res);
  6534. if (ret == 0)
  6535. {
  6536. /* set sockaddr */
  6537. sockaddr_tomusl(k_res->ai_addr, res->ai_addr);
  6538. res->ai_addrlen = k_res->ai_addrlen;
  6539. /* set up addrinfo */
  6540. res->ai_family = k_res->ai_family;
  6541. res->ai_flags = k_res->ai_flags;
  6542. res->ai_next = NULL;
  6543. if (hints != NULL)
  6544. {
  6545. /* copy socktype & protocol from hints if specified */
  6546. res->ai_socktype = hints->ai_socktype;
  6547. res->ai_protocol = hints->ai_protocol;
  6548. }
  6549. sal_freeaddrinfo(k_res);
  6550. k_res = NULL;
  6551. }
  6552. exit:
  6553. if (ret < 0)
  6554. {
  6555. ret = GET_ERRNO();
  6556. }
  6557. #ifdef ARCH_MM_MMU
  6558. if (k_nodename)
  6559. {
  6560. kmem_put(k_nodename);
  6561. }
  6562. #else
  6563. if (k_nodename)
  6564. {
  6565. rt_free(k_nodename);
  6566. }
  6567. #endif
  6568. #ifdef ARCH_MM_MMU
  6569. if (k_servname)
  6570. {
  6571. kmem_put(k_servname);
  6572. }
  6573. #else
  6574. if (k_servname)
  6575. {
  6576. rt_free(k_servname);
  6577. }
  6578. #endif
  6579. if (k_hints)
  6580. {
  6581. rt_free(k_hints);
  6582. }
  6583. return ret;
  6584. }
  6585. #define HOSTENT_BUFSZ 512
  6586. /**
  6587. * @brief Resolves a host name to an address, with support for specifying the address family.
  6588. *
  6589. * This function performs a lookup of the specified host name, and resolves it to an address,
  6590. * while allowing the caller to specify the desired address family (e.g., IPv4 or IPv6). It is
  6591. * a reentrant version of `gethostbyname2`, meaning it is safe for use in multi-threaded applications.
  6592. * The results are returned in a user-provided buffer to avoid memory allocation overhead.
  6593. *
  6594. * @param[in] name The host name to be resolved. This can be a DNS name or an IP address in string format.
  6595. * @param[in] af The address family to use for the resolution. Common values are:
  6596. * - `AF_INET` for IPv4 addresses.
  6597. * - `AF_INET6` for IPv6 addresses.
  6598. * @param[out] ret A pointer to a `struct hostent` where the resolved host information will be stored.
  6599. * This includes the host name, alias names, address type, and the address itself.
  6600. * @param[in] buf A buffer to store additional information required for the `struct hostent` structure.
  6601. * This is needed to ensure the reentrant behavior and avoid memory allocation.
  6602. * @param[in] buflen The size of the buffer provided.
  6603. * @param[out] result A pointer to a `struct hostent*` that will point to the resolved host entry.
  6604. * This will be set to the value of `ret` upon success.
  6605. * @param[out] err A pointer to an integer where error codes will be stored. If the function fails,
  6606. * `err` will contain a non-zero value corresponding to the error.
  6607. *
  6608. * @return sysret_t Returns `0` on success, indicating the resolution was successful.
  6609. * On failure, returns a negative error code that indicates the failure reason.
  6610. *
  6611. * @note This function is reentrant and thread-safe, meaning it does not use static memory or global state.
  6612. * It relies on the buffers provided by the caller to store the resolved data.
  6613. *
  6614. * @see gethostbyname2(), sys_gethostbyname(), sys_socket(), sys_connect(), sys_getaddrinfo()
  6615. */
  6616. sysret_t sys_gethostbyname2_r(const char *name, int af, struct hostent *ret,
  6617. char *buf, size_t buflen,
  6618. struct hostent **result, int *err)
  6619. {
  6620. int ret_val = -1;
  6621. int sal_ret = -1 , sal_err = -1;
  6622. struct hostent sal_he, sal_tmp;
  6623. struct hostent *sal_result = NULL;
  6624. char *sal_buf = NULL;
  6625. char *k_name = NULL;
  6626. int len = 0;
  6627. #ifdef ARCH_MM_MMU
  6628. if (!lwp_user_accessable((void *)err, sizeof(*err)))
  6629. {
  6630. SET_ERRNO(EFAULT);
  6631. goto __exit;
  6632. }
  6633. if (!lwp_user_accessable((void *)result, sizeof(*result))
  6634. || !lwp_user_accessable((void *)ret, sizeof(*ret))
  6635. || !lwp_user_accessable((void *)buf, buflen))
  6636. {
  6637. /* not all arguments given */
  6638. *err = EFAULT;
  6639. SET_ERRNO(EFAULT);
  6640. goto __exit;
  6641. }
  6642. len = lwp_user_strlen(name);
  6643. if (len <= 0)
  6644. {
  6645. *err = EFAULT;
  6646. SET_ERRNO(EFAULT);
  6647. goto __exit;
  6648. }
  6649. k_name = (char *)kmem_get(len + 1);
  6650. if (!k_name)
  6651. {
  6652. SET_ERRNO(ENOMEM);
  6653. goto __exit;
  6654. }
  6655. if (lwp_get_from_user(k_name, (void *)name, len + 1) < 0)
  6656. {
  6657. SET_ERRNO(EFAULT);
  6658. goto __exit;
  6659. }
  6660. #else
  6661. k_name = rt_strdup(name);
  6662. if (k_name == NULL)
  6663. {
  6664. SET_ERRNO(ENOMEM);
  6665. goto __exit;
  6666. }
  6667. #endif
  6668. *result = ret;
  6669. sal_buf = (char *)malloc(HOSTENT_BUFSZ);
  6670. if (sal_buf == NULL)
  6671. {
  6672. SET_ERRNO(ENOMEM);
  6673. goto __exit;
  6674. }
  6675. /* get host by name in SAL */
  6676. sal_ret = sal_gethostbyname_r(k_name, &sal_he, sal_buf, HOSTENT_BUFSZ, &sal_result, &sal_err);
  6677. if (sal_ret == 0)
  6678. {
  6679. int index = 0, cnt = 0;
  6680. char *ptr = buf;
  6681. /* get counter */
  6682. index = 0;
  6683. while (sal_he.h_addr_list[index] != NULL)
  6684. {
  6685. index++;
  6686. }
  6687. cnt = index + 1;
  6688. #ifdef ARCH_MM_MMU
  6689. /* update user space hostent */
  6690. lwp_put_to_user(buf, k_name, buflen - (ptr - buf));
  6691. lwp_memcpy(&sal_tmp, &sal_he, sizeof(sal_he));
  6692. sal_tmp.h_name = ptr;
  6693. ptr += rt_strlen(k_name);
  6694. sal_tmp.h_addr_list = (char**)ptr;
  6695. ptr += cnt * sizeof(char *);
  6696. index = 0;
  6697. while (sal_he.h_addr_list[index] != NULL)
  6698. {
  6699. sal_tmp.h_addr_list[index] = ptr;
  6700. lwp_memcpy(ptr, sal_he.h_addr_list[index], sal_he.h_length);
  6701. ptr += sal_he.h_length;
  6702. index++;
  6703. }
  6704. sal_tmp.h_addr_list[index] = NULL;
  6705. lwp_put_to_user(ret, &sal_tmp, sizeof(sal_tmp));
  6706. #else
  6707. /* update user space hostent */
  6708. ret->h_addrtype = sal_he.h_addrtype;
  6709. ret->h_length = sal_he.h_length;
  6710. rt_strncpy(ptr, k_name, buflen - (ptr - buf));
  6711. ret->h_name = ptr;
  6712. ptr += strlen(k_name);
  6713. ret->h_addr_list = (char**)ptr;
  6714. ptr += cnt * sizeof(char *);
  6715. index = 0;
  6716. while (sal_he.h_addr_list[index] != NULL)
  6717. {
  6718. ret->h_addr_list[index] = ptr;
  6719. lwp_memcpy(ptr, sal_he.h_addr_list[index], sal_he.h_length);
  6720. ptr += sal_he.h_length;
  6721. index++;
  6722. }
  6723. ret->h_addr_list[index] = NULL;
  6724. #endif
  6725. ret_val = 0;
  6726. }
  6727. else
  6728. {
  6729. SET_ERRNO(EINVAL);
  6730. }
  6731. __exit:
  6732. if (ret_val < 0)
  6733. {
  6734. ret_val = GET_ERRNO();
  6735. }
  6736. /* release buffer */
  6737. if (sal_buf)
  6738. {
  6739. free(sal_buf);
  6740. }
  6741. #ifdef ARCH_MM_MMU
  6742. if (k_name)
  6743. {
  6744. kmem_put(k_name);
  6745. }
  6746. #else
  6747. if (k_name)
  6748. {
  6749. free(k_name);
  6750. }
  6751. #endif
  6752. return ret_val;
  6753. }
  6754. #endif
  6755. /**
  6756. * @brief Gets the current working directory.
  6757. *
  6758. * This function retrieves the absolute pathname of the current working directory
  6759. * and stores it in the provided buffer. The buffer must be large enough to hold
  6760. * the directory path, including the null-terminator. If the buffer is too small,
  6761. * the function will return an error.
  6762. *
  6763. * @param[out] buf A pointer to a buffer where the current working directory
  6764. * path will be stored. The buffer should be large enough
  6765. * to hold the path, including the null-terminator.
  6766. * @param[in] size The size of the buffer in bytes. The buffer must be large enough
  6767. * to accommodate the full path.
  6768. *
  6769. * @return long On success, returns the number of bytes written to the buffer
  6770. * (not including the null-terminator). If the buffer is not large
  6771. * enough, returns a negative error code.
  6772. *
  6773. * @note The maximum path length depends on the system's configuration.
  6774. * Ensure the buffer size is sufficient to hold the entire path.
  6775. *
  6776. * @see sys_chdir(), sys_getcwd_r(), sys_realpath()
  6777. */
  6778. long sys_getcwd(char *buf, size_t size)
  6779. {
  6780. char *tmp = RT_NULL;
  6781. long ret = -1;
  6782. if (!lwp_user_accessable((void *)buf, size))
  6783. {
  6784. return ret;
  6785. }
  6786. tmp = (char *)rt_malloc(size);
  6787. if (!tmp)
  6788. {
  6789. return ret;
  6790. }
  6791. if (getcwd(tmp, size) != RT_NULL)
  6792. {
  6793. if (lwp_put_to_user(buf, tmp, size) > 0)
  6794. {
  6795. if (buf != RT_NULL)
  6796. ret = strlen(buf);
  6797. else
  6798. ret = -EFAULT;
  6799. }
  6800. }
  6801. rt_free(tmp);
  6802. return ret;
  6803. }
  6804. /**
  6805. * @brief Changes the current working directory.
  6806. *
  6807. * This function changes the current working directory of the calling process
  6808. * to the directory specified by the given path. The path can be absolute or
  6809. * relative. If the specified path does not exist or the process does not have
  6810. * sufficient permissions, the function will return an error.
  6811. *
  6812. * @param[in] path The path to the new working directory. This can be either
  6813. * an absolute or a relative path.
  6814. *
  6815. * @return sysret_t Returns `0` on success, indicating that the working
  6816. * directory was successfully changed. On failure, returns a
  6817. * negative error code indicating the reason for failure.
  6818. *
  6819. * @note If the specified path is a relative path, it is interpreted relative
  6820. * to the current working directory.
  6821. *
  6822. * @see sys_getcwd(), sys_chdir() for changing directories, sys_opendir(), sys_stat()
  6823. */
  6824. sysret_t sys_chdir(const char *path)
  6825. {
  6826. #ifdef ARCH_MM_MMU
  6827. int err = 0;
  6828. int len = 0;
  6829. int errcode;
  6830. char *kpath = RT_NULL;
  6831. len = lwp_user_strlen(path);
  6832. if (len <= 0)
  6833. {
  6834. return -EFAULT;
  6835. }
  6836. kpath = (char *)kmem_get(len + 1);
  6837. if (!kpath)
  6838. {
  6839. return -ENOMEM;
  6840. }
  6841. if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
  6842. {
  6843. kmem_put(kpath);
  6844. return -EINVAL;
  6845. }
  6846. err = chdir(kpath);
  6847. errcode = err != 0 ? GET_ERRNO() : 0;
  6848. kmem_put(kpath);
  6849. return errcode;
  6850. #else
  6851. int ret = chdir(path);
  6852. return (ret < 0 ? GET_ERRNO() : ret);
  6853. #endif
  6854. }
  6855. /**
  6856. * @brief Changes the current working directory to the one associated with the specified file descriptor.
  6857. *
  6858. * This function changes the current working directory of the calling process
  6859. * to the directory associated with the file descriptor `fd`. The file descriptor
  6860. * should refer to an open directory. If the file descriptor does not refer to a
  6861. * directory, or if the process lacks the necessary permissions, the function will
  6862. * return an error.
  6863. *
  6864. * @param[in] fd The file descriptor referring to the directory to which the current
  6865. * working directory should be changed.
  6866. *
  6867. * @return sysret_t Returns `0` on success, indicating the current working directory
  6868. * was successfully changed. On failure, returns a negative error code.
  6869. *
  6870. * @note The file descriptor must refer to a directory. If it refers to a file or other
  6871. * non-directory object, the operation will fail.
  6872. *
  6873. * @see sys_chdir(), sys_getcwd(), sys_opendir(), sys_open()
  6874. */
  6875. sysret_t sys_fchdir(int fd)
  6876. {
  6877. int errcode = -ENOSYS;
  6878. #ifdef ARCH_MM_MMU
  6879. #ifdef RT_USING_DFS_V2
  6880. int err = -1;
  6881. struct dfs_file *d;
  6882. char *kpath;
  6883. d = fd_get(fd);
  6884. if (!d || !d->vnode)
  6885. {
  6886. return -EBADF;
  6887. }
  6888. kpath = dfs_dentry_full_path(d->dentry);
  6889. if (!kpath)
  6890. {
  6891. return -EACCES;
  6892. }
  6893. err = chdir(kpath);
  6894. errcode = err != 0 ? GET_ERRNO() : 0;
  6895. kmem_put(kpath);
  6896. #endif
  6897. #endif
  6898. return errcode;
  6899. }
  6900. /**
  6901. * @brief Creates a new directory with the specified path and mode.
  6902. *
  6903. * This function creates a new directory with the specified path and mode.
  6904. * The directory is created with the permissions specified by the `mode` parameter.
  6905. * If the directory already exists, the function will return an error.
  6906. *
  6907. * @param[in] path The path of the directory to be created. This can be an absolute
  6908. * or relative path. If the directory does not exist, it will be created.
  6909. * @param[in] mode The permissions to be set for the new directory. This parameter
  6910. * specifies the access permissions for the directory owner, group, and others.
  6911. *
  6912. * @return sysret_t Returns `0` on success, indicating that the directory was successfully
  6913. * created. On failure, returns a negative error code indicating the reason for failure.
  6914. *
  6915. * @note The `mode` parameter specifies the permissions for the new directory. The permissions
  6916. * are typically specified using the `S_IRWXU`, `S_IRWXG`, and `S_IRWXO` macros, which
  6917. * define the read, write, and execute permissions for the owner, group, and others.
  6918. *
  6919. * @see sys_rmdir(), sys_chdir(), sys_mkdirat()
  6920. */
  6921. sysret_t sys_mkdir(const char *path, mode_t mode)
  6922. {
  6923. #ifdef ARCH_MM_MMU
  6924. int err = 0;
  6925. int len = 0;
  6926. char *kpath = RT_NULL;
  6927. len = lwp_user_strlen(path);
  6928. if (len <= 0)
  6929. {
  6930. return -EFAULT;
  6931. }
  6932. kpath = (char *)kmem_get(len + 1);
  6933. if (!kpath)
  6934. {
  6935. return -ENOMEM;
  6936. }
  6937. if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
  6938. {
  6939. kmem_put(kpath);
  6940. return -EINVAL;
  6941. }
  6942. err = _SYS_WRAP(mkdir(kpath, mode));
  6943. kmem_put(kpath);
  6944. return err;
  6945. #else
  6946. int ret = mkdir(path, mode);
  6947. return (ret < 0 ? GET_ERRNO() : ret);
  6948. #endif
  6949. }
  6950. /**
  6951. * @brief Removes the specified directory.
  6952. *
  6953. * This function removes the directory specified by the given path. The directory
  6954. * must be empty for the operation to succeed. If the directory is not empty, the
  6955. * function will return an error. If the directory does not exist or the process
  6956. * lacks the necessary permissions, the function will also return an error.
  6957. *
  6958. * @param[in] path The path of the directory to be removed. This can be an absolute
  6959. * or relative path. The directory must be empty for the operation to succeed.
  6960. *
  6961. * @return sysret_t Returns `0` on success, indicating that the directory was successfully
  6962. * removed. On failure, returns a negative error code indicating the reason for failure.
  6963. *
  6964. * @note The directory must be empty for the operation to succeed. If the directory contains
  6965. * files or subdirectories, the operation will fail. To remove a non-empty directory,
  6966. * the contents must be deleted first.
  6967. *
  6968. * @see sys_mkdir(), sys_chdir(), sys_rmdirat()
  6969. */
  6970. sysret_t sys_rmdir(const char *path)
  6971. {
  6972. int err = 0;
  6973. int ret = 0;
  6974. #ifdef ARCH_MM_MMU
  6975. int len = 0;
  6976. char *kpath = RT_NULL;
  6977. len = lwp_user_strlen(path);
  6978. if (len <= 0)
  6979. {
  6980. return -EFAULT;
  6981. }
  6982. kpath = (char *)kmem_get(len + 1);
  6983. if (!kpath)
  6984. {
  6985. return -ENOMEM;
  6986. }
  6987. if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
  6988. {
  6989. kmem_put(kpath);
  6990. return -EINVAL;
  6991. }
  6992. ret = rmdir(kpath);
  6993. if(ret < 0)
  6994. {
  6995. err = GET_ERRNO();
  6996. }
  6997. kmem_put(kpath);
  6998. return (err < 0 ? err : ret);
  6999. #else
  7000. ret = rmdir(path);
  7001. if(ret < 0)
  7002. {
  7003. err = GET_ERRNO();
  7004. }
  7005. return (err < 0 ? err : ret);
  7006. #endif
  7007. }
  7008. /**
  7009. * @brief Reads directory entries.
  7010. *
  7011. * This function reads the directory entries from the directory stream specified by the file descriptor `fd`.
  7012. * It stores the directory entries in the buffer pointed to by `dirp`, up to the specified number of bytes (`nbytes`).
  7013. * The entries are returned in a format compatible with the `struct libc_dirent` structure.
  7014. *
  7015. * @param[in] fd The file descriptor referring to an open directory. This descriptor must be obtained
  7016. * from a call to `sys_open()` with the appropriate flags for directory reading.
  7017. * @param[out] dirp A pointer to a buffer where the directory entries will be stored.
  7018. * The buffer must be large enough to hold at least `nbytes` bytes of directory entries.
  7019. * @param[in] nbytes The size of the buffer (`dirp`) in bytes. It limits the number of directory entries
  7020. * that can be read in a single call. The function will return as many entries as possible
  7021. * that fit within the buffer size.
  7022. *
  7023. * @return sysret_t Returns the number of bytes read on success, which may be less than `nbytes` if there
  7024. * are fewer entries in the directory or if the buffer is too small.
  7025. * On failure, returns a negative error code.
  7026. *
  7027. * @note If the function returns 0, it indicates the end of the directory stream. A negative return value
  7028. * indicates an error. The caller can use the returned number of bytes to process the entries in `dirp`.
  7029. *
  7030. * @see sys_open(), sys_close(), sys_readdir(), sys_stat()
  7031. */
  7032. sysret_t sys_getdents(int fd, struct libc_dirent *dirp, size_t nbytes)
  7033. {
  7034. int ret = -1;
  7035. struct dfs_file *file;
  7036. size_t cnt = (nbytes / sizeof(struct libc_dirent));
  7037. size_t rtt_nbytes = 0;
  7038. struct dirent *rtt_dirp;
  7039. #ifdef ARCH_MM_MMU
  7040. if (!lwp_user_accessable((void *)dirp, sizeof(struct libc_dirent)))
  7041. {
  7042. return -EFAULT;
  7043. }
  7044. #endif
  7045. if (cnt == 0)
  7046. {
  7047. return -EINVAL;
  7048. }
  7049. rtt_nbytes = cnt * sizeof(struct dirent);
  7050. rtt_dirp = (struct dirent *)rt_malloc(rtt_nbytes);
  7051. if (!rtt_dirp)
  7052. {
  7053. return -ENOMEM;
  7054. }
  7055. file = fd_get(fd);
  7056. ret = dfs_file_getdents(file, rtt_dirp, rtt_nbytes);
  7057. if (ret > 0)
  7058. {
  7059. size_t i = 0;
  7060. cnt = ret / sizeof(struct dirent);
  7061. for (i = 0; i < cnt; i++)
  7062. {
  7063. dirp[i].d_ino = 0;
  7064. dirp[i].d_off = i*sizeof(struct libc_dirent);
  7065. dirp[i].d_type = rtt_dirp[i].d_type;
  7066. dirp[i].d_reclen = sizeof(struct libc_dirent);
  7067. strcpy(dirp[i].d_name, rtt_dirp[i].d_name);
  7068. }
  7069. ret = cnt * sizeof(struct libc_dirent);
  7070. }
  7071. if (ret < 0)
  7072. {
  7073. ret = GET_ERRNO();
  7074. }
  7075. rt_free(rtt_dirp);
  7076. return ret;
  7077. }
  7078. /**
  7079. * @brief Retrieves the current value of the error code.
  7080. *
  7081. * This function returns the most recent error code set by a system call. The error code is typically set
  7082. * when a system call fails. This function allows users to retrieve the last error that occurred, helping to
  7083. * diagnose issues or handle errors in a more controlled manner.
  7084. *
  7085. * @return sysret_t The current error code. A value of `0` indicates no error, while a non-zero value
  7086. * represents the most recent error. The error codes are system-specific and can
  7087. * represent various failure conditions (e.g., `EINVAL`, `ENOMEM`, `EIO`).
  7088. *
  7089. * @note The error code returned is specific to the current thread or process and is typically updated
  7090. * each time a system call fails. The error code is persistent until it is overwritten by the next
  7091. * failed system call or explicitly reset.
  7092. *
  7093. * @see sys_set_errno(), sys_perror(), sys_strerror()
  7094. */
  7095. sysret_t sys_get_errno(void)
  7096. {
  7097. return rt_get_errno();
  7098. }
  7099. #ifdef ARCH_MM_MMU
  7100. /**
  7101. * @brief Sets the thread-specific data area.
  7102. *
  7103. * This function is used to associate a specific area of memory with the current thread. The area pointed to
  7104. * by `p` is set as the thread's local storage. Thread-specific data is used to store data that is unique to
  7105. * each thread, allowing different threads to maintain independent state information.
  7106. *
  7107. * @param[in] p A pointer to the memory area that is to be set as the thread's local storage. This area
  7108. * will be used by the thread to store its specific data. The structure and size of the data
  7109. * area depend on the implementation and use case.
  7110. *
  7111. * @return sysret_t Returns `0` on success. On failure, it returns a negative error code.
  7112. *
  7113. * @note This function is typically used to set up thread-specific storage for managing data that should
  7114. * not be shared between threads. The data area is accessible only by the thread that set it, ensuring
  7115. * thread safety for the stored information.
  7116. *
  7117. * @see sys_get_thread_area(), sys_thread_create(), sys_thread_self()
  7118. */
  7119. sysret_t sys_set_thread_area(void *p)
  7120. {
  7121. rt_thread_t thread;
  7122. thread = rt_thread_self();
  7123. thread->thread_idr = p;
  7124. arch_set_thread_area(p);
  7125. return 0;
  7126. }
  7127. /**
  7128. * @brief Sets the address at which the thread ID is stored.
  7129. *
  7130. * This function sets the address of a variable that will store the thread ID for the calling thread.
  7131. * The specified address `tidptr` will hold the thread's unique identifier. This can be useful for
  7132. * managing thread-specific state or for synchronization mechanisms where the thread's ID needs to be
  7133. * shared or checked by other parts of the system.
  7134. *
  7135. * @param[in] tidptr A pointer to an integer where the thread ID will be stored. This value will
  7136. * hold the calling thread's ID, and it can be accessed to identify the thread
  7137. * later. The value of the thread ID can be used in various thread management
  7138. * operations.
  7139. *
  7140. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7141. *
  7142. * @note This function is typically used in systems that require associating a specific address with the
  7143. * thread ID, often in real-time or embedded systems where managing and accessing thread IDs is
  7144. * crucial for scheduling or resource allocation.
  7145. *
  7146. * @see sys_get_tid(), sys_thread_self(), sys_thread_create()
  7147. */
  7148. sysret_t sys_set_tid_address(int *tidptr)
  7149. {
  7150. rt_thread_t thread;
  7151. #ifdef ARCH_MM_MMU
  7152. if (!lwp_user_accessable((void *)tidptr, sizeof(int)))
  7153. {
  7154. return -EFAULT;
  7155. }
  7156. #endif
  7157. thread = rt_thread_self();
  7158. thread->clear_child_tid = tidptr;
  7159. return thread->tid;
  7160. }
  7161. #endif /* ARCH_MM_MMU */
  7162. /**
  7163. * @brief Gets the thread ID of the calling thread.
  7164. *
  7165. * This function returns the unique thread identifier (thread ID) for the calling thread. The thread ID
  7166. * can be used to uniquely identify the thread within the system and is typically used for debugging,
  7167. * thread management, or scheduling purposes.
  7168. *
  7169. * @return sysret_t The thread ID of the calling thread. The value is typically a positive integer
  7170. * representing the unique ID assigned to the thread. In case of failure, an error code
  7171. * may be returned.
  7172. *
  7173. * @note The thread ID returned by this function is unique within the system, and it may be used to
  7174. * reference or manipulate the specific thread associated with the ID.
  7175. *
  7176. * @see sys_set_tid_address(), sys_thread_self(), sys_thread_create()
  7177. */
  7178. sysret_t sys_gettid(void)
  7179. {
  7180. return rt_thread_self()->tid;
  7181. }
  7182. /**
  7183. * @brief Checks the accessibility of a file or directory.
  7184. *
  7185. * This function checks whether the calling process has the specified access rights for the given file or directory.
  7186. * The check is performed based on the provided `mode`, which can indicate whether read, write, or execute permissions
  7187. * are required.
  7188. *
  7189. * @param[in] filename The path to the file or directory whose accessibility is being checked.
  7190. * @param[in] mode The access mode to check for. This can be a combination of the following:
  7191. * - `R_OK`: Check for read permission.
  7192. * - `W_OK`: Check for write permission.
  7193. * - `X_OK`: Check for execute permission.
  7194. * - `F_OK`: Check if the file exists.
  7195. *
  7196. * @return sysret_t Returns `0` if the specified access is allowed. On failure, returns a negative error code.
  7197. *
  7198. * @note This function does not modify the file or directory, it only checks if the specified access rights are granted.
  7199. *
  7200. * @see sys_open(), sys_stat(), sys_fstat(), sys_chmod(), sys_chown()
  7201. */
  7202. sysret_t sys_access(const char *filename, int mode)
  7203. {
  7204. int ret = 0;
  7205. #ifdef ARCH_MM_MMU
  7206. rt_size_t len = 0;
  7207. char *kfilename = RT_NULL;
  7208. len = lwp_user_strlen(filename);
  7209. if (len <= 0)
  7210. {
  7211. return -EINVAL;
  7212. }
  7213. kfilename = (char *)kmem_get(len + 1);
  7214. if (!kfilename)
  7215. {
  7216. return -ENOMEM;
  7217. }
  7218. if (lwp_get_from_user(kfilename, (void *)filename, len + 1) != (len + 1))
  7219. {
  7220. kmem_put(kfilename);
  7221. return -EFAULT;
  7222. }
  7223. ret = access(kfilename, mode);
  7224. if (ret < 0)
  7225. {
  7226. ret = GET_ERRNO();
  7227. }
  7228. kmem_put(kfilename);
  7229. return ret;
  7230. #else
  7231. ret = access(filename, mode);
  7232. return (ret < 0 ? GET_ERRNO() : ret);
  7233. #endif
  7234. }
  7235. /**
  7236. * @brief Creates a pipe, a unidirectional data channel.
  7237. *
  7238. * This function creates a pipe, which is a unidirectional data channel used for inter-process communication.
  7239. * The pipe consists of two file descriptors: one for reading from the pipe and one for writing to the pipe.
  7240. * The pipe is used for passing data between processes or threads, typically in a producer-consumer scenario.
  7241. *
  7242. * @param[out] fd An array of two integers where the file descriptors for the read and write ends of the pipe will be stored.
  7243. * - `fd[0]`: The file descriptor for reading from the pipe.
  7244. * - `fd[1]`: The file descriptor for writing to the pipe.
  7245. *
  7246. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7247. *
  7248. * @note The pipe created by this function is typically used for simple communication between processes or threads.
  7249. * The data written to `fd[1]` can be read from `fd[0]`. After usage, both file descriptors should be closed.
  7250. *
  7251. * @see sys_read(), sys_write(), sys_close(), sys_fork(), sys_execve()
  7252. */
  7253. sysret_t sys_pipe(int fd[2])
  7254. {
  7255. int ret;
  7256. int kfd[2] = {0, 0};
  7257. if (!lwp_user_accessable((void *)fd, sizeof(int[2])))
  7258. {
  7259. return -EFAULT;
  7260. }
  7261. ret = pipe(kfd);
  7262. lwp_put_to_user((void *)fd, kfd, sizeof(int[2]));
  7263. return (ret < 0 ? GET_ERRNO() : ret);
  7264. }
  7265. /**
  7266. * @brief Waits for a process to change state.
  7267. *
  7268. * This function suspends the execution of the calling process until one of its child processes terminates
  7269. * or a specified process (identified by `pid`) changes its state. The function returns the process ID of the child
  7270. * process that terminated, and provides information about its exit status and resource usage.
  7271. *
  7272. * @param[in] pid The process ID of the child process to wait for. The behavior of this parameter can be one of the following:
  7273. * - `pid > 0`: Wait for the child process with the specified PID.
  7274. * - `pid == 0`: Wait for any child process in the same process group.
  7275. * - `pid == -1`: Wait for any child process (default behavior).
  7276. * - `pid < -1`: Wait for any child process in the specified process group.
  7277. *
  7278. * @param[out] status A pointer to an integer where the exit status of the terminated child process will be stored.
  7279. * This status can be interpreted using macros such as `WIFEXITED` or `WIFSIGNALED`.
  7280. *
  7281. * @param[in] options Options for the wait operation, which can include:
  7282. * - `WNOHANG`: Return immediately if no child has exited.
  7283. * - `WUNTRACED`: Return if a child has stopped, but not yet terminated.
  7284. *
  7285. * @param[out] ru A pointer to a `struct rusage` where resource usage information of the child process will be stored.
  7286. * This includes information such as CPU time consumed by the child process.
  7287. *
  7288. * @return sysret_t Returns the process ID of the terminated child on success. In case of failure, a negative error code is returned.
  7289. *
  7290. * @note This function is useful for monitoring and cleaning up child processes in parent-child relationships.
  7291. * The `status` value can be further analyzed to determine if the child process terminated normally or due to a signal.
  7292. *
  7293. * @see sys_waitpid(), sys_fork(), sys_exit()
  7294. */
  7295. sysret_t sys_wait4(pid_t pid, int *status, int options, struct rusage *ru)
  7296. {
  7297. return lwp_waitpid(pid, status, options, ru);
  7298. }
  7299. /**
  7300. * @brief Sets the time of a specified clock.
  7301. *
  7302. * This function sets the time of the specified clock (identified by `clk`) to the given value. The time is provided
  7303. * as a `struct timespec` containing seconds and nanoseconds. This function can be used to set the system clock or
  7304. * other specific clocks, such as monotonic or real-time clocks.
  7305. *
  7306. * @param[in] clk The clock ID for which to set the time. The clock can be one of the following:
  7307. * - `CLOCK_REALTIME`: Set the system's real-time clock.
  7308. * - `CLOCK_MONOTONIC`: Set the monotonic clock, which measures time since some unspecified starting point.
  7309. * - `CLOCK_PROCESS_CPUTIME_ID`: Set the CPU time used by the process.
  7310. * - `CLOCK_THREAD_CPUTIME_ID`: Set the CPU time used by the current thread.
  7311. *
  7312. * @param[in] ts A pointer to a `struct timespec` containing the new time to set for the specified clock.
  7313. * - `ts->tv_sec`: Seconds since the epoch (for `CLOCK_REALTIME`) or since some unspecified start point (for other clocks).
  7314. * - `ts->tv_nsec`: Nanoseconds within the current second.
  7315. *
  7316. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7317. *
  7318. * @note This function requires appropriate permissions for setting the system's clock. In some systems, only privileged users
  7319. * may change the `CLOCK_REALTIME` clock.
  7320. *
  7321. * @see sys_clock_gettime(), sys_clock_getres()
  7322. */
  7323. sysret_t sys_clock_settime(clockid_t clk, const struct timespec *ts)
  7324. {
  7325. int ret = 0;
  7326. #ifdef ARCH_MM_MMU
  7327. size_t size = sizeof(struct timespec);
  7328. struct timespec *kts = NULL;
  7329. if (!lwp_user_accessable((void *)ts, size))
  7330. {
  7331. return -EFAULT;
  7332. }
  7333. kts = kmem_get(size);
  7334. if (!kts)
  7335. {
  7336. return -ENOMEM;
  7337. }
  7338. lwp_get_from_user(kts, (void *)ts, size);
  7339. ret = clock_settime(clk, kts);
  7340. if (ret < 0)
  7341. {
  7342. ret = GET_ERRNO();
  7343. }
  7344. kmem_put(kts);
  7345. return ret;
  7346. #else
  7347. if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
  7348. {
  7349. return -EFAULT;
  7350. }
  7351. ret = clock_settime(clk, ts);
  7352. return (ret < 0 ? GET_ERRNO() : ret);
  7353. #endif
  7354. }
  7355. /**
  7356. * @brief Retrieves the current time of a specified clock.
  7357. *
  7358. * This function retrieves the current time of the specified clock (identified by `clk`) and stores it in the
  7359. * `struct timespec` pointed to by `ts`. The time is expressed in seconds and nanoseconds. The clock can be
  7360. * one of several types, such as real-time, monotonic, or process-specific clocks.
  7361. *
  7362. * @param[in] clk The clock ID for which to get the time. The clock can be one of the following:
  7363. * - `CLOCK_REALTIME`: Get the system's real-time clock.
  7364. * - `CLOCK_MONOTONIC`: Get the monotonic clock, which measures time since some unspecified starting point.
  7365. * - `CLOCK_PROCESS_CPUTIME_ID`: Get the CPU time used by the process.
  7366. * - `CLOCK_THREAD_CPUTIME_ID`: Get the CPU time used by the current thread.
  7367. *
  7368. * @param[out] ts A pointer to a `struct timespec` where the current time for the specified clock will be stored.
  7369. * - `ts->tv_sec`: Seconds since the epoch (for `CLOCK_REALTIME`) or since some unspecified start point (for other clocks).
  7370. * - `ts->tv_nsec`: Nanoseconds within the current second.
  7371. *
  7372. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7373. *
  7374. * @note This function requires appropriate permissions for retrieving certain clocks (e.g., `CLOCK_REALTIME`).
  7375. *
  7376. * @see sys_clock_settime(), sys_clock_getres()
  7377. */
  7378. sysret_t sys_clock_gettime(clockid_t clk, struct timespec *ts)
  7379. {
  7380. int ret = 0;
  7381. #ifdef ARCH_MM_MMU
  7382. size_t size = sizeof(struct timespec);
  7383. struct timespec *kts = NULL;
  7384. if (!lwp_user_accessable((void *)ts, size))
  7385. {
  7386. return -EFAULT;
  7387. }
  7388. kts = kmem_get(size);
  7389. if (!kts)
  7390. {
  7391. return -ENOMEM;
  7392. }
  7393. ret = clock_gettime(clk, kts);
  7394. if (ret != -1)
  7395. lwp_put_to_user(ts, kts, size);
  7396. if (ret < 0)
  7397. {
  7398. ret = GET_ERRNO();
  7399. }
  7400. kmem_put(kts);
  7401. return ret;
  7402. #else
  7403. if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
  7404. {
  7405. return -EFAULT;
  7406. }
  7407. ret = clock_gettime(clk, ts);
  7408. return (ret < 0 ? GET_ERRNO() : ret);
  7409. #endif
  7410. }
  7411. /**
  7412. * @brief Suspends the execution of the calling thread for the specified time duration.
  7413. *
  7414. * This function causes the calling thread to sleep for the specified time duration, which is provided as a
  7415. * `struct timespec` containing seconds and nanoseconds. The sleep is done based on the specified clock (identified by `clk`).
  7416. * If the `flags` parameter is set to `TIMER_ABSTIME`, the specified time represents an absolute time, otherwise,
  7417. * it represents a relative time interval.
  7418. *
  7419. * @param[in] clk The clock ID for which to perform the sleep. The clock can be one of the following:
  7420. * - `CLOCK_REALTIME`: Use the system's real-time clock.
  7421. * - `CLOCK_MONOTONIC`: Use the monotonic clock, which measures time since some unspecified starting point.
  7422. * - `CLOCK_PROCESS_CPUTIME_ID`: Use the CPU time used by the process.
  7423. * - `CLOCK_THREAD_CPUTIME_ID`: Use the CPU time used by the current thread.
  7424. *
  7425. * @param[in] flags The sleep behavior flags. The possible flags are:
  7426. * - `0`: The sleep duration is relative to the current time.
  7427. * - `TIMER_ABSTIME`: The sleep duration is absolute (measured from the specified clock).
  7428. *
  7429. * @param[in] rqtp A pointer to a `struct timespec` containing the requested sleep time.
  7430. * - `rqtp->tv_sec`: Seconds to sleep.
  7431. * - `rqtp->tv_nsec`: Nanoseconds to sleep (0 ≤ `rqtp->tv_nsec` < 1 billion).
  7432. *
  7433. * @param[out] rmtp A pointer to a `struct timespec` where the remaining time will be stored if the sleep is interrupted.
  7434. * If the sleep completes successfully, `rmtp` will not be modified.
  7435. * - `rmtp->tv_sec`: Remaining seconds.
  7436. * - `rmtp->tv_nsec`: Remaining nanoseconds.
  7437. *
  7438. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7439. *
  7440. * @note This function can be interrupted by signals. In that case, the remaining time is returned in `rmtp`.
  7441. * If the sleep is not interrupted, the function returns `SYSRET_OK` when the requested time has passed.
  7442. *
  7443. * @see sys_clock_gettime(), sys_clock_settime(), sys_nanosleep()
  7444. */
  7445. sysret_t sys_clock_nanosleep(clockid_t clk, int flags, const struct timespec *rqtp, struct timespec *rmtp)
  7446. {
  7447. int ret = 0;
  7448. LOG_D("sys_nanosleep\n");
  7449. if (!lwp_user_accessable((void *)rqtp, sizeof *rqtp))
  7450. return -EFAULT;
  7451. #ifdef ARCH_MM_MMU
  7452. struct timespec rqtp_k;
  7453. struct timespec rmtp_k;
  7454. lwp_get_from_user(&rqtp_k, (void *)rqtp, sizeof rqtp_k);
  7455. ret = clock_nanosleep(clk, flags, &rqtp_k, &rmtp_k);
  7456. if ((ret != -1 || rt_get_errno() == EINTR) && rmtp && lwp_user_accessable((void *)rmtp, sizeof *rmtp))
  7457. {
  7458. lwp_put_to_user(rmtp, (void *)&rmtp_k, sizeof rmtp_k);
  7459. if(ret != 0)
  7460. return -EINTR;
  7461. }
  7462. #else
  7463. if (rmtp)
  7464. {
  7465. if (!lwp_user_accessable((void *)rmtp, sizeof *rmtp))
  7466. return -EFAULT;
  7467. ret = clock_nanosleep(clk, flags, rqtp, rmtp);
  7468. }
  7469. #endif
  7470. return (ret < 0 ? GET_ERRNO() : ret);
  7471. }
  7472. /**
  7473. * @brief Get the resolution of the specified clock.
  7474. *
  7475. * This function retrieves the resolution of the specified clock, which is the smallest time interval that the clock can measure.
  7476. * The resolution is returned in a `struct timespec` which contains seconds and nanoseconds.
  7477. *
  7478. * @param[in] clk The clock ID for which to get the resolution. The clock can be one of the following:
  7479. * - `CLOCK_REALTIME`: System's real-time clock.
  7480. * - `CLOCK_MONOTONIC`: Monotonic clock (measures time since an unspecified point).
  7481. * - `CLOCK_PROCESS_CPUTIME_ID`: CPU time consumed by the current process.
  7482. * - `CLOCK_THREAD_CPUTIME_ID`: CPU time consumed by the current thread.
  7483. *
  7484. * @param[out] ts A pointer to a `struct timespec` where the clock's resolution will be stored.
  7485. * - `ts->tv_sec`: The number of seconds in the resolution.
  7486. * - `ts->tv_nsec`: The number of nanoseconds in the resolution (0 ≤ `ts->tv_nsec` < 1 billion).
  7487. *
  7488. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7489. *
  7490. * @note The resolution may be zero for some clocks, depending on the system's configuration.
  7491. * A clock's resolution determines the smallest unit of time the clock can measure.
  7492. *
  7493. * @see sys_clock_gettime(), sys_clock_settime(), sys_clock_nanosleep()
  7494. */
  7495. sysret_t sys_clock_getres(clockid_t clk, struct timespec *ts)
  7496. {
  7497. int ret = 0;
  7498. #ifdef ARCH_MM_MMU
  7499. struct timespec kts;
  7500. size_t size = sizeof(struct timespec);
  7501. if (!lwp_user_accessable((void *)ts, size))
  7502. {
  7503. return -EFAULT;
  7504. }
  7505. ret = clock_getres(clk, &kts);
  7506. if (ret != -1)
  7507. lwp_put_to_user(ts, &kts, size);
  7508. #else
  7509. if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
  7510. {
  7511. return -EFAULT;
  7512. }
  7513. ret = clock_getres(clk, ts);
  7514. #endif
  7515. return (ret < 0 ? GET_ERRNO() : ret);
  7516. }
  7517. /**
  7518. * @brief Rename or move a file or directory.
  7519. *
  7520. * This function renames or moves a file or directory from `oldpath` to `newpath`.
  7521. * If the `newpath` exists, it may be overwritten depending on the system's file system behavior and
  7522. * the permissions of the files involved.
  7523. *
  7524. * @param[in] oldpath The current path of the file or directory to rename or move.
  7525. * @param[in] newpath The new path or name to which the file or directory should be renamed or moved.
  7526. *
  7527. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7528. *
  7529. * @note If `oldpath` and `newpath` refer to different file systems, the behavior may vary,
  7530. * as the operation might involve copying and removing files instead of simply renaming them.
  7531. * The success of the operation also depends on the permissions of the source and destination.
  7532. *
  7533. * @see sys_unlink(), sys_mkdir(), sys_access()
  7534. */
  7535. sysret_t sys_rename(const char *oldpath, const char *newpath)
  7536. {
  7537. int ret = -1;
  7538. #ifdef ARCH_MM_MMU
  7539. int err;
  7540. err = lwp_user_strlen(oldpath);
  7541. if (err <= 0)
  7542. {
  7543. return -EFAULT;
  7544. }
  7545. err = lwp_user_strlen(newpath);
  7546. if (err <= 0)
  7547. {
  7548. return -EFAULT;
  7549. }
  7550. #endif
  7551. ret = rename(oldpath, newpath);
  7552. return (ret < 0 ? GET_ERRNO() : ret);
  7553. }
  7554. typedef unsigned long long rlim_t;
  7555. struct rlimit {
  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. /**
  7964. * @brief Set scheduling parameters for a specific thread.
  7965. *
  7966. * This function allows setting the scheduling parameters for a thread identified by its thread ID (`tid`).
  7967. * The parameters are provided via the `param` argument, which should be a structure compatible with the
  7968. * system's scheduling policies.
  7969. *
  7970. * @param[in] tid The thread ID of the target thread for which the scheduling parameters are to be set.
  7971. * @param[in] param A pointer to a structure containing the new scheduling parameters. The structure
  7972. * typically includes fields like priority and policy.
  7973. *
  7974. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  7975. *
  7976. * @note The caller must have appropriate permissions to change the scheduling parameters of the specified thread.
  7977. * The exact structure and fields of `param` depend on the system's implementation and scheduling policies.
  7978. */
  7979. sysret_t sys_sched_setparam(pid_t tid, void *param)
  7980. {
  7981. struct sched_param *sched_param = RT_NULL;
  7982. rt_thread_t thread;
  7983. int ret = -1;
  7984. if (!lwp_user_accessable(param, sizeof(struct sched_param)))
  7985. {
  7986. return -EFAULT;
  7987. }
  7988. sched_param = kmem_get(sizeof(struct sched_param));
  7989. if (sched_param == RT_NULL)
  7990. {
  7991. return -ENOMEM;
  7992. }
  7993. if (lwp_get_from_user(sched_param, param, sizeof(struct sched_param)) != sizeof(struct sched_param))
  7994. {
  7995. kmem_put(sched_param);
  7996. return -EINVAL;
  7997. }
  7998. thread = lwp_tid_get_thread_and_inc_ref(tid);
  7999. if (thread)
  8000. {
  8001. ret = rt_thread_control(thread, RT_THREAD_CTRL_RESET_PRIORITY, (void *)&sched_param->sched_priority);
  8002. }
  8003. lwp_tid_dec_ref(thread);
  8004. kmem_put(sched_param);
  8005. return ret;
  8006. }
  8007. /**
  8008. * @brief Relinquish the processor voluntarily.
  8009. *
  8010. * This function causes the calling thread to yield the processor, allowing other threads
  8011. * that are ready to run to execute. The thread will be placed back into the scheduler's
  8012. * ready queue and may be rescheduled according to its priority and the system's scheduling policy.
  8013. *
  8014. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8015. *
  8016. * @note This function is typically used in cooperative multitasking scenarios or when a thread
  8017. * explicitly determines it no longer needs the processor at the moment.
  8018. */
  8019. sysret_t sys_sched_yield(void)
  8020. {
  8021. rt_thread_yield();
  8022. return 0;
  8023. }
  8024. /**
  8025. * @brief Retrieve the scheduling parameters of a specific thread.
  8026. *
  8027. * This function retrieves the scheduling parameters of the thread identified by the thread ID (`tid`).
  8028. * The retrieved parameters are stored in the structure pointed to by the `param` argument.
  8029. *
  8030. * @param[in] tid The thread ID of the target thread whose scheduling parameters are to be retrieved.
  8031. * @param[out] param A pointer to a structure where the scheduling parameters will be stored. The structure
  8032. * typically includes fields like priority and policy.
  8033. *
  8034. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8035. *
  8036. * @note The caller must have appropriate permissions to query the scheduling parameters of the specified thread.
  8037. * The exact structure and fields of `param` depend on the system's implementation and scheduling policies.
  8038. */
  8039. sysret_t sys_sched_getparam(const pid_t tid, void *param)
  8040. {
  8041. struct sched_param *sched_param = RT_NULL;
  8042. rt_thread_t thread;
  8043. int ret = -1;
  8044. if (!lwp_user_accessable(param, sizeof(struct sched_param)))
  8045. {
  8046. return -EFAULT;
  8047. }
  8048. sched_param = kmem_get(sizeof(struct sched_param));
  8049. if (sched_param == RT_NULL)
  8050. {
  8051. return -ENOMEM;
  8052. }
  8053. thread = lwp_tid_get_thread_and_inc_ref(tid);
  8054. if (thread)
  8055. {
  8056. sched_param->sched_priority = RT_SCHED_PRIV(thread).current_priority;
  8057. ret = 0;
  8058. }
  8059. lwp_tid_dec_ref(thread);
  8060. lwp_put_to_user((void *)param, sched_param, sizeof(struct sched_param));
  8061. kmem_put(sched_param);
  8062. return ret;
  8063. }
  8064. /**
  8065. * @brief Get the maximum priority for a given scheduling policy.
  8066. *
  8067. * This function retrieves the maximum priority value that can be used with the specified
  8068. * scheduling policy.
  8069. *
  8070. * @param[in] policy The scheduling policy for which to retrieve the maximum priority.
  8071. *
  8072. * @return sysret_t Returns the maximum priority value on success. On failure, returns a
  8073. * negative error code.
  8074. *
  8075. * @note The valid priority range depends on the system's configuration and the selected
  8076. * scheduling policy. The returned value represents the highest priority that can
  8077. * be assigned to a thread using the given policy.
  8078. */
  8079. sysret_t sys_sched_get_priority_max(int policy)
  8080. {
  8081. if(policy < 0)
  8082. {
  8083. SET_ERRNO(EINVAL);
  8084. return -rt_get_errno();
  8085. }
  8086. return RT_THREAD_PRIORITY_MAX;
  8087. }
  8088. /**
  8089. * @brief Get the minimum priority for a given scheduling policy.
  8090. *
  8091. * This function retrieves the minimum priority value that can be used with the specified
  8092. * scheduling policy.
  8093. *
  8094. * @param[in] policy The scheduling policy for which to retrieve the minimum priority.
  8095. *
  8096. * @return sysret_t Returns the minimum priority value on success. On failure, returns a
  8097. * negative error code.
  8098. *
  8099. * @note The valid priority range depends on the system's configuration and the selected
  8100. * scheduling policy. The returned value represents the lowest priority that can
  8101. * be assigned to a thread using the given policy.
  8102. */
  8103. sysret_t sys_sched_get_priority_min(int policy)
  8104. {
  8105. if(policy < 0)
  8106. {
  8107. SET_ERRNO(EINVAL);
  8108. return -rt_get_errno();
  8109. }
  8110. return 0;
  8111. }
  8112. /**
  8113. * @brief Set the scheduling policy and parameters for a thread.
  8114. *
  8115. * This function sets the scheduling policy and associated parameters for the specified thread.
  8116. * It allows controlling the scheduling behavior of threads.
  8117. *
  8118. * @param[in] tid The thread ID of the target thread.
  8119. * @param[in] policy The scheduling policy to be applied. Common values include:
  8120. * - `SCHED_FIFO`: First-in, first-out scheduling.
  8121. * - `SCHED_RR`: Round-robin scheduling.
  8122. * - `SCHED_OTHER`: Default or standard scheduling.
  8123. * @param[in] param Pointer to a structure containing scheduling parameters, such as priority.
  8124. * The structure type depends on the system implementation.
  8125. *
  8126. * @return sysret_t Returns 0 on success. On failure, returns a negative error code.
  8127. *
  8128. * @note This function requires appropriate permissions to modify the scheduling settings
  8129. * of another thread. For most systems, elevated privileges may be required.
  8130. * Ensure the `param` structure is properly initialized for the given `policy`.
  8131. */
  8132. sysret_t sys_sched_setscheduler(int tid, int policy, void *param)
  8133. {
  8134. sysret_t ret;
  8135. struct sched_param *sched_param = RT_NULL;
  8136. rt_thread_t thread = RT_NULL;
  8137. if (!lwp_user_accessable(param, sizeof(struct sched_param)))
  8138. {
  8139. return -EFAULT;
  8140. }
  8141. sched_param = kmem_get(sizeof(struct sched_param));
  8142. if (sched_param == RT_NULL)
  8143. {
  8144. return -ENOMEM;
  8145. }
  8146. if (lwp_get_from_user(sched_param, param, sizeof(struct sched_param)) != sizeof(struct sched_param))
  8147. {
  8148. kmem_put(sched_param);
  8149. return -EINVAL;
  8150. }
  8151. thread = lwp_tid_get_thread_and_inc_ref(tid);
  8152. ret = rt_thread_control(thread, RT_THREAD_CTRL_RESET_PRIORITY, (void *)&sched_param->sched_priority);
  8153. lwp_tid_dec_ref(thread);
  8154. kmem_put(sched_param);
  8155. return ret;
  8156. }
  8157. /**
  8158. * @brief Get the scheduling policy of a thread.
  8159. *
  8160. * This function retrieves the current scheduling policy of the specified thread.
  8161. *
  8162. * @param[in] tid The thread ID of the target thread.
  8163. *
  8164. * @return sysret_t Returns the scheduling policy of the thread on success. On failure,
  8165. * returns a negative error code.
  8166. *
  8167. * @note The caller must have appropriate permissions to query the scheduling policy
  8168. * of the specified thread.
  8169. */
  8170. sysret_t sys_sched_getscheduler(int tid)
  8171. {
  8172. rt_thread_t thread = RT_NULL;
  8173. int rtn;
  8174. thread = lwp_tid_get_thread_and_inc_ref(tid);
  8175. lwp_tid_dec_ref(thread);
  8176. if (thread)
  8177. {
  8178. rtn = SCHED_RR;
  8179. }
  8180. else
  8181. {
  8182. rtn = -ESRCH;
  8183. }
  8184. return rtn;
  8185. }
  8186. /**
  8187. * @brief Flush the file descriptors' data to disk.
  8188. *
  8189. * This function flushes all modified data of the file associated with the specified
  8190. * file descriptor to disk, ensuring that any changes made to the file are committed
  8191. * to permanent storage.
  8192. *
  8193. * @param[in] fd The file descriptor associated with the file to be flushed. It should
  8194. * refer to an open file.
  8195. *
  8196. * @return sysret_t Returns `0` (0) on success. On failure, returns a negative
  8197. * error code.
  8198. *
  8199. * @note The `fsync` function ensures that all data written to the file is physically
  8200. * stored on disk, but it does not guarantee that all file metadata is flushed.
  8201. * To flush both data and metadata, `fdatasync` can be used.
  8202. */
  8203. sysret_t sys_fsync(int fd)
  8204. {
  8205. int res = fsync(fd);
  8206. if (res < 0)
  8207. res = rt_get_errno();
  8208. return res;
  8209. }
  8210. /**
  8211. * @brief Open a message queue.
  8212. *
  8213. * This function opens a message queue for communication between processes.
  8214. * It can create a new message queue or open an existing one, depending on the specified
  8215. * flags.
  8216. *
  8217. * @param[in] name The name of the message queue. The name should be a null-terminated
  8218. * string and is subject to system-specific naming conventions.
  8219. * @param[in] flags Flags that control the behavior of the message queue. Common flags include:
  8220. * - `O_CREAT`: Create the message queue if it does not exist.
  8221. * - `O_EXCL`: Fail if the message queue already exists.
  8222. * - `O_RDONLY`: Open the queue for reading.
  8223. * - `O_WRONLY`: Open the queue for writing.
  8224. * - `O_RDWR`: Open the queue for both reading and writing.
  8225. * @param[in] mode The mode to be applied when creating the message queue, which defines
  8226. * the permissions for the message queue (e.g., read, write).
  8227. * @param[in] attr A pointer to a `struct mq_attr` that defines the attributes of the
  8228. * message queue, such as the maximum number of messages and the size of
  8229. * each message. If `NULL`, default values are used.
  8230. *
  8231. * @return mqd_t Returns a non-negative file descriptor for the message queue on success.
  8232. * On failure, returns `-1` and sets `errno` to indicate the error.
  8233. *
  8234. * @note If the message queue is created, its attributes (such as the maximum number of
  8235. * messages and message size) must be defined in the `mq_attr` structure. If the
  8236. * `O_CREAT` flag is not specified and the queue does not exist, the function will
  8237. * return `-1`.
  8238. */
  8239. mqd_t sys_mq_open(const char *name, int flags, mode_t mode, struct mq_attr *attr)
  8240. {
  8241. mqd_t mqdes;
  8242. sysret_t ret = 0;
  8243. #ifdef ARCH_MM_MMU
  8244. char *kname = RT_NULL;
  8245. rt_size_t len = 0;
  8246. struct mq_attr attr_k;
  8247. len = lwp_user_strlen(name);
  8248. if (!len)
  8249. return (mqd_t)-EINVAL;
  8250. kname = (char *)kmem_get(len + 1);
  8251. if (!kname)
  8252. return (mqd_t)-ENOMEM;
  8253. if (attr == NULL)
  8254. {
  8255. attr_k.mq_maxmsg = 10;
  8256. attr_k.mq_msgsize = 8192;
  8257. attr_k.mq_flags = 0;
  8258. attr = &attr_k;
  8259. }
  8260. else
  8261. {
  8262. if (!lwp_get_from_user(&attr_k, (void *)attr, sizeof(struct mq_attr)))
  8263. return -EINVAL;
  8264. }
  8265. lwp_get_from_user(kname, (void *)name, len + 1);
  8266. mqdes = mq_open(kname, flags, mode, &attr_k);
  8267. if (mqdes == -1)
  8268. {
  8269. ret = GET_ERRNO();
  8270. }
  8271. lwp_put_to_user(attr, &attr_k, sizeof(struct mq_attr));
  8272. kmem_put(kname);
  8273. #else
  8274. mqdes = mq_open(name, flags, mode, attr);
  8275. #endif
  8276. if (mqdes == -1)
  8277. return (mqd_t)ret;
  8278. else
  8279. return mqdes;
  8280. }
  8281. /**
  8282. * @brief Remove a message queue.
  8283. *
  8284. * This function removes a message queue identified by its name. If the message queue
  8285. * is open by any process, it will be removed only when all the processes close their
  8286. * file descriptors associated with the message queue.
  8287. *
  8288. * @param[in] name The name of the message queue to be removed. It should be a null-terminated
  8289. * string that conforms to system-specific naming conventions.
  8290. *
  8291. * @return sysret_t Returns `0` on success. On failure, returns a negative
  8292. * error code.
  8293. *
  8294. * @note After a successful call, the message queue is removed from the system. However,
  8295. * the removal will not take effect until all processes close their file descriptors
  8296. * associated with the queue. The function will fail if the message queue is still
  8297. * open by other processes.
  8298. */
  8299. sysret_t sys_mq_unlink(const char *name)
  8300. {
  8301. int ret = 0;
  8302. #ifdef ARCH_MM_MMU
  8303. char *kname = RT_NULL;
  8304. rt_size_t len = 0;
  8305. len = lwp_user_strlen(name);
  8306. if (!len)
  8307. return -EINVAL;
  8308. kname = (char *)kmem_get(len + 1);
  8309. if (!kname)
  8310. return -ENOMEM;
  8311. lwp_get_from_user(kname, (void *)name, len + 1);
  8312. ret = mq_unlink(kname);
  8313. if (ret < 0)
  8314. {
  8315. ret = GET_ERRNO();
  8316. }
  8317. kmem_put(kname);
  8318. return ret;
  8319. #else
  8320. ret = mq_unlink(name);
  8321. return (ret < 0 ? GET_ERRNO() : ret);
  8322. #endif
  8323. }
  8324. /**
  8325. * @brief Send a message to a message queue with a timeout.
  8326. *
  8327. * This function sends a message to the specified message queue, but it allows the sender
  8328. * to specify a timeout. If the message queue is full, the function will block until either
  8329. * space becomes available or the specified timeout expires. If the timeout expires without
  8330. * space being available, the function returns an error.
  8331. *
  8332. * @param[in] mqd The message queue descriptor returned by `sys_mq_open`.
  8333. * @param[in] msg A pointer to the message to be sent.
  8334. * @param[in] len The length of the message to send.
  8335. * @param[in] prio The priority of the message (higher values indicate higher priority).
  8336. * @param[in] at A pointer to a `timespec` structure that specifies the absolute timeout.
  8337. * If the timeout expires before the message can be sent, the function returns
  8338. * an error.
  8339. *
  8340. * @return sysret_t Returns `0` on success. On failure, returns a negative error
  8341. * code.
  8342. *
  8343. * @note The function uses the `timespec` structure to specify the absolute timeout. The
  8344. * `at` parameter should indicate the time at which the operation should time out.
  8345. * If the timeout is `NULL`, the function will not apply any timeout (it will block
  8346. * indefinitely until the message is sent).
  8347. *
  8348. * @see sys_mq_send
  8349. */
  8350. sysret_t sys_mq_timedsend(mqd_t mqd, const char *msg, size_t len, unsigned prio, const struct timespec *at)
  8351. {
  8352. int ret = 0;
  8353. #ifdef ARCH_MM_MMU
  8354. char *kmsg = RT_NULL;
  8355. struct timespec at_k;
  8356. kmsg = (char *)kmem_get(len + 1);
  8357. if (!kmsg)
  8358. return -ENOMEM;
  8359. lwp_get_from_user(&at_k, (void *)at, sizeof(struct timespec));
  8360. lwp_get_from_user(kmsg, (void *)msg, len + 1);
  8361. ret = mq_timedsend(mqd, kmsg, len, prio, &at_k);
  8362. if (ret < 0)
  8363. {
  8364. ret = GET_ERRNO();
  8365. }
  8366. kmem_put(kmsg);
  8367. return ret;
  8368. #else
  8369. ret = mq_timedsend(mqd, msg, len, prio, at);
  8370. return (ret < 0 ? GET_ERRNO() : ret);
  8371. #endif
  8372. }
  8373. /**
  8374. * @brief Receive a message from a message queue with a timeout.
  8375. *
  8376. * This function attempts to receive a message from the specified message queue, but it
  8377. * allows the receiver to specify a timeout. If the queue is empty, the function will block
  8378. * until either a message becomes available or the specified timeout expires. If the timeout
  8379. * expires without receiving a message, the function returns an error.
  8380. *
  8381. * @param[in] mqd The message queue descriptor returned by `sys_mq_open`.
  8382. * @param[out] msg A pointer to the buffer where the received message will be stored.
  8383. * @param[in] len The maximum length of the buffer to store the received message.
  8384. * @param[out] prio A pointer to an unsigned integer that will be set to the priority
  8385. * of the received message.
  8386. * @param[in] at A pointer to a `timespec` structure that specifies the absolute timeout.
  8387. * If the timeout expires before a message is received, the function will
  8388. * return an error.
  8389. *
  8390. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8391. *
  8392. * @note The function uses the `timespec` structure to specify the absolute timeout. The
  8393. * `at` parameter should indicate the time at which the operation should time out.
  8394. * If the timeout is `NULL`, the function will block indefinitely until a message is
  8395. * received.
  8396. *
  8397. * @see sys_mq_receive
  8398. */
  8399. sysret_t sys_mq_timedreceive(mqd_t mqd, char *restrict msg, size_t len, unsigned *restrict prio, const struct timespec *restrict at)
  8400. {
  8401. int ret = 0;
  8402. #ifdef ARCH_MM_MMU
  8403. char *restrict kmsg = RT_NULL;
  8404. struct timespec at_k;
  8405. kmsg = (char *restrict)kmem_get(len + 1);
  8406. if (!kmsg)
  8407. return -ENOMEM;
  8408. lwp_get_from_user(kmsg, (void *)msg, len + 1);
  8409. if (at == RT_NULL)
  8410. {
  8411. ret = mq_timedreceive(mqd, kmsg, len, prio, RT_NULL);
  8412. }
  8413. else
  8414. {
  8415. if (!lwp_get_from_user(&at_k, (void *)at, sizeof(struct timespec)))
  8416. return -EINVAL;
  8417. ret = mq_timedreceive(mqd, kmsg, len, prio, &at_k);
  8418. }
  8419. if (ret > 0)
  8420. lwp_put_to_user(msg, kmsg, len + 1);
  8421. if (ret < 0)
  8422. {
  8423. ret = GET_ERRNO();
  8424. }
  8425. kmem_put(kmsg);
  8426. return ret;
  8427. #else
  8428. ret = mq_timedreceive(mqd, msg, len, prio, at);
  8429. return (ret < 0 ? GET_ERRNO() : ret);
  8430. #endif
  8431. }
  8432. /**
  8433. * @brief Set up asynchronous notification for a message queue.
  8434. *
  8435. * This function configures asynchronous notification for a message queue. When a message
  8436. * is available in the queue, the system can notify the calling process through a signal
  8437. * or another method specified in the `sigevent` structure. This is typically used to allow
  8438. * a process to be notified when a message arrives without having to block in the receive call.
  8439. *
  8440. * @param[in] mqd The message queue descriptor returned by `sys_mq_open`.
  8441. * @param[in] sev A pointer to a `sigevent` structure that specifies the notification
  8442. * mechanism to be used when a message is received. It could include
  8443. * signals or other notification types such as event flags or message passing.
  8444. *
  8445. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8446. *
  8447. * @note This function enables asynchronous notification, but the specific behavior depends
  8448. * on the configuration specified in the `sev` parameter, which could involve signals
  8449. * or other forms of notification.
  8450. *
  8451. * @see sys_mq_send, sys_mq_timedreceive
  8452. */
  8453. sysret_t sys_mq_notify(mqd_t mqd, const struct sigevent *sev)
  8454. {
  8455. int ret = 0;
  8456. #ifdef ARCH_MM_MMU
  8457. struct sigevent sev_k;
  8458. lwp_get_from_user(&sev_k, (void *)sev, sizeof(struct timespec));
  8459. ret = mq_notify(mqd, &sev_k);
  8460. #else
  8461. ret = mq_notify(mqd, sev);
  8462. #endif
  8463. return (ret < 0 ? GET_ERRNO() : ret);
  8464. }
  8465. /**
  8466. * @brief Get or set attributes of a message queue.
  8467. *
  8468. * This function allows you to get or set the attributes of an existing message queue.
  8469. * If the `new` attribute structure is non-NULL, it updates the message queue with the new
  8470. * attributes. Otherwise, If the `old` attribute structure is non-NULL, it will return the current
  8471. * attributes of the message queue.
  8472. *
  8473. * @param[in] mqd The message queue descriptor returned by `sys_mq_open`.
  8474. * @param[in] new A pointer to a `mq_attr` structure containing the new attributes to set.
  8475. * If `NULL`, the function will not modify the message queue attributes.
  8476. * @param[out] old A pointer to a `mq_attr` structure where the current message queue
  8477. * attributes will be returned. If `NULL`, the current attributes will not
  8478. * be returned.
  8479. *
  8480. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8481. *
  8482. * @note The `mq_attr` structure contains parameters like the maximum number of messages,
  8483. * the maximum message size, and other attributes that control the behavior of the
  8484. * message queue.
  8485. *
  8486. * @see sys_mq_open, sys_mq_notify
  8487. */
  8488. sysret_t sys_mq_getsetattr(mqd_t mqd, const struct mq_attr *restrict new, struct mq_attr *restrict old)
  8489. {
  8490. int ret = 0;
  8491. #ifdef ARCH_MM_MMU
  8492. size_t size = sizeof(struct mq_attr);
  8493. struct mq_attr *restrict knew = NULL;
  8494. struct mq_attr *restrict kold = NULL;
  8495. if (new != RT_NULL)
  8496. {
  8497. if (!lwp_user_accessable((void *)new, size))
  8498. return -EFAULT;
  8499. knew = kmem_get(size);
  8500. if (!knew)
  8501. return -ENOMEM;
  8502. lwp_get_from_user(knew, (void *)new, size);
  8503. }
  8504. if (!lwp_user_accessable((void *)old, size))
  8505. return -EFAULT;
  8506. kold = kmem_get(size);
  8507. if (!kold)
  8508. return -ENOMEM;
  8509. lwp_get_from_user(kold, (void *)old, size);
  8510. ret = mq_setattr(mqd, knew, kold);
  8511. if (ret != -1)
  8512. lwp_put_to_user(old, kold, size);
  8513. if (ret < 0)
  8514. {
  8515. ret = GET_ERRNO();
  8516. }
  8517. kmem_put(kold);
  8518. if (new != RT_NULL)
  8519. kmem_put(knew);
  8520. return ret;
  8521. #else
  8522. ret = mq_setattr(mqd, new, old);
  8523. return (ret < 0 ? GET_ERRNO() : ret);
  8524. #endif
  8525. }
  8526. /**
  8527. * @brief Close a message queue descriptor.
  8528. *
  8529. * This function closes a message queue descriptor. After calling this function, the
  8530. * descriptor can no longer be used to interact with the message queue. Any resources
  8531. * associated with the descriptor are released. If the message queue was opened with the
  8532. * `O_CLOEXEC` flag, it will be automatically closed when the calling process executes
  8533. * an `exec` system call.
  8534. *
  8535. * @param[in] mqd The message queue descriptor to be closed. It was previously returned
  8536. * by `sys_mq_open`.
  8537. *
  8538. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8539. *
  8540. * @see sys_mq_open, sys_mq_unlink
  8541. */
  8542. sysret_t sys_mq_close(mqd_t mqd)
  8543. {
  8544. int ret = 0;
  8545. #ifdef ARCH_MM_MMU
  8546. ret = mq_close(mqd);
  8547. #else
  8548. ret = mq_close(mqd);
  8549. #endif
  8550. return (ret < 0 ? GET_ERRNO() : ret);
  8551. }
  8552. #define ICACHE (1<<0)
  8553. #define DCACHE (1<<1)
  8554. #define BCACHE (ICACHE|DCACHE)
  8555. /**
  8556. * @brief Flush the cache for a specified memory region.
  8557. *
  8558. * This function flushes the cache for a specified memory region. It is commonly used
  8559. * to ensure that the contents of a memory region are written back to the main memory
  8560. * or that stale cache entries are invalidated. The cache operation can be controlled
  8561. * by the `cache` parameter to determine whether to clean or invalidate the cache.
  8562. *
  8563. * @param[in] addr The starting address of the memory region to flush.
  8564. * @param[in] size The size of the memory region to flush, in bytes.
  8565. * @param[in] cache A flag to specify the cache operation:
  8566. * - `CACHE_CLEAN`: Clean the cache (write back to memory).
  8567. * - `CACHE_INVALIDATE`: Invalidate the cache (discard cached data).
  8568. * - `CACHE_FLUSH`: Both clean and invalidate the cache.
  8569. *
  8570. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8571. *
  8572. * @note This function is typically used in low-level operations or in systems where
  8573. * cache coherence between memory and cache is critical.
  8574. */
  8575. rt_weak sysret_t sys_cacheflush(void *addr, int size, int cache)
  8576. {
  8577. if (!lwp_user_accessable(addr, size))
  8578. return -EFAULT;
  8579. if (((size_t)addr < (size_t)addr + size) &&
  8580. ((size_t)addr >= USER_VADDR_START) &&
  8581. ((size_t)addr + size < USER_VADDR_TOP))
  8582. {
  8583. if ((cache & DCACHE))
  8584. {
  8585. rt_hw_cpu_dcache_clean_and_invalidate(addr, size);
  8586. }
  8587. if ((cache & ICACHE))
  8588. {
  8589. rt_hw_cpu_icache_invalidate(addr, size);
  8590. }
  8591. return 0;
  8592. }
  8593. return -EFAULT;
  8594. }
  8595. /**
  8596. * @brief Get system information.
  8597. *
  8598. * This function retrieves information about the current system, such as the system name,
  8599. * version, release, architecture, and other details. The information is stored in the
  8600. * `utsname` structure pointed to by the `uts` parameter.
  8601. *
  8602. * @param[out] uts A pointer to a `utsname` structure where the system information will
  8603. * be stored. The structure includes fields such as:
  8604. * - `sysname`: Operating system name.
  8605. * - `nodename`: Network node hostname.
  8606. * - `release`: Operating system release version.
  8607. * - `version`: Operating system version.
  8608. * - `machine`: Hardware identifier (architecture).
  8609. *
  8610. * @return sysret_t Returns `SYSRET_OK` (0) on success. On failure, returns a negative error code.
  8611. *
  8612. * @note This function provides details about the system environment, which may be useful
  8613. * for applications needing to adapt to different system configurations.
  8614. *
  8615. * @see sys_gethostname, sys_uname
  8616. */
  8617. sysret_t sys_uname(struct utsname *uts)
  8618. {
  8619. struct utsname utsbuff = {0};
  8620. int ret = 0;
  8621. const char *machine;
  8622. if (!lwp_user_accessable((void *)uts, sizeof(struct utsname)))
  8623. {
  8624. return -EFAULT;
  8625. }
  8626. rt_strncpy(utsbuff.sysname, "RT-Thread", sizeof(utsbuff.sysname));
  8627. utsbuff.nodename[0] = '\0';
  8628. ret = rt_snprintf(utsbuff.release, sizeof(utsbuff.release), "%u.%u.%u",
  8629. RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH);
  8630. if (ret < 0)
  8631. {
  8632. return -EIO;
  8633. }
  8634. ret = rt_snprintf(utsbuff.version, sizeof(utsbuff.version), "RT-Thread %u.%u.%u %s %s",
  8635. RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH, __DATE__, __TIME__);
  8636. if (ret < 0)
  8637. {
  8638. return -EIO;
  8639. }
  8640. machine = rt_hw_cpu_arch();
  8641. rt_strncpy(utsbuff.machine, machine, sizeof(utsbuff.machine));
  8642. utsbuff.domainname[0] = '\0';
  8643. lwp_put_to_user(uts, &utsbuff, sizeof utsbuff);
  8644. return 0;
  8645. }
  8646. /**
  8647. * @brief Get filesystem statistics.
  8648. *
  8649. * This function retrieves statistics about the filesystem at the specified path,
  8650. * storing the results in the provided `statfs` structure. It can be used to obtain
  8651. * information such as the total number of blocks, free blocks, available inodes, etc.
  8652. *
  8653. * @param[in] path The path to the filesystem to query. If the path is the root directory
  8654. * (`"/"`), it returns statistics for the root filesystem.
  8655. * @param[out] buf A pointer to a `statfs` structure where the filesystem statistics will
  8656. * be stored. This structure includes information such as:
  8657. * - `f_type`: The type of the filesystem.
  8658. * - `f_bsize`: The optimal block size for I/O operations.
  8659. * - `f_blocks`: Total number of blocks in the filesystem.
  8660. * - `f_bfree`: Number of free blocks.
  8661. * - `f_bavail`: Number of free blocks available to non-superuser.
  8662. * - `f_files`: Total number of file nodes (inodes).
  8663. * - `f_ffree`: Number of free inodes.
  8664. * - `f_favail`: Number of inodes available to non-superuser.
  8665. * - `f_flag`: Flags describing the filesystem.
  8666. * - `f_namelen`: Maximum length of a filename.
  8667. *
  8668. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8669. *
  8670. * @note This function is useful for determining the available space and file system
  8671. * characteristics of a mounted filesystem.
  8672. *
  8673. * @see sys_fstatfs
  8674. */
  8675. sysret_t sys_statfs(const char *path, struct statfs *buf)
  8676. {
  8677. int ret = 0;
  8678. size_t len;
  8679. size_t copy_len;
  8680. char *copy_path;
  8681. struct statfs statfsbuff = {0};
  8682. if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
  8683. {
  8684. return -EFAULT;
  8685. }
  8686. len = lwp_user_strlen(path);
  8687. if (len <= 0)
  8688. {
  8689. return -EFAULT;
  8690. }
  8691. copy_path = (char*)rt_malloc(len + 1);
  8692. if (!copy_path)
  8693. {
  8694. return -ENOMEM;
  8695. }
  8696. copy_len = lwp_get_from_user(copy_path, (void*)path, len);
  8697. if (copy_len == 0)
  8698. {
  8699. rt_free(copy_path);
  8700. return -EFAULT;
  8701. }
  8702. copy_path[copy_len] = '\0';
  8703. ret = _SYS_WRAP(statfs(copy_path, &statfsbuff));
  8704. rt_free(copy_path);
  8705. if (ret == 0)
  8706. {
  8707. lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
  8708. }
  8709. return ret;
  8710. }
  8711. /**
  8712. * @brief Get extended filesystem statistics (64-bit).
  8713. *
  8714. * This function retrieves extended statistics about the filesystem at the specified path,
  8715. * using 64-bit values for larger filesystems or filesystems with a large number of blocks or inodes.
  8716. * The information is stored in the provided `statfs` structure, which includes details such as total
  8717. * blocks, free blocks, available inodes, etc.
  8718. *
  8719. * @param[in] path The path to the filesystem to query. Typically, this would be the root directory
  8720. * (`"/"`) for the root filesystem, or any other directory on the filesystem.
  8721. * @param[in] sz The size of the `statfs` structure. This parameter allows for future extensions
  8722. * of the `statfs` structure without breaking compatibility with older applications.
  8723. * @param[out] buf A pointer to a `statfs` structure where the extended filesystem statistics
  8724. * will be stored. This structure includes information such as:
  8725. * - `f_bsize`: The optimal block size for I/O operations.
  8726. * - `f_blocks`: Total number of blocks in the filesystem.
  8727. * - `f_bfree`: Number of free blocks.
  8728. * - `f_bavail`: Number of free blocks available to non-superuser.
  8729. *
  8730. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8731. *
  8732. * @note This function is particularly useful for querying large filesystems or filesystems with
  8733. * 64-bit addresses or data values, and is an extended version of the standard `sys_statfs`.
  8734. *
  8735. * @see sys_statfs
  8736. */
  8737. sysret_t sys_statfs64(const char *path, size_t sz, struct statfs *buf)
  8738. {
  8739. int ret = 0;
  8740. size_t len;
  8741. size_t copy_len;
  8742. char *copy_path;
  8743. struct statfs statfsbuff = {0};
  8744. if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
  8745. {
  8746. return -EFAULT;
  8747. }
  8748. if (sz != sizeof(struct statfs))
  8749. {
  8750. return -EINVAL;
  8751. }
  8752. len = lwp_user_strlen(path);
  8753. if (len <= 0)
  8754. {
  8755. return -EFAULT;
  8756. }
  8757. copy_path = (char*)rt_malloc(len + 1);
  8758. if (!copy_path)
  8759. {
  8760. return -ENOMEM;
  8761. }
  8762. copy_len = lwp_get_from_user(copy_path, (void*)path, len);
  8763. if (copy_len == 0)
  8764. {
  8765. rt_free(copy_path);
  8766. return -EFAULT;
  8767. }
  8768. copy_path[copy_len] = '\0';
  8769. ret = _SYS_WRAP(statfs(copy_path, &statfsbuff));
  8770. rt_free(copy_path);
  8771. if (ret == 0)
  8772. {
  8773. lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
  8774. }
  8775. return ret;
  8776. }
  8777. /**
  8778. * @brief Get filesystem statistics for a file descriptor.
  8779. *
  8780. * This function retrieves statistics about the filesystem containing the file referred to by the
  8781. * file descriptor `fd`. The information is stored in the provided `statfs` structure, which includes
  8782. * details such as total blocks, free blocks, available inodes, etc.
  8783. *
  8784. * @param[in] fd The file descriptor referring to an open file. The file descriptor must be
  8785. * valid and represent a file on a mounted filesystem.
  8786. * @param[out] buf A pointer to a `statfs` structure where the filesystem statistics will be
  8787. * stored. This structure includes information such as:
  8788. * - `f_bsize`: The optimal block size for I/O operations.
  8789. * - `f_blocks`: Total number of blocks in the filesystem.
  8790. * - `f_bfree`: Number of free blocks.
  8791. * - `f_bavail`: Number of free blocks available to non-superuser.
  8792. *
  8793. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8794. *
  8795. * @note This function is useful for obtaining filesystem information about a specific file
  8796. * represented by its file descriptor, rather than querying the filesystem associated with
  8797. * a specific path.
  8798. *
  8799. * @see sys_statfs
  8800. */
  8801. sysret_t sys_fstatfs(int fd, struct statfs *buf)
  8802. {
  8803. int ret = 0;
  8804. struct statfs statfsbuff = {0};
  8805. if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
  8806. {
  8807. return -EFAULT;
  8808. }
  8809. ret = _SYS_WRAP(fstatfs(fd, &statfsbuff));
  8810. if (ret == 0)
  8811. {
  8812. lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
  8813. }
  8814. return ret;
  8815. }
  8816. /**
  8817. * @brief Get 64-bit filesystem statistics for a file descriptor.
  8818. *
  8819. * This function retrieves 64-bit statistics about the filesystem containing the file referred to by
  8820. * the file descriptor `fd`. The statistics are stored in the provided `statfs` structure, which
  8821. * includes details such as total blocks, free blocks, available inodes, etc. The function differs
  8822. * from `sys_fstatfs` in that it supports 64-bit values for filesystem sizes and counts.
  8823. *
  8824. * @param[in] fd The file descriptor referring to an open file. The file descriptor must be
  8825. * valid and represent a file on a mounted filesystem.
  8826. * @param[in] sz The size of the `statfs` structure (typically used to ensure compatibility with
  8827. * different versions of the structure).
  8828. * @param[out] buf A pointer to a `statfs` structure where the filesystem statistics will be
  8829. * stored. This structure includes information such as:
  8830. * - `f_bsize`: The optimal block size for I/O operations.
  8831. * - `f_blocks`: Total number of blocks in the filesystem (64-bit).
  8832. * - `f_bfree`: Number of free blocks (64-bit).
  8833. * - `f_bavail`: Number of free blocks available to non-superuser (64-bit).
  8834. *
  8835. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8836. * @note This function is particularly useful for systems supporting 64-bit filesystem statistics.
  8837. * It provides extended accuracy for large filesystems, including those with very large
  8838. * numbers of blocks or inodes.
  8839. *
  8840. * @see sys_fstatfs
  8841. */
  8842. sysret_t sys_fstatfs64(int fd, size_t sz, struct statfs *buf)
  8843. {
  8844. int ret = 0;
  8845. struct statfs statfsbuff = {0};
  8846. if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
  8847. {
  8848. return -EFAULT;
  8849. }
  8850. if (sz != sizeof(struct statfs))
  8851. {
  8852. return -EINVAL;
  8853. }
  8854. ret = _SYS_WRAP(fstatfs(fd, &statfsbuff));
  8855. if (ret == 0)
  8856. {
  8857. lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
  8858. }
  8859. return ret;
  8860. }
  8861. static char *_cp_from_usr_string(char *dst, char *src, size_t length)
  8862. {
  8863. char *rc;
  8864. size_t copied_bytes;
  8865. if (length)
  8866. {
  8867. copied_bytes = lwp_get_from_user(dst, src, length);
  8868. dst[copied_bytes] = '\0';
  8869. rc = dst;
  8870. }
  8871. else
  8872. {
  8873. rc = RT_NULL;
  8874. }
  8875. return rc;
  8876. }
  8877. /**
  8878. * @brief Mount a filesystem.
  8879. *
  8880. * This function mounts a filesystem onto a specified directory. It allows for mounting various
  8881. * types of filesystems, including but not limited to `ext4`, `nfs`, and `tmpfs`. The function
  8882. * allows the specification of the source device, the target mount point, and additional parameters
  8883. * such as filesystem type, mount flags, and extra data.
  8884. *
  8885. * @param[in] source The source of the filesystem, which can be a device (e.g., `/dev/sda1`)
  8886. * or a network resource (e.g., a NFS share). For certain filesystems like
  8887. * `tmpfs`, this can be `NULL`.
  8888. * @param[in] target The target directory where the filesystem will be mounted.
  8889. * This should be an existing empty directory.
  8890. * @param[in] filesystemtype The type of filesystem to mount, e.g., `ext4`, `tmpfs`, `nfs`, etc.
  8891. * @param[in] mountflags Flags that control the mount operation, such as `MS_RDONLY` for read-only
  8892. * mounts or `MS_NODEV` to prevent device files from being created.
  8893. * @param[in] data Optional data that is passed to the filesystem's mount handler. This
  8894. * may be used for setting up specific parameters for the filesystem type.
  8895. *
  8896. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8897. *
  8898. * @note Mounting a filesystem on an existing mount point can replace the existing filesystem at that
  8899. * location. Make sure the target directory is empty before mounting to avoid any conflicts.
  8900. */
  8901. sysret_t sys_mount(char *source, char *target, char *filesystemtype,
  8902. unsigned long mountflags, void *data)
  8903. {
  8904. char *kbuffer, *ksource, *ktarget, *kfs;
  8905. size_t len_source, len_target, len_fs;
  8906. char *tmp = NULL;
  8907. int ret = 0;
  8908. struct stat buf = {0};
  8909. char *dev_fullpath = RT_NULL;
  8910. len_source = source ? lwp_user_strlen(source) : 0;
  8911. if (len_source < 0)
  8912. return -EINVAL;
  8913. len_target = target ? lwp_user_strlen(target) : 0;
  8914. if (len_target <= 0)
  8915. return -EINVAL;
  8916. len_fs = filesystemtype ? lwp_user_strlen(filesystemtype) : 0;
  8917. if (len_fs < 0)
  8918. return -EINVAL;
  8919. kbuffer = (char *)rt_malloc(len_source + 1 + len_target + 1 + len_fs + 1);
  8920. if (!kbuffer)
  8921. {
  8922. return -ENOMEM;
  8923. }
  8924. /* get parameters from user space */
  8925. ksource = kbuffer;
  8926. ktarget = ksource + len_source + 1;
  8927. kfs = ktarget + len_target + 1;
  8928. ksource = _cp_from_usr_string(ksource, source, len_source);
  8929. ktarget = _cp_from_usr_string(ktarget, target, len_target);
  8930. kfs = _cp_from_usr_string(kfs, filesystemtype, len_fs);
  8931. if (mountflags & MS_REMOUNT)
  8932. {
  8933. ret = dfs_remount(ktarget, mountflags, data);
  8934. }
  8935. else
  8936. {
  8937. if (strcmp(kfs, "nfs") == 0)
  8938. {
  8939. tmp = ksource;
  8940. ksource = NULL;
  8941. }
  8942. if (strcmp(kfs, "tmp") == 0)
  8943. {
  8944. ksource = NULL;
  8945. }
  8946. if (ksource && !dfs_file_stat(ksource, &buf) && S_ISBLK(buf.st_mode))
  8947. {
  8948. dev_fullpath = dfs_normalize_path(RT_NULL, ksource);
  8949. RT_ASSERT(rt_strncmp(dev_fullpath, "/dev/", sizeof("/dev/") - 1) == 0);
  8950. ret = dfs_mount(dev_fullpath + sizeof("/dev/") - 1, ktarget, kfs, 0, tmp);
  8951. }
  8952. else
  8953. {
  8954. ret = dfs_mount(ksource, ktarget, kfs, 0, tmp);
  8955. }
  8956. if (ret < 0)
  8957. {
  8958. ret = -rt_get_errno();
  8959. }
  8960. }
  8961. rt_free(kbuffer);
  8962. rt_free(dev_fullpath);
  8963. return ret;
  8964. }
  8965. /**
  8966. * @brief Unmount a filesystem.
  8967. *
  8968. * This function unmounts a previously mounted filesystem from a specified target directory or file.
  8969. * It removes the filesystem from the system, making the resources associated with it available for
  8970. * other uses. It can also support additional flags to control the unmounting behavior.
  8971. *
  8972. * @param[in] __special_file The target directory or mount point from which the filesystem is to be
  8973. * unmounted. This should be a valid mount point that was previously mounted.
  8974. * @param[in] __flags Flags that control the unmounting behavior. Common flags include:
  8975. * - `MNT_FORCE`: Forces the unmount even if the filesystem is busy.
  8976. * - `MNT_DETACH`: Detaches the filesystem, allowing it to be unmounted
  8977. * asynchronously.
  8978. *
  8979. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  8980. *
  8981. * @note The `MNT_FORCE` flag should be used with caution, as it may result in data loss or corruption
  8982. * if there are pending writes or active processes using the filesystem.
  8983. *
  8984. * @see sys_mount
  8985. */
  8986. sysret_t sys_umount2(char *__special_file, int __flags)
  8987. {
  8988. char *copy_special_file;
  8989. size_t len_special_file, copy_len_special_file;
  8990. int ret = 0;
  8991. len_special_file = lwp_user_strlen(__special_file);
  8992. if (len_special_file <= 0)
  8993. {
  8994. return -EFAULT;
  8995. }
  8996. copy_special_file = (char*)rt_malloc(len_special_file + 1);
  8997. if (!copy_special_file)
  8998. {
  8999. return -ENOMEM;
  9000. }
  9001. copy_len_special_file = lwp_get_from_user(copy_special_file, __special_file, len_special_file);
  9002. copy_special_file[copy_len_special_file] = '\0';
  9003. ret = dfs_unmount(copy_special_file);
  9004. rt_free(copy_special_file);
  9005. return ret;
  9006. }
  9007. /**
  9008. * @brief Create a new hard link to an existing file.
  9009. *
  9010. * This function creates a new hard link to an existing file, making the file accessible from
  9011. * multiple filenames. The new link points to the same inode as the existing file, meaning
  9012. * both names refer to the same underlying data. The link count for the file is incremented.
  9013. *
  9014. * @param[in] existing The path to the existing file. It must be an absolute or relative path
  9015. * to a file that already exists.
  9016. * @param[in] new The path to the new link to be created. This can be a new filename or
  9017. * an existing directory where the link will be placed.
  9018. *
  9019. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  9020. *
  9021. * @note Hard links share the same inode number, meaning changes to the data of the file via one
  9022. * link will be reflected in all hard links. Deleting any of the links will not remove the
  9023. * file data until all links are deleted.
  9024. */
  9025. sysret_t sys_link(const char *existing, const char *new)
  9026. {
  9027. int ret = -1;
  9028. int err = 0;
  9029. #ifdef RT_USING_DFS_V2
  9030. #ifdef ARCH_MM_MMU
  9031. int len = 0;
  9032. char *kexisting = RT_NULL;
  9033. char *knew = RT_NULL;
  9034. len = lwp_user_strlen(existing);
  9035. if (len <= 0)
  9036. {
  9037. return -EFAULT;
  9038. }
  9039. kexisting = (char *)kmem_get(len + 1);
  9040. if (!kexisting)
  9041. {
  9042. return -ENOMEM;
  9043. }
  9044. if (lwp_get_from_user(kexisting, (void *)existing, len + 1) != (len + 1))
  9045. {
  9046. kmem_put(kexisting);
  9047. return -EINVAL;
  9048. }
  9049. len = lwp_user_strlen(new);
  9050. if (len <= 0)
  9051. {
  9052. kmem_put(kexisting);
  9053. return -EFAULT;
  9054. }
  9055. knew = (char *)kmem_get(len + 1);
  9056. if (!knew)
  9057. {
  9058. kmem_put(kexisting);
  9059. return -ENOMEM;
  9060. }
  9061. if (lwp_get_from_user(knew, (void *)new, len + 1) != (len + 1))
  9062. {
  9063. kmem_put(knew);
  9064. kmem_put(kexisting);
  9065. return -EINVAL;
  9066. }
  9067. ret = dfs_file_link(kexisting, knew);
  9068. if(ret < 0)
  9069. {
  9070. err = GET_ERRNO();
  9071. }
  9072. kmem_put(knew);
  9073. kmem_put(kexisting);
  9074. #else
  9075. ret = dfs_file_link(existing, new);
  9076. #endif
  9077. #else
  9078. SET_ERRNO(EFAULT);
  9079. err = GET_ERRNO();
  9080. #endif
  9081. return (err < 0 ? err : ret);
  9082. }
  9083. /**
  9084. * @brief Create a symbolic link to an existing file or directory.
  9085. *
  9086. * This function creates a new symbolic link, which is a special file that contains a reference
  9087. * to another file or directory. The symbolic link allows for easy redirection or aliasing of
  9088. * file paths. Unlike a hard link, a symbolic link can point to a file or directory across
  9089. * different file systems.
  9090. *
  9091. * @param[in] existing The path to the existing file or directory that the symbolic link
  9092. * will refer to. It must be an absolute or relative path.
  9093. * @param[in] new The path to the new symbolic link to be created. This must be a valid
  9094. * path where the link will be placed.
  9095. *
  9096. * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
  9097. *
  9098. * @note A symbolic link is distinct from a hard link in that it points to the path of the target
  9099. * file or directory, rather than directly to the inode. If the target file or directory is
  9100. * removed or moved, the symbolic link will become "broken" and will not resolve to a valid
  9101. * location.
  9102. */
  9103. sysret_t sys_symlink(const char *existing, const char *new)
  9104. {
  9105. int ret = -1;
  9106. int err = 0 ;
  9107. #ifdef ARCH_MM_MMU
  9108. ret = lwp_user_strlen(existing);
  9109. if (ret <= 0)
  9110. {
  9111. return -EFAULT;
  9112. }
  9113. ret = lwp_user_strlen(new);
  9114. if (ret <= 0)
  9115. {
  9116. return -EFAULT;
  9117. }
  9118. #endif
  9119. #ifdef RT_USING_DFS_V2
  9120. ret = dfs_file_symlink(existing, new);
  9121. if(ret < 0)
  9122. {
  9123. err = GET_ERRNO();
  9124. }
  9125. #else
  9126. SET_ERRNO(EFAULT);
  9127. #endif
  9128. return (err < 0 ? err : ret);
  9129. }
  9130. /**
  9131. * @brief Create an event file descriptor.
  9132. *
  9133. * This function creates an eventfd, which is a file descriptor used for event notification.
  9134. * Eventfd is a simple mechanism to notify threads or processes about certain events using
  9135. * an integer counter. It is typically used for inter-process communication (IPC) or
  9136. * synchronization purposes, where one thread or process increments the counter to signal
  9137. * another thread or process.
  9138. *
  9139. * @param[in] count Initial value for the eventfd counter. It can be set to a non-zero
  9140. * value to initialize the counter to that value.
  9141. * @param[in] flags Flags that control the behavior of the eventfd. Valid flags include:
  9142. * - `EFD_CLOEXEC`: Set the close-on-exec flag for the eventfd.
  9143. * - `EFD_NONBLOCK`: Set the non-blocking flag for the eventfd.
  9144. *
  9145. * @return sysret_t On success, returns a valid file descriptor referring to the eventfd. On
  9146. * failure, returns a negative error code.
  9147. *
  9148. * @note Eventfd can be used for both counting and signaling purposes. It provides
  9149. * efficient signaling between threads or processes.
  9150. */
  9151. sysret_t sys_eventfd2(unsigned int count, int flags)
  9152. {
  9153. int ret;
  9154. ret = eventfd(count, flags);
  9155. return (ret < 0 ? GET_ERRNO() : ret);
  9156. }
  9157. /**
  9158. * @brief Create an epoll instance.
  9159. *
  9160. * This function creates an epoll instance, which is used for monitoring multiple file descriptors
  9161. * to see if I/O is possible on them. It allows a program to efficiently wait for events such as
  9162. * data being available for reading or space becoming available for writing. Epoll provides a scalable
  9163. * mechanism for managing large numbers of file descriptors.
  9164. *
  9165. * @param[in] flags Flags that control the behavior of the epoll instance. The valid flags include:
  9166. * - `EPOLL_CLOEXEC`: Set the close-on-exec flag for the epoll instance.
  9167. * - `EPOLL_NONBLOCK`: Set the non-blocking flag for the epoll instance.
  9168. *
  9169. * @return sysret_t On success, returns a file descriptor for the epoll instance. On failure,
  9170. * returns a negative error code.
  9171. *
  9172. * @note The `sys_epoll_create1` function is similar to `sys_epoll_create`, but it allows for
  9173. * additional control over the epoll instance creation via flags.
  9174. */
  9175. sysret_t sys_epoll_create1(int flags)
  9176. {
  9177. int ret;
  9178. ret = epoll_create(flags);
  9179. return (ret < 0 ? GET_ERRNO() : ret);
  9180. }
  9181. /**
  9182. * @brief Control an epoll instance.
  9183. *
  9184. * This function performs control operations on an epoll instance, such as adding, modifying,
  9185. * or removing file descriptors from the epoll instance's interest list.
  9186. *
  9187. * @param[in] fd The file descriptor of the epoll instance created using `sys_epoll_create` or `sys_epoll_create1`.
  9188. * @param[in] op The operation to perform on the epoll instance. It can be one of the following:
  9189. * - `EPOLL_CTL_ADD`: Add the specified file descriptor to the epoll interest list.
  9190. * - `EPOLL_CTL_MOD`: Modify the event mask of an existing file descriptor in the epoll interest list.
  9191. * - `EPOLL_CTL_DEL`: Remove the specified file descriptor from the epoll interest list.
  9192. * @param[in] fd2 The file descriptor to be added, modified, or removed from the epoll interest list.
  9193. * @param[in] ev A pointer to an `epoll_event` structure that describes the event to be associated with `fd2`.
  9194. * This parameter is required for `EPOLL_CTL_ADD` and `EPOLL_CTL_MOD`, but not for `EPOLL_CTL_DEL`.
  9195. *
  9196. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9197. *
  9198. * @note This function is typically used to manage the set of file descriptors monitored by an epoll instance.
  9199. */
  9200. sysret_t sys_epoll_ctl(int fd, int op, int fd2, struct epoll_event *ev)
  9201. {
  9202. int ret = 0;
  9203. struct epoll_event *kev = RT_NULL;
  9204. if (ev)
  9205. {
  9206. if (!lwp_user_accessable((void *)ev, sizeof(struct epoll_event)))
  9207. return -EFAULT;
  9208. kev = kmem_get(sizeof(struct epoll_event));
  9209. if (kev == RT_NULL)
  9210. {
  9211. return -ENOMEM;
  9212. }
  9213. if (lwp_get_from_user(kev, ev, sizeof(struct epoll_event)) != sizeof(struct epoll_event))
  9214. {
  9215. kmem_put(kev);
  9216. return -EINVAL;
  9217. }
  9218. ret = epoll_ctl(fd, op, fd2, kev);
  9219. kmem_put(kev);
  9220. }
  9221. else
  9222. {
  9223. ret = epoll_ctl(fd, op, fd2, RT_NULL);
  9224. }
  9225. return (ret < 0 ? GET_ERRNO() : ret);
  9226. }
  9227. /**
  9228. * @brief Wait for events on an epoll file descriptor, with the ability to block for specific signals.
  9229. *
  9230. * This function waits for events on an epoll file descriptor. It blocks until one or more events
  9231. * are available or a timeout occurs. In addition to waiting for events, it can also block for specific signals
  9232. * as specified by the `sigs` argument.
  9233. *
  9234. * @param[in] fd The file descriptor of the epoll instance, created using `sys_epoll_create` or `sys_epoll_create1`.
  9235. * @param[out] ev A pointer to an array of `epoll_event` structures that will receive the events that have occurred.
  9236. * @param[in] cnt The maximum number of events to return. This specifies the size of the `ev` array.
  9237. * @param[in] to The timeout in milliseconds. A negative value means no timeout, and `0` means non-blocking.
  9238. * @param[in] sigs A pointer to a signal set (`sigset_t`) that specifies the signals to block during the wait.
  9239. * If `NULL`, no signals are blocked.
  9240. * @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`.
  9241. *
  9242. * @return sysret_t On success, returns the number of events returned (may be `0` if the timeout expires with no events).
  9243. * On failure, returns a negative error code.
  9244. *
  9245. * @note This function is similar to `sys_epoll_wait`, but it also allows for signal handling, blocking the calling thread
  9246. * from receiving signals specified in the `sigs` set while waiting for events.
  9247. */
  9248. sysret_t sys_epoll_pwait(int fd,
  9249. struct epoll_event *ev,
  9250. int cnt,
  9251. int to,
  9252. const sigset_t *sigs,
  9253. unsigned long sigsetsize)
  9254. {
  9255. int ret = 0;
  9256. struct epoll_event *kev = RT_NULL;
  9257. sigset_t *ksigs = RT_NULL;
  9258. if (!lwp_user_accessable((void *)ev, cnt * sizeof(struct epoll_event)))
  9259. return -EFAULT;
  9260. kev = kmem_get(cnt * sizeof(struct epoll_event));
  9261. if (kev == RT_NULL)
  9262. {
  9263. return -ENOMEM;
  9264. }
  9265. if (sigs != RT_NULL)
  9266. {
  9267. if (!lwp_user_accessable((void *)sigs, sizeof(sigset_t)))
  9268. {
  9269. kmem_put(kev);
  9270. return -EFAULT;
  9271. }
  9272. ksigs = kmem_get(sizeof(sigset_t));
  9273. if (ksigs == RT_NULL)
  9274. {
  9275. kmem_put(kev);
  9276. return -ENOMEM;
  9277. }
  9278. if (lwp_get_from_user(ksigs, (void *)sigs, sizeof(sigset_t)) != sizeof(sigset_t))
  9279. {
  9280. kmem_put(kev);
  9281. kmem_put(ksigs);
  9282. return -EINVAL;
  9283. }
  9284. }
  9285. ret = epoll_pwait(fd, kev, cnt, to, ksigs);
  9286. if (ret > 0)
  9287. {
  9288. lwp_put_to_user((void *)ev, kev, ret * sizeof(struct epoll_event));
  9289. }
  9290. if (sigs != RT_NULL)
  9291. kmem_put(ksigs);
  9292. kmem_put(kev);
  9293. return (ret < 0 ? GET_ERRNO() : ret);
  9294. }
  9295. /**
  9296. * @brief Truncate a file to a specified length.
  9297. *
  9298. * This function resizes the file associated with the given file descriptor `fd` to the specified length.
  9299. * If the current size of the file is greater than the specified length, the file is truncated. If the file is smaller,
  9300. * it is extended, and the new space is initialized to zero.
  9301. *
  9302. * @param[in] fd The file descriptor referring to the file to truncate. This must be a valid open file descriptor.
  9303. * @param[in] length The new length of the file. The file will be truncated or extended to this size.
  9304. *
  9305. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9306. *
  9307. * @note The file descriptor `fd` must be opened with write permissions for this operation to succeed.
  9308. */
  9309. sysret_t sys_ftruncate(int fd, size_t length)
  9310. {
  9311. int ret;
  9312. ret = ftruncate(fd, length);
  9313. return (ret < 0 ? GET_ERRNO() : ret);
  9314. }
  9315. /**
  9316. * @brief Set file access and modification times.
  9317. *
  9318. * This function updates the access and modification times of a file or directory referenced by `__fd` or `__path`.
  9319. * If `__fd` is a valid file descriptor, the times will be applied to the file or directory it refers to.
  9320. * If `__fd` is `AT_FDCWD`, the times will be applied to the file or directory specified by `__path`.
  9321. * The `__times` argument consists of two `timespec` values: the first represents the access time,
  9322. * and the second represents the modification time. If `__times` is `NULL`, the current time is used.
  9323. *
  9324. * @param[in] __fd The file descriptor of the file or directory to modify, or `AT_FDCWD` to modify using `__path`.
  9325. * @param[in] __path The path to the file or directory to modify. Ignored if `__fd` is not `AT_FDCWD`.
  9326. * @param[in] __times An array of two `timespec` structures. The first element is the access time, and the second is the modification time.
  9327. * If `__times` is `NULL`, the current time is used for both access and modification times.
  9328. * @param[in] __flags Flags to modify behavior. Supported flags include:
  9329. * - `AT_SYMLINK_NOFOLLOW`: Do not follow symbolic links.
  9330. * - `AT_NO_AUTOMOUNT`: Do not trigger automounting.
  9331. *
  9332. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9333. *
  9334. * @note This function modifies both access and modification times of files, and may affect file system timestamps.
  9335. */
  9336. sysret_t sys_utimensat(int __fd, const char *__path, const struct timespec __times[2], int __flags)
  9337. {
  9338. #ifdef RT_USING_DFS_V2
  9339. #ifdef ARCH_MM_MMU
  9340. int ret = -1;
  9341. rt_size_t len = 0;
  9342. char *kpath = RT_NULL;
  9343. len = lwp_user_strlen(__path);
  9344. if (len <= 0)
  9345. {
  9346. return -EINVAL;
  9347. }
  9348. kpath = (char *)kmem_get(len + 1);
  9349. if (!kpath)
  9350. {
  9351. return -ENOMEM;
  9352. }
  9353. lwp_get_from_user(kpath, (void *)__path, len + 1);
  9354. ret = utimensat(__fd, kpath, __times, __flags);
  9355. kmem_put(kpath);
  9356. return ret;
  9357. #else
  9358. if (!lwp_user_accessable((void *)__path, 1))
  9359. {
  9360. return -EFAULT;
  9361. }
  9362. int ret = utimensat(__fd, __path, __times, __flags);
  9363. return ret;
  9364. #endif
  9365. #else
  9366. return -1;
  9367. #endif
  9368. }
  9369. /**
  9370. * @brief Change file permissions.
  9371. *
  9372. * This function changes the permissions of a file or directory specified by the `pathname`.
  9373. * The new permissions are specified using the `mode` argument, which is a bitwise OR of permission bits.
  9374. * The permissions apply to the file owner, group, and others, depending on the value of `mode`.
  9375. *
  9376. * @param[in] pathname The path to the file or directory whose permissions are to be changed.
  9377. * @param[in] mode The new permissions to set, represented as a bitwise OR of permission flags.
  9378. * For example, `S_IRUSR`, `S_IWUSR`, `S_IRGRP`, etc.
  9379. *
  9380. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9381. *
  9382. * @note If the file or directory is a symbolic link, this function will modify the permissions of the symbolic link itself,
  9383. * not the target file or directory.
  9384. */
  9385. sysret_t sys_chmod(const char *pathname, mode_t mode)
  9386. {
  9387. char *copy_file;
  9388. size_t len_file, copy_len_file;
  9389. struct dfs_attr attr = {0};
  9390. int ret = 0;
  9391. len_file = lwp_user_strlen(pathname);
  9392. if (len_file <= 0)
  9393. {
  9394. return -EFAULT;
  9395. }
  9396. copy_file = (char*)rt_malloc(len_file + 1);
  9397. if (!copy_file)
  9398. {
  9399. return -ENOMEM;
  9400. }
  9401. copy_len_file = lwp_get_from_user(copy_file, (void *)pathname, len_file);
  9402. attr.st_mode = mode;
  9403. attr.ia_valid |= ATTR_MODE_SET;
  9404. copy_file[copy_len_file] = '\0';
  9405. ret = dfs_file_setattr(copy_file, &attr);
  9406. rt_free(copy_file);
  9407. return (ret < 0 ? GET_ERRNO() : ret);
  9408. }
  9409. /**
  9410. * @brief Change the ownership of a file or directory.
  9411. *
  9412. * This function changes the owner and/or group of the file or directory specified by `pathname`.
  9413. * The `owner` and `group` parameters represent the new owner and group IDs, respectively. If either
  9414. * parameter is set to `-1`, that aspect (owner or group) will remain unchanged.
  9415. *
  9416. * @param[in] pathname The path to the file or directory whose ownership is to be changed.
  9417. * @param[in] owner The new owner ID. If set to `-1`, the owner's ID is not changed.
  9418. * @param[in] group The new group ID. If set to `-1`, the group's ID is not changed.
  9419. *
  9420. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9421. *
  9422. * @note The caller must have the appropriate permissions (i.e., be the superuser or the file owner)
  9423. * to change the ownership of a file or directory.
  9424. */
  9425. sysret_t sys_chown(const char *pathname, uid_t owner, gid_t group)
  9426. {
  9427. char *copy_file;
  9428. size_t len_file, copy_len_file;
  9429. struct dfs_attr attr = {0};
  9430. int ret = 0;
  9431. len_file = lwp_user_strlen(pathname);
  9432. if (len_file <= 0)
  9433. {
  9434. return -EFAULT;
  9435. }
  9436. copy_file = (char*)rt_malloc(len_file + 1);
  9437. if (!copy_file)
  9438. {
  9439. return -ENOMEM;
  9440. }
  9441. copy_len_file = lwp_get_from_user(copy_file, (void *)pathname, len_file);
  9442. if(owner >= 0)
  9443. {
  9444. attr.st_uid = owner;
  9445. attr.ia_valid |= ATTR_UID_SET;
  9446. }
  9447. if(group >= 0)
  9448. {
  9449. attr.st_gid = group;
  9450. attr.ia_valid |= ATTR_GID_SET;
  9451. }
  9452. copy_file[copy_len_file] = '\0';
  9453. ret = dfs_file_setattr(copy_file, &attr);
  9454. rt_free(copy_file);
  9455. return (ret < 0 ? GET_ERRNO() : ret);
  9456. }
  9457. #ifndef LWP_USING_RUNTIME
  9458. sysret_t lwp_teardown(struct rt_lwp *lwp, void (*cb)(void))
  9459. {
  9460. /* if no LWP_USING_RUNTIME configured */
  9461. return -ENOSYS;
  9462. }
  9463. #endif
  9464. /**
  9465. * @brief Reboot the system.
  9466. *
  9467. * This function initiates a system reboot with a specific reboot type and optional arguments.
  9468. * The reboot process is performed by passing `magic` and `magic2` as security keys to validate the
  9469. * reboot request, along with the desired reboot type (`type`) and optional argument (`arg`) that
  9470. * may contain additional parameters depending on the reboot type.
  9471. *
  9472. * @param[in] magic A magic number for security validation, typically used to verify that the caller
  9473. * has sufficient privileges (e.g., root).
  9474. * @param[in] magic2 A second magic number for additional security verification, used in combination
  9475. * with `magic` to validate the reboot request.
  9476. * @param[in] type The type of reboot to perform, such as `RB_AUTOBOOT`, `RB_HALT`, `RB_RESTART`,
  9477. * etc. The exact values may depend on the platform.
  9478. * @param[in] arg An optional argument for the reboot process. This can provide additional data,
  9479. * such as a specific shutdown procedure, depending on the type of reboot.
  9480. *
  9481. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9482. *
  9483. * @note This operation is typically available to the system administrator (root) and should be used
  9484. * with caution as it can cause the system to restart or shut down.
  9485. */
  9486. sysret_t sys_reboot(int magic, int magic2, int type, void *arg)
  9487. {
  9488. sysret_t rc;
  9489. switch (type)
  9490. {
  9491. /* Hardware reset */
  9492. case RB_AUTOBOOT:
  9493. rc = lwp_teardown(lwp_self(), rt_hw_cpu_reset);
  9494. break;
  9495. /* Stop system and switch power off */
  9496. case RB_POWER_OFF:
  9497. rc = lwp_teardown(lwp_self(), rt_hw_cpu_shutdown);
  9498. break;
  9499. default:
  9500. rc = -ENOSYS;
  9501. }
  9502. return rc;
  9503. }
  9504. /**
  9505. * @brief Read data from a file descriptor at a specific offset.
  9506. *
  9507. * This function reads data from a file descriptor `fd` into the buffer `buf`, starting from the
  9508. * specified byte `offset`. Unlike a regular `read` call, `sys_pread64` allows the file pointer to
  9509. * remain unchanged after the read, as the operation directly accesses the file at the provided
  9510. * offset.
  9511. *
  9512. * @param[in] fd The file descriptor from which to read. It must be a valid open file descriptor.
  9513. * @param[out] buf A pointer to the buffer where the read data will be stored.
  9514. * @param[in] size The number of bytes to read from the file.
  9515. * @param[in] offset The offset in bytes from the beginning of the file to start reading from.
  9516. *
  9517. * @return ssize_t On success, returns the number of bytes read (which may be less than `size` if
  9518. * the end of the file is reached). On error, returns a negative error code.
  9519. *
  9520. * @note This function is particularly useful for random access to files, allowing for efficient
  9521. * reads from arbitrary positions without affecting the current file pointer.
  9522. */
  9523. ssize_t sys_pread64(int fd, void *buf, int size, size_t offset)
  9524. #ifdef RT_USING_DFS_V2
  9525. {
  9526. ssize_t pread(int fd, void *buf, size_t len, size_t offset);
  9527. #ifdef ARCH_MM_MMU
  9528. ssize_t ret = -1;
  9529. void *kmem = RT_NULL;
  9530. if (!size)
  9531. {
  9532. return -EINVAL;
  9533. }
  9534. if (!lwp_user_accessable((void *)buf, size))
  9535. {
  9536. return -EFAULT;
  9537. }
  9538. kmem = kmem_get(size);
  9539. if (!kmem)
  9540. {
  9541. return -ENOMEM;
  9542. }
  9543. ret = pread(fd, kmem, size, offset);
  9544. if (ret > 0)
  9545. {
  9546. lwp_put_to_user(buf, kmem, ret);
  9547. }
  9548. if (ret < 0)
  9549. {
  9550. ret = GET_ERRNO();
  9551. }
  9552. kmem_put(kmem);
  9553. return ret;
  9554. #else
  9555. if (!lwp_user_accessable((void *)buf, size))
  9556. {
  9557. return -EFAULT;
  9558. }
  9559. ssize_t ret = pread(fd, kmem, size, offset);
  9560. return (ret < 0 ? GET_ERRNO() : ret);
  9561. #endif
  9562. }
  9563. #else
  9564. {
  9565. ssize_t ret = -ENOSYS;
  9566. return (ret < 0 ? GET_ERRNO() : ret);
  9567. }
  9568. #endif
  9569. /**
  9570. * @brief Write data to a file descriptor at a specific offset.
  9571. *
  9572. * This function writes data from the buffer `buf` to the file descriptor `fd`, starting at the
  9573. * specified byte `offset`. Unlike a regular `write` call, `sys_pwrite64` allows the file pointer to
  9574. * remain unchanged after the write, as the operation directly writes the data to the file at the
  9575. * provided offset.
  9576. *
  9577. * @param[in] fd The file descriptor to which the data will be written. It must be a valid open
  9578. * file descriptor.
  9579. * @param[in] buf A pointer to the buffer containing the data to be written.
  9580. * @param[in] size The number of bytes to write to the file.
  9581. * @param[in] offset The offset in bytes from the beginning of the file to start writing to.
  9582. *
  9583. * @return ssize_t On success, returns the number of bytes written (which may be less than `size` if
  9584. * the write operation is partial). On error, returns a negative error code.
  9585. *
  9586. * @note This function is particularly useful for random access to files, allowing for efficient
  9587. * writes to arbitrary positions without affecting the current file pointer.
  9588. */
  9589. ssize_t sys_pwrite64(int fd, void *buf, int size, size_t offset)
  9590. #ifdef RT_USING_DFS_V2
  9591. {
  9592. ssize_t pwrite(int fd, const void *buf, size_t len, size_t offset);
  9593. #ifdef ARCH_MM_MMU
  9594. ssize_t ret = -1;
  9595. void *kmem = RT_NULL;
  9596. if (!size)
  9597. {
  9598. return -EINVAL;
  9599. }
  9600. if (!lwp_user_accessable((void *)buf, size))
  9601. {
  9602. return -EFAULT;
  9603. }
  9604. kmem = kmem_get(size);
  9605. if (!kmem)
  9606. {
  9607. return -ENOMEM;
  9608. }
  9609. lwp_get_from_user(kmem, (void *)buf, size);
  9610. ret = pwrite(fd, kmem, size, offset);
  9611. if (ret < 0)
  9612. {
  9613. ret = GET_ERRNO();
  9614. }
  9615. kmem_put(kmem);
  9616. return ret;
  9617. #else
  9618. if (!lwp_user_accessable((void *)buf, size))
  9619. {
  9620. return -EFAULT;
  9621. }
  9622. ssize_t ret = pwrite(fd, kmem, size, offset);
  9623. return (ret < 0 ? GET_ERRNO() : ret);
  9624. #endif
  9625. }
  9626. #else
  9627. {
  9628. ssize_t ret = -ENOSYS;
  9629. return (ret < 0 ? GET_ERRNO() : ret);
  9630. }
  9631. #endif
  9632. /**
  9633. * @brief Create a timer file descriptor.
  9634. *
  9635. * This function creates a timer that can be used to notify a process after a specified
  9636. * amount of time has passed. The timer is represented by a file descriptor, which can be
  9637. * used with functions such as `read` and `poll` to monitor and retrieve notifications
  9638. * about timer expirations.
  9639. *
  9640. * @param[in] clockid The clock to use for the timer. Possible values include:
  9641. * - `CLOCK_REALTIME`: The system's real-time clock.
  9642. * - `CLOCK_MONOTONIC`: A clock that cannot be set and is not affected by
  9643. * changes in the system time.
  9644. * @param[in] flags Flags that modify the behavior of the timer. The commonly used values are:
  9645. * - `TFD_CLOEXEC`: Set the close-on-exec flag for the file descriptor.
  9646. * - `TFD_NONBLOCK`: Set the non-blocking flag for the file descriptor.
  9647. *
  9648. * @return sysret_t On success, returns a non-negative file descriptor that refers to the timer.
  9649. * On failure, returns a negative error code.
  9650. *
  9651. * @note The timer created by this function can be used to create periodic or one-shot timers.
  9652. * The timer can be configured using `timerfd_settime` and notifications can be retrieved
  9653. * by reading from the returned file descriptor.
  9654. */
  9655. sysret_t sys_timerfd_create(int clockid, int flags)
  9656. {
  9657. int ret;
  9658. ret = timerfd_create(clockid, flags);
  9659. return (ret < 0 ? GET_ERRNO() : ret);
  9660. }
  9661. /**
  9662. * @brief Set or modify the expiration time for a timer.
  9663. *
  9664. * This function is used to arm or re-arm a timer associated with a file descriptor created
  9665. * by `sys_timerfd_create`. It allows setting a new expiration time and can also return
  9666. * the previous timer configuration.
  9667. *
  9668. * @param[in] fd The file descriptor referring to the timer, which was created using
  9669. * `sys_timerfd_create`.
  9670. * @param[in] flags Flags that modify the behavior of the timer. The commonly used values are:
  9671. * - `TFD_TIMER_ABSTIME`: If set, the `new` expiration time is an absolute time.
  9672. * - `TFD_TIMER_RELATIVE`: The default behavior, where `new` expiration time is
  9673. * a relative time from now.
  9674. * @param[in] new A pointer to a `struct itimerspec` specifying the new expiration time.
  9675. * It contains two fields:
  9676. * - `it_value`: The initial expiration time of the timer.
  9677. * - `it_interval`: The period of periodic timers (if zero, the timer is one-shot).
  9678. * @param[out] old A pointer to a `struct itimerspec` where the previous timer configuration
  9679. * will be stored. This can be `NULL` if the previous configuration is not needed.
  9680. *
  9681. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9682. *
  9683. * @note This function allows for both one-shot and periodic timers. If the timer is periodic,
  9684. * it will continue triggering at intervals specified in `it_interval` until canceled or modified.
  9685. * When a timer expires, the associated file descriptor becomes readable, and the application
  9686. * can retrieve the expiration event by reading from the file descriptor.
  9687. */
  9688. sysret_t sys_timerfd_settime(int fd, int flags, const struct itimerspec *new, struct itimerspec *old)
  9689. {
  9690. int ret = -1;
  9691. struct itimerspec *knew = RT_NULL;
  9692. struct itimerspec *kold = RT_NULL;
  9693. if (new == RT_NULL)
  9694. return -EINVAL;
  9695. if (!lwp_user_accessable((void *)new, sizeof(struct itimerspec)))
  9696. {
  9697. return -EFAULT;
  9698. }
  9699. knew = kmem_get(sizeof(struct itimerspec));
  9700. if (knew)
  9701. {
  9702. lwp_get_from_user(knew, (void*)new, sizeof(struct itimerspec));
  9703. if (old)
  9704. {
  9705. if (!lwp_user_accessable((void *)old, sizeof(struct itimerspec)))
  9706. {
  9707. kmem_put(knew);
  9708. return -EFAULT;
  9709. }
  9710. kold = kmem_get(sizeof(struct itimerspec));
  9711. if (kold == RT_NULL)
  9712. {
  9713. kmem_put(knew);
  9714. return -ENOMEM;
  9715. }
  9716. }
  9717. ret = timerfd_settime(fd, flags, knew, kold);
  9718. if (old)
  9719. {
  9720. lwp_put_to_user(old, kold, sizeof(*kold));
  9721. kmem_put(kold);
  9722. }
  9723. kmem_put(knew);
  9724. }
  9725. return (ret < 0 ? GET_ERRNO() : ret);
  9726. }
  9727. /**
  9728. * @brief Retrieve the current configuration of a timer.
  9729. *
  9730. * This function is used to obtain the current expiration time and interval of a timer associated
  9731. * with a file descriptor created by `sys_timerfd_create`. It allows querying the current state
  9732. * of the timer, including the time remaining until the next expiration and the period (for periodic timers).
  9733. *
  9734. * @param[in] fd The file descriptor referring to the timer, which was created using
  9735. * `sys_timerfd_create`.
  9736. * @param[out] cur A pointer to a `struct itimerspec` where the current timer configuration will
  9737. * be stored. This structure contains:
  9738. * - `it_value`: The time remaining until the timer expires.
  9739. * - `it_interval`: The period for periodic timers (zero for one-shot timers).
  9740. *
  9741. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9742. *
  9743. * @note The timer's `it_value` field will contain the time remaining until the next expiration.
  9744. * If the timer is periodic, the `it_interval` field will contain the period for the next expiration.
  9745. * If the timer has expired and there is no further interval (for one-shot timers), `it_value` will
  9746. * contain a value of `0`.
  9747. */
  9748. sysret_t sys_timerfd_gettime(int fd, struct itimerspec *cur)
  9749. {
  9750. int ret = -1;
  9751. struct itimerspec *kcur;
  9752. if (cur == RT_NULL)
  9753. return -EINVAL;
  9754. if (!lwp_user_accessable((void *)cur, sizeof(struct itimerspec)))
  9755. {
  9756. return -EFAULT;
  9757. }
  9758. kcur = kmem_get(sizeof(struct itimerspec));
  9759. if (kcur)
  9760. {
  9761. lwp_get_from_user(kcur, cur, sizeof(struct itimerspec));
  9762. ret = timerfd_gettime(fd, kcur);
  9763. lwp_put_to_user(cur, kcur, sizeof(struct itimerspec));
  9764. kmem_put(kcur);
  9765. }
  9766. return (ret < 0 ? GET_ERRNO() : ret);
  9767. }
  9768. /**
  9769. * @brief Create a file descriptor for receiving signals.
  9770. *
  9771. * This function creates a file descriptor that can be used to receive signals, similar to how a
  9772. * regular file descriptor is used. The signals specified in the provided signal mask are blocked
  9773. * for the calling thread, and any matching signals will be reported through the file descriptor.
  9774. * This allows signals to be handled in a more controlled, non-interrupt-driven way by using
  9775. * standard I/O operations (e.g., `read()` or `select()`) on the file descriptor.
  9776. *
  9777. * @param[in] fd A file descriptor associated with the process, typically obtained from
  9778. * `sys_signalfd()` or a similar mechanism. If `fd` is `-1`, a new file descriptor
  9779. * will be created.
  9780. * @param[in] mask A pointer to the signal mask (`sigset_t`) that specifies the signals that
  9781. * should be received by the file descriptor. Only signals in the mask will be
  9782. * reported.
  9783. * @param[in] flags Additional flags to control the behavior of the signalfd. Common flags
  9784. * include `O_NONBLOCK` for non-blocking operation.
  9785. *
  9786. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9787. *
  9788. * @note The caller must call `read()` on the resulting file descriptor to actually receive signals.
  9789. * Each read returns a `struct signalfd_siginfo` containing the signal number, and additional
  9790. * information, such as the signal source and sender.
  9791. *
  9792. * @see sys_read(), sigprocmask(), sigaction(), sigsuspend().
  9793. */
  9794. sysret_t sys_signalfd(int fd, const sigset_t *mask, int flags)
  9795. {
  9796. int ret = 0;
  9797. sigset_t *kmask = RT_NULL;
  9798. #ifdef RT_USING_MUSLLIBC
  9799. if (mask == RT_NULL)
  9800. return -EINVAL;
  9801. if (!lwp_user_accessable((void *)mask, sizeof(struct itimerspec)))
  9802. {
  9803. return -EFAULT;
  9804. }
  9805. kmask = kmem_get(sizeof(struct itimerspec));
  9806. if (kmask)
  9807. {
  9808. if (lwp_get_from_user(kmask, (void *)mask, sizeof(struct itimerspec)) != sizeof(struct itimerspec))
  9809. {
  9810. kmem_put(kmask);
  9811. return -EFAULT;
  9812. }
  9813. ret = signalfd(fd, mask, flags);
  9814. kmem_put(kmask);
  9815. }
  9816. #endif
  9817. return (ret < 0 ? GET_ERRNO() : ret);
  9818. }
  9819. sysret_t sys_memfd_create()
  9820. {
  9821. return 0;
  9822. }
  9823. /**
  9824. * @brief Set the value of an interval timer.
  9825. *
  9826. * This function is used to set the value of a specified timer that generates periodic signals
  9827. * after the specified intervals. The timer can be configured to generate a signal when it expires,
  9828. * and it can be used for tasks like scheduling periodic events.
  9829. *
  9830. * @param[in] which Specifies which timer to set. Possible values include:
  9831. * - `ITIMER_REAL`: Timer that decrements in real time and sends `SIGALRM` when expired.
  9832. * - `ITIMER_VIRTUAL`: Timer that decrements only while the process is executing.
  9833. * - `ITIMER_PROF`: Timer that decrements while the process is executing or when it is
  9834. * executing in the kernel.
  9835. * @param[in] new A pointer to a `struct itimerspec` containing the new value for the timer.
  9836. * The `itimerspec` structure contains two `timespec` fields: `it_value` for the initial
  9837. * expiration time and `it_interval` for the interval between successive expirations.
  9838. * @param[out] old A pointer to a `struct itimerspec` where the previous timer values (before the
  9839. * timer is set) will be stored.
  9840. *
  9841. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9842. *
  9843. * @note If the specified timer is already active, it will be updated with the new values. The timer
  9844. * will start at the `it_value` time and will repeat at the interval specified in `it_interval`.
  9845. * If `it_interval` is set to `0`, the timer will not repeat and will only expire once.
  9846. *
  9847. * @see sys_getitimer(), sigaction(), alarm(), setitimer().
  9848. */
  9849. sysret_t sys_setitimer(int which, const struct itimerspec *restrict new, struct itimerspec *restrict old)
  9850. {
  9851. sysret_t rc = 0;
  9852. rt_lwp_t lwp = lwp_self();
  9853. struct itimerspec new_value_k;
  9854. struct itimerspec old_value_k;
  9855. if (lwp_get_from_user(&new_value_k, (void *)new, sizeof(*new)) != sizeof(*new))
  9856. {
  9857. return -EFAULT;
  9858. }
  9859. rc = lwp_signal_setitimer(lwp, which, &new_value_k, &old_value_k);
  9860. if (old && lwp_put_to_user(old, (void *)&old_value_k, sizeof old_value_k) != sizeof old_value_k)
  9861. return -EFAULT;
  9862. return rc;
  9863. }
  9864. /**
  9865. * @brief Set the robust list for the current thread.
  9866. *
  9867. * The `sys_set_robust_list` function sets the robust list for the calling thread. The robust list is
  9868. * a list of `struct robust_list_head` elements that contain information about mutexes or other
  9869. * resources that need to be cleaned up if the thread dies unexpectedly.
  9870. *
  9871. * This function is typically used for thread safety in multi-threaded programs, where robust mutexes
  9872. * can be used to avoid leaving resources in an inconsistent state when a thread is terminated
  9873. * without properly unlocking locks or releasing resources.
  9874. *
  9875. * @param[in] head A pointer to the robust list to be set. This list contains `struct robust_list_head`
  9876. * entries which are used by the kernel to maintain information about robust mutexes.
  9877. * @param[in] len The length of the robust list (the number of entries in the list). This should correspond
  9878. * to the size of the list in memory, generally expressed in bytes.
  9879. *
  9880. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9881. *
  9882. * @note The robust list should be set during the initialization of a thread or task, and it may be
  9883. * used by the kernel to track which mutexes need to be cleaned up in case of failure.
  9884. * The list may be manipulated using related functions such as `sys_get_robust_list`.
  9885. *
  9886. * @see sys_get_robust_list(), robust_mutex, pthread_mutex, set_robust_list.
  9887. */
  9888. sysret_t sys_set_robust_list(struct robust_list_head *head, size_t len)
  9889. {
  9890. if (len != sizeof(*head))
  9891. return -EINVAL;
  9892. rt_thread_self()->robust_list = head;
  9893. return 0;
  9894. }
  9895. /**
  9896. * @brief Get the robust list for the specified thread.
  9897. *
  9898. * The `sys_get_robust_list` function retrieves the robust list associated with the given thread.
  9899. * The robust list contains `struct robust_list_head` entries used by the kernel to manage
  9900. * robust mutexes and other resources that need to be cleaned up if the thread terminates unexpectedly.
  9901. *
  9902. * This function is primarily used to retrieve the robust list for a specific thread, so that
  9903. * the caller can inspect or manipulate the robust list to handle clean-up operations in case
  9904. * the thread exits while holding resources.
  9905. *
  9906. * @param[in] tid The thread ID of the thread whose robust list is to be retrieved.
  9907. *
  9908. * @param[out] head_ptr A pointer to a pointer to `struct robust_list_head`. On success,
  9909. * this will point to the robust list for the specified thread.
  9910. *
  9911. * @param[out] len_ptr A pointer to a variable that will hold the length of the robust list
  9912. * (i.e., the number of entries in the list).
  9913. *
  9914. * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
  9915. *
  9916. * @note The robust list is used to track mutexes and other resources that need to be cleaned up
  9917. * if a thread terminates without releasing the resources properly. It is typically used by
  9918. * the kernel for thread safety and resource management in multi-threaded programs.
  9919. *
  9920. * @see sys_set_robust_list(), robust_mutex, pthread_mutex, get_robust_list.
  9921. */
  9922. sysret_t sys_get_robust_list(int tid, struct robust_list_head **head_ptr, size_t *len_ptr)
  9923. {
  9924. rt_thread_t thread;
  9925. size_t len;
  9926. struct robust_list_head *head;
  9927. if (!lwp_user_accessable((void *)head_ptr, sizeof(struct robust_list_head *)))
  9928. {
  9929. return -EFAULT;
  9930. }
  9931. if (!lwp_user_accessable((void *)len_ptr, sizeof(size_t)))
  9932. {
  9933. return -EFAULT;
  9934. }
  9935. if (tid == 0)
  9936. {
  9937. thread = rt_thread_self();
  9938. head = thread->robust_list;
  9939. }
  9940. else
  9941. {
  9942. thread = lwp_tid_get_thread_and_inc_ref(tid);
  9943. if (thread)
  9944. {
  9945. head = thread->robust_list;
  9946. lwp_tid_dec_ref(thread);
  9947. }
  9948. else
  9949. {
  9950. return -ESRCH;
  9951. }
  9952. }
  9953. len = sizeof(*(head));
  9954. if (!lwp_put_to_user(len_ptr, &len, sizeof(size_t)))
  9955. return -EFAULT;
  9956. if (!lwp_put_to_user(head_ptr, &head, sizeof(struct robust_list_head *)))
  9957. return -EFAULT;
  9958. return 0;
  9959. }
  9960. const static struct rt_syscall_def func_table[] =
  9961. {
  9962. SYSCALL_SIGN(sys_exit), /* 01 */
  9963. SYSCALL_SIGN(sys_read),
  9964. SYSCALL_SIGN(sys_write),
  9965. SYSCALL_SIGN(sys_lseek),
  9966. SYSCALL_SIGN(sys_open), /* 05 */
  9967. SYSCALL_SIGN(sys_close),
  9968. SYSCALL_SIGN(sys_ioctl),
  9969. SYSCALL_SIGN(sys_fstat),
  9970. SYSCALL_SIGN(sys_poll),
  9971. SYSCALL_SIGN(sys_nanosleep), /* 10 */
  9972. SYSCALL_SIGN(sys_gettimeofday),
  9973. SYSCALL_SIGN(sys_settimeofday),
  9974. SYSCALL_SIGN(sys_exec),
  9975. SYSCALL_SIGN(sys_kill),
  9976. SYSCALL_SIGN(sys_getpid), /* 15 */
  9977. SYSCALL_SIGN(sys_getpriority),
  9978. SYSCALL_SIGN(sys_setpriority),
  9979. SYSCALL_SIGN(sys_sem_create),
  9980. SYSCALL_SIGN(sys_sem_delete),
  9981. SYSCALL_SIGN(sys_sem_take), /* 20 */
  9982. SYSCALL_SIGN(sys_sem_release),
  9983. SYSCALL_SIGN(sys_mutex_create),
  9984. SYSCALL_SIGN(sys_mutex_delete),
  9985. SYSCALL_SIGN(sys_mutex_take),
  9986. SYSCALL_SIGN(sys_mutex_release), /* 25 */
  9987. SYSCALL_SIGN(sys_event_create),
  9988. SYSCALL_SIGN(sys_event_delete),
  9989. SYSCALL_SIGN(sys_event_send),
  9990. SYSCALL_SIGN(sys_event_recv),
  9991. SYSCALL_SIGN(sys_mb_create), /* 30 */
  9992. SYSCALL_SIGN(sys_mb_delete),
  9993. SYSCALL_SIGN(sys_mb_send),
  9994. SYSCALL_SIGN(sys_mb_send_wait),
  9995. SYSCALL_SIGN(sys_mb_recv),
  9996. SYSCALL_SIGN(sys_mq_create), /* 35 */
  9997. SYSCALL_SIGN(sys_mq_delete),
  9998. SYSCALL_SIGN(sys_mq_send),
  9999. SYSCALL_SIGN(sys_mq_urgent),
  10000. SYSCALL_SIGN(sys_mq_recv),
  10001. SYSCALL_SIGN(sys_thread_create), /* 40 */
  10002. SYSCALL_SIGN(sys_thread_delete),
  10003. SYSCALL_SIGN(sys_thread_startup),
  10004. SYSCALL_SIGN(sys_thread_self),
  10005. SYSCALL_SIGN(sys_channel_open),
  10006. SYSCALL_SIGN(sys_channel_close), /* 45 */
  10007. SYSCALL_SIGN(sys_channel_send),
  10008. SYSCALL_SIGN(sys_channel_send_recv_timeout),
  10009. SYSCALL_SIGN(sys_channel_reply),
  10010. SYSCALL_SIGN(sys_channel_recv_timeout),
  10011. SYSCALL_SIGN(sys_enter_critical), /* 50 */
  10012. SYSCALL_SIGN(sys_exit_critical),
  10013. SYSCALL_USPACE(SYSCALL_SIGN(sys_brk)),
  10014. SYSCALL_USPACE(SYSCALL_SIGN(sys_mmap2)),
  10015. SYSCALL_USPACE(SYSCALL_SIGN(sys_munmap)),
  10016. #ifdef ARCH_MM_MMU
  10017. SYSCALL_USPACE(SYSCALL_SIGN(sys_shmget)), /* 55 */
  10018. SYSCALL_USPACE(SYSCALL_SIGN(sys_shmrm)),
  10019. SYSCALL_USPACE(SYSCALL_SIGN(sys_shmat)),
  10020. SYSCALL_USPACE(SYSCALL_SIGN(sys_shmdt)),
  10021. #else
  10022. #ifdef RT_LWP_USING_SHM
  10023. SYSCALL_SIGN(sys_shm_alloc), /* 55 */
  10024. SYSCALL_SIGN(sys_shm_free),
  10025. SYSCALL_SIGN(sys_shm_retain),
  10026. SYSCALL_SIGN(sys_notimpl),
  10027. #else
  10028. SYSCALL_SIGN(sys_notimpl), /* 55 */
  10029. SYSCALL_SIGN(sys_notimpl),
  10030. SYSCALL_SIGN(sys_notimpl),
  10031. SYSCALL_SIGN(sys_notimpl),
  10032. #endif /* RT_LWP_USING_SHM */
  10033. #endif /* ARCH_MM_MMU */
  10034. SYSCALL_SIGN(sys_device_init),
  10035. SYSCALL_SIGN(sys_device_register), /* 60 */
  10036. SYSCALL_SIGN(sys_device_control),
  10037. SYSCALL_SIGN(sys_device_find),
  10038. SYSCALL_SIGN(sys_device_open),
  10039. SYSCALL_SIGN(sys_device_close),
  10040. SYSCALL_SIGN(sys_device_read), /* 65 */
  10041. SYSCALL_SIGN(sys_device_write),
  10042. SYSCALL_SIGN(sys_stat),
  10043. SYSCALL_SIGN(sys_thread_find),
  10044. SYSCALL_NET(SYSCALL_SIGN(sys_accept)),
  10045. SYSCALL_NET(SYSCALL_SIGN(sys_bind)), /* 70 */
  10046. SYSCALL_NET(SYSCALL_SIGN(sys_shutdown)),
  10047. SYSCALL_NET(SYSCALL_SIGN(sys_getpeername)),
  10048. SYSCALL_NET(SYSCALL_SIGN(sys_getsockname)),
  10049. SYSCALL_NET(SYSCALL_SIGN(sys_getsockopt)),
  10050. SYSCALL_NET(SYSCALL_SIGN(sys_setsockopt)), /* 75 */
  10051. SYSCALL_NET(SYSCALL_SIGN(sys_connect)),
  10052. SYSCALL_NET(SYSCALL_SIGN(sys_listen)),
  10053. SYSCALL_NET(SYSCALL_SIGN(sys_recv)),
  10054. SYSCALL_NET(SYSCALL_SIGN(sys_recvfrom)),
  10055. SYSCALL_NET(SYSCALL_SIGN(sys_send)), /* 80 */
  10056. SYSCALL_NET(SYSCALL_SIGN(sys_sendto)),
  10057. SYSCALL_NET(SYSCALL_SIGN(sys_socket)),
  10058. SYSCALL_NET(SYSCALL_SIGN(sys_closesocket)),
  10059. SYSCALL_NET(SYSCALL_SIGN(sys_getaddrinfo)),
  10060. SYSCALL_NET(SYSCALL_SIGN(sys_gethostbyname2_r)), /* 85 */
  10061. SYSCALL_NET(SYSCALL_SIGN(sys_sendmsg)),
  10062. SYSCALL_NET(SYSCALL_SIGN(sys_recvmsg)),
  10063. SYSCALL_SIGN(sys_notimpl), /* network */
  10064. SYSCALL_SIGN(sys_notimpl), /* network */
  10065. SYSCALL_SIGN(sys_notimpl), /* network, 90 */
  10066. SYSCALL_SIGN(sys_notimpl), /* network */
  10067. SYSCALL_SIGN(sys_notimpl), /* network */
  10068. SYSCALL_SIGN(sys_notimpl), /* network */
  10069. #ifdef RT_USING_DFS
  10070. SYSCALL_SIGN(sys_select),
  10071. #else
  10072. SYSCALL_SIGN(sys_notimpl),
  10073. #endif
  10074. SYSCALL_SIGN(sys_notimpl), /* SYSCALL_SIGN(sys_hw_interrupt_disable), 95 */
  10075. SYSCALL_SIGN(sys_notimpl), /* SYSCALL_SIGN(sys_hw_interrupt_enable) */
  10076. SYSCALL_SIGN(sys_tick_get),
  10077. SYSCALL_SIGN(sys_exit_group),
  10078. SYSCALL_SIGN(sys_notimpl), /* rt_delayed_work_init */
  10079. SYSCALL_SIGN(sys_notimpl), /* rt_work_submit, 100 */
  10080. SYSCALL_SIGN(sys_notimpl), /* rt_wqueue_wakeup */
  10081. SYSCALL_SIGN(sys_thread_mdelay),
  10082. SYSCALL_SIGN(sys_sigaction),
  10083. SYSCALL_SIGN(sys_sigprocmask),
  10084. SYSCALL_SIGN(sys_tkill), /* 105 */
  10085. SYSCALL_SIGN(sys_thread_sigprocmask),
  10086. #ifdef ARCH_MM_MMU
  10087. SYSCALL_SIGN(sys_cacheflush),
  10088. SYSCALL_SIGN(sys_notimpl),
  10089. SYSCALL_SIGN(sys_notimpl),
  10090. #else
  10091. SYSCALL_SIGN(sys_notimpl),
  10092. SYSCALL_SIGN(sys_lwp_sighandler_set),
  10093. SYSCALL_SIGN(sys_thread_sighandler_set),
  10094. #endif
  10095. SYSCALL_SIGN(sys_waitpid), /* 110 */
  10096. SYSCALL_SIGN(sys_rt_timer_create),
  10097. SYSCALL_SIGN(sys_rt_timer_delete),
  10098. SYSCALL_SIGN(sys_rt_timer_start),
  10099. SYSCALL_SIGN(sys_rt_timer_stop),
  10100. SYSCALL_SIGN(sys_rt_timer_control), /* 115 */
  10101. SYSCALL_SIGN(sys_getcwd),
  10102. SYSCALL_SIGN(sys_chdir),
  10103. SYSCALL_SIGN(sys_unlink),
  10104. SYSCALL_SIGN(sys_mkdir),
  10105. SYSCALL_SIGN(sys_rmdir), /* 120 */
  10106. SYSCALL_SIGN(sys_getdents),
  10107. SYSCALL_SIGN(sys_get_errno),
  10108. #ifdef ARCH_MM_MMU
  10109. SYSCALL_SIGN(sys_set_thread_area),
  10110. SYSCALL_SIGN(sys_set_tid_address),
  10111. #else
  10112. SYSCALL_SIGN(sys_notimpl),
  10113. SYSCALL_SIGN(sys_notimpl),
  10114. #endif
  10115. SYSCALL_SIGN(sys_access), /* 125 */
  10116. SYSCALL_SIGN(sys_pipe),
  10117. SYSCALL_SIGN(sys_clock_settime),
  10118. SYSCALL_SIGN(sys_clock_gettime),
  10119. SYSCALL_SIGN(sys_clock_getres),
  10120. SYSCALL_USPACE(SYSCALL_SIGN(sys_clone)), /* 130 */
  10121. SYSCALL_USPACE(SYSCALL_SIGN(sys_futex)),
  10122. SYSCALL_SIGN(sys_notimpl), /* discarded: sys_pmutex */
  10123. SYSCALL_SIGN(sys_dup),
  10124. SYSCALL_SIGN(sys_dup2),
  10125. SYSCALL_SIGN(sys_rename), /* 135 */
  10126. SYSCALL_USPACE(SYSCALL_SIGN(sys_fork)),
  10127. SYSCALL_USPACE(SYSCALL_SIGN(sys_execve)),
  10128. SYSCALL_USPACE(SYSCALL_SIGN(sys_vfork)),
  10129. SYSCALL_SIGN(sys_gettid),
  10130. SYSCALL_SIGN(sys_prlimit64), /* 140 */
  10131. SYSCALL_SIGN(sys_getrlimit),
  10132. SYSCALL_SIGN(sys_setrlimit),
  10133. SYSCALL_SIGN(sys_setsid),
  10134. SYSCALL_SIGN(sys_getrandom),
  10135. SYSCALL_SIGN(sys_readlink), /* 145 */
  10136. SYSCALL_USPACE(SYSCALL_SIGN(sys_mremap)),
  10137. SYSCALL_USPACE(SYSCALL_SIGN(sys_madvise)),
  10138. SYSCALL_SIGN(sys_sched_setparam),
  10139. SYSCALL_SIGN(sys_sched_getparam),
  10140. SYSCALL_SIGN(sys_sched_get_priority_max), /* 150 */
  10141. SYSCALL_SIGN(sys_sched_get_priority_min),
  10142. SYSCALL_SIGN(sys_sched_setscheduler),
  10143. SYSCALL_SIGN(sys_sched_getscheduler),
  10144. SYSCALL_SIGN(sys_sched_setaffinity),
  10145. SYSCALL_SIGN(sys_fsync), /* 155 */
  10146. SYSCALL_SIGN(sys_clock_nanosleep),
  10147. SYSCALL_SIGN(sys_timer_create),
  10148. SYSCALL_SIGN(sys_timer_delete),
  10149. SYSCALL_SIGN(sys_timer_settime),
  10150. SYSCALL_SIGN(sys_timer_gettime), /* 160 */
  10151. SYSCALL_SIGN(sys_timer_getoverrun),
  10152. SYSCALL_SIGN(sys_mq_open),
  10153. SYSCALL_SIGN(sys_mq_unlink),
  10154. SYSCALL_SIGN(sys_mq_timedsend),
  10155. SYSCALL_SIGN(sys_mq_timedreceive), /* 165 */
  10156. SYSCALL_SIGN(sys_mq_notify),
  10157. SYSCALL_SIGN(sys_mq_getsetattr),
  10158. SYSCALL_SIGN(sys_mq_close),
  10159. SYSCALL_SIGN(sys_lstat),
  10160. SYSCALL_SIGN(sys_uname), /* 170 */
  10161. SYSCALL_SIGN(sys_statfs),
  10162. SYSCALL_SIGN(sys_statfs64),
  10163. SYSCALL_SIGN(sys_fstatfs),
  10164. SYSCALL_SIGN(sys_fstatfs64),
  10165. SYSCALL_SIGN(sys_openat), /* 175 */
  10166. SYSCALL_SIGN(sys_mount),
  10167. SYSCALL_SIGN(sys_umount2),
  10168. SYSCALL_SIGN(sys_link),
  10169. SYSCALL_SIGN(sys_symlink),
  10170. SYSCALL_SIGN(sys_sched_getaffinity), /* 180 */
  10171. SYSCALL_SIGN(sys_sysinfo),
  10172. SYSCALL_SIGN(sys_chmod),
  10173. SYSCALL_SIGN(sys_reboot),
  10174. SYSCALL_SIGN(sys_sched_yield),
  10175. SYSCALL_SIGN(sys_pread64), /* 185 */
  10176. SYSCALL_SIGN(sys_pwrite64),
  10177. SYSCALL_SIGN(sys_sigpending),
  10178. SYSCALL_SIGN(sys_sigtimedwait),
  10179. SYSCALL_SIGN(sys_notimpl),
  10180. SYSCALL_SIGN(sys_notimpl), /* 190 */
  10181. SYSCALL_SIGN(sys_eventfd2),
  10182. SYSCALL_SIGN(sys_epoll_create1),
  10183. SYSCALL_SIGN(sys_epoll_ctl),
  10184. SYSCALL_SIGN(sys_epoll_pwait),
  10185. SYSCALL_SIGN(sys_notimpl), /* 195 */
  10186. SYSCALL_SIGN(sys_timerfd_create),
  10187. SYSCALL_SIGN(sys_timerfd_settime),
  10188. SYSCALL_SIGN(sys_timerfd_gettime),
  10189. SYSCALL_SIGN(sys_signalfd),
  10190. SYSCALL_SIGN(sys_memfd_create), /* 200 */
  10191. SYSCALL_SIGN(sys_ftruncate),
  10192. SYSCALL_SIGN(sys_setitimer),
  10193. SYSCALL_SIGN(sys_utimensat),
  10194. #ifdef RT_USING_POSIX_SOCKET
  10195. SYSCALL_SIGN(sys_syslog),
  10196. SYSCALL_SIGN(sys_socketpair), /* 205 */
  10197. #else
  10198. SYSCALL_SIGN(sys_notimpl),
  10199. SYSCALL_SIGN(sys_notimpl), /* 205 */
  10200. #endif
  10201. SYSCALL_SIGN(sys_wait4),
  10202. SYSCALL_SIGN(sys_set_robust_list),
  10203. SYSCALL_SIGN(sys_get_robust_list),
  10204. SYSCALL_SIGN(sys_setpgid),
  10205. SYSCALL_SIGN(sys_getpgid), /* 210 */
  10206. SYSCALL_SIGN(sys_getsid),
  10207. SYSCALL_SIGN(sys_getppid),
  10208. SYSCALL_SIGN(sys_fchdir),
  10209. SYSCALL_SIGN(sys_chown),
  10210. };
  10211. const void *lwp_get_sys_api(rt_uint32_t number)
  10212. {
  10213. const void *func = (const void *)sys_notimpl;
  10214. if (number == 0xff)
  10215. {
  10216. func = (void *)sys_log;
  10217. }
  10218. else
  10219. {
  10220. number -= 1;
  10221. if (number < sizeof(func_table) / sizeof(func_table[0]))
  10222. {
  10223. func = func_table[number].func;
  10224. }
  10225. else
  10226. {
  10227. if (__sys_log_enable)
  10228. {
  10229. LOG_I("Unimplement syscall %d", number);
  10230. }
  10231. }
  10232. }
  10233. return func;
  10234. }
  10235. const char *lwp_get_syscall_name(rt_uint32_t number)
  10236. {
  10237. const char *name = "sys_notimpl";
  10238. if (number == 0xff)
  10239. {
  10240. name = "sys_log";
  10241. }
  10242. else
  10243. {
  10244. number -= 1;
  10245. if (number < sizeof(func_table) / sizeof(func_table[0]))
  10246. {
  10247. name = (char*)func_table[number].name;
  10248. }
  10249. else
  10250. {
  10251. if (__sys_log_enable)
  10252. {
  10253. LOG_I("Unimplement syscall %d", number);
  10254. }
  10255. }
  10256. }
  10257. /* skip sys_ */
  10258. return name;
  10259. }