You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ev.c 149KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674
  1. /*
  2. * libev event processing core, watcher management
  3. *
  4. * Copyright (c) 2007-2019 Marc Alexander Lehmann <libev@schmorp.de>
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without modifica-
  8. * tion, are permitted provided that the following conditions are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright notice,
  11. * this list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in the
  15. * documentation and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  18. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
  19. * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  20. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
  21. * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  22. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  23. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  24. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
  25. * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  26. * OF THE POSSIBILITY OF SUCH DAMAGE.
  27. *
  28. * Alternatively, the contents of this file may be used under the terms of
  29. * the GNU General Public License ("GPL") version 2 or any later version,
  30. * in which case the provisions of the GPL are applicable instead of
  31. * the above. If you wish to allow the use of your version of this file
  32. * only under the terms of the GPL and not to allow others to use your
  33. * version of this file under the BSD license, indicate your decision
  34. * by deleting the provisions above and replace them with the notice
  35. * and other provisions required by the GPL. If you do not delete the
  36. * provisions above, a recipient may use your version of this file under
  37. * either the BSD or the GPL.
  38. */
  39. /* this big block deduces configuration from config.h */
  40. #ifndef EV_STANDALONE
  41. # ifdef EV_CONFIG_H
  42. # include EV_CONFIG_H
  43. # else
  44. # include "config.h"
  45. # endif
  46. #ifdef __GNUC__
  47. #pragma GCC diagnostic ignored "-Wunused-value"
  48. #endif
  49. # if HAVE_FLOOR
  50. # ifndef EV_USE_FLOOR
  51. # define EV_USE_FLOOR 1
  52. # endif
  53. # endif
  54. # if HAVE_CLOCK_SYSCALL
  55. # ifndef EV_USE_CLOCK_SYSCALL
  56. # define EV_USE_CLOCK_SYSCALL 1
  57. # ifndef EV_USE_REALTIME
  58. # define EV_USE_REALTIME 0
  59. # endif
  60. # ifndef EV_USE_MONOTONIC
  61. # define EV_USE_MONOTONIC 1
  62. # endif
  63. # endif
  64. # elif !defined EV_USE_CLOCK_SYSCALL
  65. # define EV_USE_CLOCK_SYSCALL 0
  66. # endif
  67. # if HAVE_CLOCK_GETTIME
  68. # ifndef EV_USE_MONOTONIC
  69. # define EV_USE_MONOTONIC 1
  70. # endif
  71. # ifndef EV_USE_REALTIME
  72. # define EV_USE_REALTIME 0
  73. # endif
  74. # else
  75. # ifndef EV_USE_MONOTONIC
  76. # define EV_USE_MONOTONIC 0
  77. # endif
  78. # ifndef EV_USE_REALTIME
  79. # define EV_USE_REALTIME 0
  80. # endif
  81. # endif
  82. # if HAVE_NANOSLEEP
  83. # ifndef EV_USE_NANOSLEEP
  84. # define EV_USE_NANOSLEEP EV_FEATURE_OS
  85. # endif
  86. # else
  87. # undef EV_USE_NANOSLEEP
  88. # define EV_USE_NANOSLEEP 0
  89. # endif
  90. # if HAVE_SELECT && HAVE_SYS_SELECT_H
  91. # ifndef EV_USE_SELECT
  92. # define EV_USE_SELECT EV_FEATURE_BACKENDS
  93. # endif
  94. # else
  95. # undef EV_USE_SELECT
  96. # define EV_USE_SELECT 0
  97. # endif
  98. # if HAVE_POLL && HAVE_POLL_H
  99. # ifndef EV_USE_POLL
  100. # define EV_USE_POLL EV_FEATURE_BACKENDS
  101. # endif
  102. # else
  103. # undef EV_USE_POLL
  104. # define EV_USE_POLL 0
  105. # endif
  106. # if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
  107. # ifndef EV_USE_EPOLL
  108. # define EV_USE_EPOLL EV_FEATURE_BACKENDS
  109. # endif
  110. # else
  111. # undef EV_USE_EPOLL
  112. # define EV_USE_EPOLL 0
  113. # endif
  114. # if HAVE_LINUX_AIO_ABI_H
  115. # ifndef EV_USE_LINUXAIO
  116. # define EV_USE_LINUXAIO 0 /* was: EV_FEATURE_BACKENDS, always off by default */
  117. # endif
  118. # else
  119. # undef EV_USE_LINUXAIO
  120. # define EV_USE_LINUXAIO 0
  121. # endif
  122. # if HAVE_LINUX_FS_H && HAVE_SYS_TIMERFD_H && HAVE_KERNEL_RWF_T
  123. # ifndef EV_USE_IOURING
  124. # define EV_USE_IOURING EV_FEATURE_BACKENDS
  125. # endif
  126. # else
  127. # undef EV_USE_IOURING
  128. # define EV_USE_IOURING 0
  129. # endif
  130. # if HAVE_KQUEUE && HAVE_SYS_EVENT_H
  131. # ifndef EV_USE_KQUEUE
  132. # define EV_USE_KQUEUE EV_FEATURE_BACKENDS
  133. # endif
  134. # else
  135. # undef EV_USE_KQUEUE
  136. # define EV_USE_KQUEUE 0
  137. # endif
  138. # if HAVE_PORT_H && HAVE_PORT_CREATE
  139. # ifndef EV_USE_PORT
  140. # define EV_USE_PORT EV_FEATURE_BACKENDS
  141. # endif
  142. # else
  143. # undef EV_USE_PORT
  144. # define EV_USE_PORT 0
  145. # endif
  146. # if HAVE_INOTIFY_INIT && HAVE_SYS_INOTIFY_H
  147. # ifndef EV_USE_INOTIFY
  148. # define EV_USE_INOTIFY EV_FEATURE_OS
  149. # endif
  150. # else
  151. # undef EV_USE_INOTIFY
  152. # define EV_USE_INOTIFY 0
  153. # endif
  154. # if HAVE_SIGNALFD && HAVE_SYS_SIGNALFD_H
  155. # ifndef EV_USE_SIGNALFD
  156. # define EV_USE_SIGNALFD EV_FEATURE_OS
  157. # endif
  158. # else
  159. # undef EV_USE_SIGNALFD
  160. # define EV_USE_SIGNALFD 0
  161. # endif
  162. # if HAVE_EVENTFD
  163. # ifndef EV_USE_EVENTFD
  164. # define EV_USE_EVENTFD EV_FEATURE_OS
  165. # endif
  166. # else
  167. # undef EV_USE_EVENTFD
  168. # define EV_USE_EVENTFD 0
  169. # endif
  170. # if HAVE_SYS_TIMERFD_H && HAVE_TIMERFD
  171. # ifndef EV_USE_TIMERFD
  172. # define EV_USE_TIMERFD EV_FEATURE_OS
  173. # endif
  174. # else
  175. # undef EV_USE_TIMERFD
  176. # define EV_USE_TIMERFD 0
  177. # endif
  178. #endif
  179. /* OS X, in its infinite idiocy, actually HARDCODES
  180. * a limit of 1024 into their select. Where people have brains,
  181. * OS X engineers apparently have a vacuum. Or maybe they were
  182. * ordered to have a vacuum, or they do anything for money.
  183. * This might help. Or not.
  184. * Note that this must be defined early, as other include files
  185. * will rely on this define as well.
  186. */
  187. #define _DARWIN_UNLIMITED_SELECT 1
  188. #include <stdlib.h>
  189. #include <string.h>
  190. #include <fcntl.h>
  191. #include <stddef.h>
  192. #include <stdio.h>
  193. #include <assert.h>
  194. #include <errno.h>
  195. #include <sys/types.h>
  196. #include <time.h>
  197. #include <limits.h>
  198. #include <signal.h>
  199. #ifdef EV_H
  200. # include EV_H
  201. #else
  202. # include "ev.h"
  203. #endif
  204. #if EV_NO_THREADS
  205. # undef EV_NO_SMP
  206. # define EV_NO_SMP 1
  207. # undef ECB_NO_THREADS
  208. # define ECB_NO_THREADS 1
  209. #endif
  210. #if EV_NO_SMP
  211. # undef EV_NO_SMP
  212. # define ECB_NO_SMP 1
  213. #endif
  214. #ifndef _WIN32
  215. # include <sys/time.h>
  216. # include <sys/wait.h>
  217. # include <unistd.h>
  218. #else
  219. # include <io.h>
  220. # define WIN32_LEAN_AND_MEAN
  221. # include <winsock2.h>
  222. # include <windows.h>
  223. # ifndef EV_SELECT_IS_WINSOCKET
  224. # define EV_SELECT_IS_WINSOCKET 1
  225. # endif
  226. # undef EV_AVOID_STDIO
  227. #endif
  228. /* this block tries to deduce configuration from header-defined symbols and defaults */
  229. /* try to deduce the maximum number of signals on this platform */
  230. #if defined EV_NSIG
  231. /* use what's provided */
  232. #elif defined NSIG
  233. # define EV_NSIG (NSIG)
  234. #elif defined _NSIG
  235. # define EV_NSIG (_NSIG)
  236. #elif defined SIGMAX
  237. # define EV_NSIG (SIGMAX+1)
  238. #elif defined SIG_MAX
  239. # define EV_NSIG (SIG_MAX+1)
  240. #elif defined _SIG_MAX
  241. # define EV_NSIG (_SIG_MAX+1)
  242. #elif defined MAXSIG
  243. # define EV_NSIG (MAXSIG+1)
  244. #elif defined MAX_SIG
  245. # define EV_NSIG (MAX_SIG+1)
  246. #elif defined SIGARRAYSIZE
  247. # define EV_NSIG (SIGARRAYSIZE) /* Assume ary[SIGARRAYSIZE] */
  248. #elif defined _sys_nsig
  249. # define EV_NSIG (_sys_nsig) /* Solaris 2.5 */
  250. #else
  251. # define EV_NSIG (8 * sizeof (sigset_t) + 1)
  252. #endif
  253. #ifndef EV_USE_FLOOR
  254. # define EV_USE_FLOOR 0
  255. #endif
  256. #ifndef EV_USE_CLOCK_SYSCALL
  257. # if __linux && __GLIBC__ == 2 && __GLIBC_MINOR__ < 17
  258. # define EV_USE_CLOCK_SYSCALL EV_FEATURE_OS
  259. # else
  260. # define EV_USE_CLOCK_SYSCALL 0
  261. # endif
  262. #endif
  263. #if !(_POSIX_TIMERS > 0)
  264. # ifndef EV_USE_MONOTONIC
  265. # define EV_USE_MONOTONIC 0
  266. # endif
  267. # ifndef EV_USE_REALTIME
  268. # define EV_USE_REALTIME 0
  269. # endif
  270. #endif
  271. #ifndef EV_USE_MONOTONIC
  272. # if defined _POSIX_MONOTONIC_CLOCK && _POSIX_MONOTONIC_CLOCK >= 0
  273. # define EV_USE_MONOTONIC EV_FEATURE_OS
  274. # else
  275. # define EV_USE_MONOTONIC 0
  276. # endif
  277. #endif
  278. #ifndef EV_USE_REALTIME
  279. # define EV_USE_REALTIME !EV_USE_CLOCK_SYSCALL
  280. #endif
  281. #ifndef EV_USE_NANOSLEEP
  282. # if _POSIX_C_SOURCE >= 199309L
  283. # define EV_USE_NANOSLEEP EV_FEATURE_OS
  284. # else
  285. # define EV_USE_NANOSLEEP 0
  286. # endif
  287. #endif
  288. #ifndef EV_USE_SELECT
  289. # define EV_USE_SELECT EV_FEATURE_BACKENDS
  290. #endif
  291. #ifndef EV_USE_POLL
  292. # ifdef _WIN32
  293. # define EV_USE_POLL 0
  294. # else
  295. # define EV_USE_POLL EV_FEATURE_BACKENDS
  296. # endif
  297. #endif
  298. #ifndef EV_USE_EPOLL
  299. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
  300. # define EV_USE_EPOLL EV_FEATURE_BACKENDS
  301. # else
  302. # define EV_USE_EPOLL 0
  303. # endif
  304. #endif
  305. #ifndef EV_USE_KQUEUE
  306. # define EV_USE_KQUEUE 0
  307. #endif
  308. #ifndef EV_USE_PORT
  309. # define EV_USE_PORT 0
  310. #endif
  311. #ifndef EV_USE_LINUXAIO
  312. # if __linux /* libev currently assumes linux/aio_abi.h is always available on linux */
  313. # define EV_USE_LINUXAIO 0 /* was: 1, always off by default */
  314. # else
  315. # define EV_USE_LINUXAIO 0
  316. # endif
  317. #endif
  318. #ifndef EV_USE_IOURING
  319. # if __linux /* later checks might disable again */
  320. # define EV_USE_IOURING 1
  321. # else
  322. # define EV_USE_IOURING 0
  323. # endif
  324. #endif
  325. #ifndef EV_USE_INOTIFY
  326. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 4))
  327. # define EV_USE_INOTIFY EV_FEATURE_OS
  328. # else
  329. # define EV_USE_INOTIFY 0
  330. # endif
  331. #endif
  332. #ifndef EV_PID_HASHSIZE
  333. # define EV_PID_HASHSIZE EV_FEATURE_DATA ? 16 : 1
  334. #endif
  335. #ifndef EV_INOTIFY_HASHSIZE
  336. # define EV_INOTIFY_HASHSIZE EV_FEATURE_DATA ? 16 : 1
  337. #endif
  338. #ifndef EV_USE_EVENTFD
  339. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
  340. # define EV_USE_EVENTFD EV_FEATURE_OS
  341. # else
  342. # define EV_USE_EVENTFD 0
  343. # endif
  344. #endif
  345. #ifndef EV_USE_SIGNALFD
  346. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 7))
  347. # define EV_USE_SIGNALFD EV_FEATURE_OS
  348. # else
  349. # define EV_USE_SIGNALFD 0
  350. # endif
  351. #endif
  352. #ifndef EV_USE_TIMERFD
  353. # if __linux && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 8))
  354. # define EV_USE_TIMERFD EV_FEATURE_OS
  355. # else
  356. # define EV_USE_TIMERFD 0
  357. # endif
  358. #endif
  359. #if 0 /* debugging */
  360. # define EV_VERIFY 3
  361. # define EV_USE_4HEAP 1
  362. # define EV_HEAP_CACHE_AT 1
  363. #endif
  364. #ifndef EV_VERIFY
  365. # define EV_VERIFY (EV_FEATURE_API ? 1 : 0)
  366. #endif
  367. #ifndef EV_USE_4HEAP
  368. # define EV_USE_4HEAP EV_FEATURE_DATA
  369. #endif
  370. #ifndef EV_HEAP_CACHE_AT
  371. # define EV_HEAP_CACHE_AT EV_FEATURE_DATA
  372. #endif
  373. #ifdef __ANDROID__
  374. /* supposedly, android doesn't typedef fd_mask */
  375. # undef EV_USE_SELECT
  376. # define EV_USE_SELECT 0
  377. /* supposedly, we need to include syscall.h, not sys/syscall.h, so just disable */
  378. # undef EV_USE_CLOCK_SYSCALL
  379. # define EV_USE_CLOCK_SYSCALL 0
  380. #endif
  381. /* aix's poll.h seems to cause lots of trouble */
  382. #ifdef _AIX
  383. /* AIX has a completely broken poll.h header */
  384. # undef EV_USE_POLL
  385. # define EV_USE_POLL 0
  386. #endif
  387. /* on linux, we can use a (slow) syscall to avoid a dependency on pthread, */
  388. /* which makes programs even slower. might work on other unices, too. */
  389. #if EV_USE_CLOCK_SYSCALL
  390. # include <sys/syscall.h>
  391. # ifdef SYS_clock_gettime
  392. # define clock_gettime(id, ts) syscall (SYS_clock_gettime, (id), (ts))
  393. # undef EV_USE_MONOTONIC
  394. # define EV_USE_MONOTONIC 1
  395. # define EV_NEED_SYSCALL 1
  396. # else
  397. # undef EV_USE_CLOCK_SYSCALL
  398. # define EV_USE_CLOCK_SYSCALL 0
  399. # endif
  400. #endif
  401. /* this block fixes any misconfiguration where we know we run into trouble otherwise */
  402. #ifndef CLOCK_MONOTONIC
  403. # undef EV_USE_MONOTONIC
  404. # define EV_USE_MONOTONIC 0
  405. #endif
  406. #ifndef CLOCK_REALTIME
  407. # undef EV_USE_REALTIME
  408. # define EV_USE_REALTIME 0
  409. #endif
  410. #if !EV_STAT_ENABLE
  411. # undef EV_USE_INOTIFY
  412. # define EV_USE_INOTIFY 0
  413. #endif
  414. #if __linux && EV_USE_IOURING
  415. # include <linux/version.h>
  416. # if LINUX_VERSION_CODE < KERNEL_VERSION(4,14,0)
  417. # undef EV_USE_IOURING
  418. # define EV_USE_IOURING 0
  419. # endif
  420. #endif
  421. #if !EV_USE_NANOSLEEP
  422. /* hp-ux has it in sys/time.h, which we unconditionally include above */
  423. # if !defined _WIN32 && !defined __hpux
  424. # include <sys/select.h>
  425. # endif
  426. #endif
  427. #if EV_USE_LINUXAIO
  428. # include <sys/syscall.h>
  429. # if SYS_io_getevents && EV_USE_EPOLL /* linuxaio backend requires epoll backend */
  430. # define EV_NEED_SYSCALL 1
  431. # else
  432. # undef EV_USE_LINUXAIO
  433. # define EV_USE_LINUXAIO 0
  434. # endif
  435. #endif
  436. #if EV_USE_IOURING
  437. # include <sys/syscall.h>
  438. # if !SYS_io_uring_setup && __linux && !__alpha
  439. # define SYS_io_uring_setup 425
  440. # define SYS_io_uring_enter 426
  441. # define SYS_io_uring_wregister 427
  442. # endif
  443. # if SYS_io_uring_setup && EV_USE_EPOLL /* iouring backend requires epoll backend */
  444. # define EV_NEED_SYSCALL 1
  445. # else
  446. # undef EV_USE_IOURING
  447. # define EV_USE_IOURING 0
  448. # endif
  449. #endif
  450. #if EV_USE_INOTIFY
  451. # include <sys/statfs.h>
  452. # include <sys/inotify.h>
  453. /* some very old inotify.h headers don't have IN_DONT_FOLLOW */
  454. # ifndef IN_DONT_FOLLOW
  455. # undef EV_USE_INOTIFY
  456. # define EV_USE_INOTIFY 0
  457. # endif
  458. #endif
  459. #if EV_USE_EVENTFD
  460. /* our minimum requirement is glibc 2.7 which has the stub, but not the full header */
  461. # include <stdint.h>
  462. # ifndef EFD_NONBLOCK
  463. # define EFD_NONBLOCK O_NONBLOCK
  464. # endif
  465. # ifndef EFD_CLOEXEC
  466. # ifdef O_CLOEXEC
  467. # define EFD_CLOEXEC O_CLOEXEC
  468. # else
  469. # define EFD_CLOEXEC 02000000
  470. # endif
  471. # endif
  472. EV_CPP(extern "C") int (eventfd) (unsigned int initval, int flags);
  473. #endif
  474. #if EV_USE_SIGNALFD
  475. /* our minimum requirement is glibc 2.7 which has the stub, but not the full header */
  476. # include <stdint.h>
  477. # ifndef SFD_NONBLOCK
  478. # define SFD_NONBLOCK O_NONBLOCK
  479. # endif
  480. # ifndef SFD_CLOEXEC
  481. # ifdef O_CLOEXEC
  482. # define SFD_CLOEXEC O_CLOEXEC
  483. # else
  484. # define SFD_CLOEXEC 02000000
  485. # endif
  486. # endif
  487. EV_CPP (extern "C") int (signalfd) (int fd, const sigset_t *mask, int flags);
  488. struct signalfd_siginfo
  489. {
  490. uint32_t ssi_signo;
  491. char pad[128 - sizeof (uint32_t)];
  492. };
  493. #endif
  494. /* for timerfd, libev core requires TFD_TIMER_CANCEL_ON_SET &c */
  495. #if EV_USE_TIMERFD
  496. # include <sys/timerfd.h>
  497. /* timerfd is only used for periodics */
  498. # if !(defined (TFD_TIMER_CANCEL_ON_SET) && defined (TFD_CLOEXEC) && defined (TFD_NONBLOCK)) || !EV_PERIODIC_ENABLE
  499. # undef EV_USE_TIMERFD
  500. # define EV_USE_TIMERFD 0
  501. # endif
  502. #endif
  503. /*****************************************************************************/
  504. #if EV_VERIFY >= 3
  505. # define EV_FREQUENT_CHECK ev_verify (EV_A)
  506. #else
  507. # define EV_FREQUENT_CHECK do { } while (0)
  508. #endif
  509. /*
  510. * This is used to work around floating point rounding problems.
  511. * This value is good at least till the year 4000.
  512. */
  513. #define MIN_INTERVAL 0.0001220703125 /* 1/2**13, good till 4000 */
  514. // #define MIN_INTERVAL 0.00000095367431640625 /* 1/2**20, good till 2200 */
  515. #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
  516. #define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */
  517. #define MAX_BLOCKTIME2 1500001.07 /* same, but when timerfd is used to detect jumps, also safe delay to not overflow */
  518. /* find a portable timestamp that is "always" in the future but fits into time_t.
  519. * this is quite hard, and we are mostly guessing - we handle 32 bit signed/unsigned time_t,
  520. * and sizes larger than 32 bit, and maybe the unlikely floating point time_t */
  521. #define EV_TSTAMP_HUGE \
  522. (sizeof (time_t) >= 8 ? 10000000000000. \
  523. : 0 < (time_t)4294967295 ? 4294967295. \
  524. : 2147483647.) \
  525. #ifndef EV_TS_CONST
  526. # define EV_TS_CONST(nv) nv
  527. # define EV_TS_TO_MSEC(a) a * 1e3 + 0.9999
  528. # define EV_TS_FROM_USEC(us) us * 1e-6
  529. # define EV_TV_SET(tv,t) do { tv.tv_sec = (long)t; tv.tv_usec = (long)((t - tv.tv_sec) * 1e6); } while (0)
  530. # define EV_TS_SET(ts,t) do { ts.tv_sec = (long)t; ts.tv_nsec = (long)((t - ts.tv_sec) * 1e9); } while (0)
  531. # define EV_TV_GET(tv) ((tv).tv_sec + (tv).tv_usec * 1e-6)
  532. # define EV_TS_GET(ts) ((ts).tv_sec + (ts).tv_nsec * 1e-9)
  533. #endif
  534. /* the following is ecb.h embedded into libev - use update_ev_c to update from an external copy */
  535. /* ECB.H BEGIN */
  536. /*
  537. * libecb - http://software.schmorp.de/pkg/libecb
  538. *
  539. * Copyright (©) 2009-2015,2018-2020 Marc Alexander Lehmann <libecb@schmorp.de>
  540. * Copyright (©) 2011 Emanuele Giaquinta
  541. * All rights reserved.
  542. *
  543. * Redistribution and use in source and binary forms, with or without modifica-
  544. * tion, are permitted provided that the following conditions are met:
  545. *
  546. * 1. Redistributions of source code must retain the above copyright notice,
  547. * this list of conditions and the following disclaimer.
  548. *
  549. * 2. Redistributions in binary form must reproduce the above copyright
  550. * notice, this list of conditions and the following disclaimer in the
  551. * documentation and/or other materials provided with the distribution.
  552. *
  553. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  554. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
  555. * CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  556. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
  557. * CIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  558. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  559. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  560. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTH-
  561. * ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  562. * OF THE POSSIBILITY OF SUCH DAMAGE.
  563. *
  564. * Alternatively, the contents of this file may be used under the terms of
  565. * the GNU General Public License ("GPL") version 2 or any later version,
  566. * in which case the provisions of the GPL are applicable instead of
  567. * the above. If you wish to allow the use of your version of this file
  568. * only under the terms of the GPL and not to allow others to use your
  569. * version of this file under the BSD license, indicate your decision
  570. * by deleting the provisions above and replace them with the notice
  571. * and other provisions required by the GPL. If you do not delete the
  572. * provisions above, a recipient may use your version of this file under
  573. * either the BSD or the GPL.
  574. */
  575. #ifndef ECB_H
  576. #define ECB_H
  577. /* 16 bits major, 16 bits minor */
  578. #define ECB_VERSION 0x00010008
  579. #include <string.h> /* for memcpy */
  580. #if defined (_WIN32) && !defined (__MINGW32__)
  581. typedef signed char int8_t;
  582. typedef unsigned char uint8_t;
  583. typedef signed char int_fast8_t;
  584. typedef unsigned char uint_fast8_t;
  585. typedef signed short int16_t;
  586. typedef unsigned short uint16_t;
  587. typedef signed int int_fast16_t;
  588. typedef unsigned int uint_fast16_t;
  589. typedef signed int int32_t;
  590. typedef unsigned int uint32_t;
  591. typedef signed int int_fast32_t;
  592. typedef unsigned int uint_fast32_t;
  593. #if __GNUC__
  594. typedef signed long long int64_t;
  595. typedef unsigned long long uint64_t;
  596. #else /* _MSC_VER || __BORLANDC__ */
  597. typedef signed __int64 int64_t;
  598. typedef unsigned __int64 uint64_t;
  599. #endif
  600. typedef int64_t int_fast64_t;
  601. typedef uint64_t uint_fast64_t;
  602. #ifdef _WIN64
  603. #define ECB_PTRSIZE 8
  604. typedef uint64_t uintptr_t;
  605. typedef int64_t intptr_t;
  606. #else
  607. #define ECB_PTRSIZE 4
  608. typedef uint32_t uintptr_t;
  609. typedef int32_t intptr_t;
  610. #endif
  611. #else
  612. #include <inttypes.h>
  613. #if (defined INTPTR_MAX ? INTPTR_MAX : ULONG_MAX) > 0xffffffffU
  614. #define ECB_PTRSIZE 8
  615. #else
  616. #define ECB_PTRSIZE 4
  617. #endif
  618. #endif
  619. #define ECB_GCC_AMD64 (__amd64 || __amd64__ || __x86_64 || __x86_64__)
  620. #define ECB_MSVC_AMD64 (_M_AMD64 || _M_X64)
  621. #ifndef ECB_OPTIMIZE_SIZE
  622. #if __OPTIMIZE_SIZE__
  623. #define ECB_OPTIMIZE_SIZE 1
  624. #else
  625. #define ECB_OPTIMIZE_SIZE 0
  626. #endif
  627. #endif
  628. /* work around x32 idiocy by defining proper macros */
  629. #if ECB_GCC_AMD64 || ECB_MSVC_AMD64
  630. #if _ILP32
  631. #define ECB_AMD64_X32 1
  632. #else
  633. #define ECB_AMD64 1
  634. #endif
  635. #endif
  636. /* many compilers define _GNUC_ to some versions but then only implement
  637. * what their idiot authors think are the "more important" extensions,
  638. * causing enormous grief in return for some better fake benchmark numbers.
  639. * or so.
  640. * we try to detect these and simply assume they are not gcc - if they have
  641. * an issue with that they should have done it right in the first place.
  642. */
  643. #if !defined __GNUC_MINOR__ || defined __INTEL_COMPILER || defined __SUNPRO_C || defined __SUNPRO_CC || defined __llvm__ || defined __clang__
  644. #define ECB_GCC_VERSION(major,minor) 0
  645. #else
  646. #define ECB_GCC_VERSION(major,minor) (__GNUC__ > (major) || (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
  647. #endif
  648. #define ECB_CLANG_VERSION(major,minor) (__clang_major__ > (major) || (__clang_major__ == (major) && __clang_minor__ >= (minor)))
  649. #if __clang__ && defined __has_builtin
  650. #define ECB_CLANG_BUILTIN(x) __has_builtin (x)
  651. #else
  652. #define ECB_CLANG_BUILTIN(x) 0
  653. #endif
  654. #if __clang__ && defined __has_extension
  655. #define ECB_CLANG_EXTENSION(x) __has_extension (x)
  656. #else
  657. #define ECB_CLANG_EXTENSION(x) 0
  658. #endif
  659. #define ECB_CPP (__cplusplus+0)
  660. #define ECB_CPP11 (__cplusplus >= 201103L)
  661. #define ECB_CPP14 (__cplusplus >= 201402L)
  662. #define ECB_CPP17 (__cplusplus >= 201703L)
  663. #if ECB_CPP
  664. #define ECB_C 0
  665. #define ECB_STDC_VERSION 0
  666. #else
  667. #define ECB_C 1
  668. #define ECB_STDC_VERSION __STDC_VERSION__
  669. #endif
  670. #define ECB_C99 (ECB_STDC_VERSION >= 199901L)
  671. #define ECB_C11 (ECB_STDC_VERSION >= 201112L)
  672. #define ECB_C17 (ECB_STDC_VERSION >= 201710L)
  673. #if ECB_CPP
  674. #define ECB_EXTERN_C extern "C"
  675. #define ECB_EXTERN_C_BEG ECB_EXTERN_C {
  676. #define ECB_EXTERN_C_END }
  677. #else
  678. #define ECB_EXTERN_C extern
  679. #define ECB_EXTERN_C_BEG
  680. #define ECB_EXTERN_C_END
  681. #endif
  682. /*****************************************************************************/
  683. /* ECB_NO_THREADS - ecb is not used by multiple threads, ever */
  684. /* ECB_NO_SMP - ecb might be used in multiple threads, but only on a single cpu */
  685. #if ECB_NO_THREADS
  686. #define ECB_NO_SMP 1
  687. #endif
  688. #if ECB_NO_SMP
  689. #define ECB_MEMORY_FENCE do { } while (0)
  690. #endif
  691. /* http://www-01.ibm.com/support/knowledgecenter/SSGH3R_13.1.0/com.ibm.xlcpp131.aix.doc/compiler_ref/compiler_builtins.html */
  692. #if __xlC__ && ECB_CPP
  693. #include <builtins.h>
  694. #endif
  695. #if 1400 <= _MSC_VER
  696. #include <intrin.h> /* fence functions _ReadBarrier, also bit search functions _BitScanReverse */
  697. #endif
  698. #ifndef ECB_MEMORY_FENCE
  699. #if ECB_GCC_VERSION(2,5) || defined __INTEL_COMPILER || (__llvm__ && __GNUC__) || __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110
  700. #define ECB_MEMORY_FENCE_RELAXED __asm__ __volatile__ ("" : : : "memory")
  701. #if __i386 || __i386__
  702. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("lock; orb $0, -1(%%esp)" : : : "memory")
  703. #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory")
  704. #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("" : : : "memory")
  705. #elif ECB_GCC_AMD64
  706. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mfence" : : : "memory")
  707. #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("" : : : "memory")
  708. #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("" : : : "memory")
  709. #elif __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__
  710. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("sync" : : : "memory")
  711. #elif defined __ARM_ARCH_2__ \
  712. || defined __ARM_ARCH_3__ || defined __ARM_ARCH_3M__ \
  713. || defined __ARM_ARCH_4__ || defined __ARM_ARCH_4T__ \
  714. || defined __ARM_ARCH_5__ || defined __ARM_ARCH_5E__ \
  715. || defined __ARM_ARCH_5T__ || defined __ARM_ARCH_5TE__ \
  716. || defined __ARM_ARCH_5TEJ__
  717. /* should not need any, unless running old code on newer cpu - arm doesn't support that */
  718. #elif defined __ARM_ARCH_6__ || defined __ARM_ARCH_6J__ \
  719. || defined __ARM_ARCH_6K__ || defined __ARM_ARCH_6ZK__ \
  720. || defined __ARM_ARCH_6T2__
  721. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mcr p15,0,%0,c7,c10,5" : : "r" (0) : "memory")
  722. #elif defined __ARM_ARCH_7__ || defined __ARM_ARCH_7A__ \
  723. || defined __ARM_ARCH_7R__ || defined __ARM_ARCH_7M__
  724. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("dmb" : : : "memory")
  725. #elif __aarch64__
  726. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("dmb ish" : : : "memory")
  727. #elif (__sparc || __sparc__) && !(__sparc_v8__ || defined __sparcv8)
  728. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad | #StoreStore | #StoreLoad" : : : "memory")
  729. #define ECB_MEMORY_FENCE_ACQUIRE __asm__ __volatile__ ("membar #LoadStore | #LoadLoad" : : : "memory")
  730. #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("membar #LoadStore | #StoreStore")
  731. #elif defined __s390__ || defined __s390x__
  732. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("bcr 15,0" : : : "memory")
  733. #elif defined __mips__
  734. /* GNU/Linux emulates sync on mips1 architectures, so we force its use */
  735. /* anybody else who still uses mips1 is supposed to send in their version, with detection code. */
  736. #define ECB_MEMORY_FENCE __asm__ __volatile__ (".set mips2; sync; .set mips0" : : : "memory")
  737. #elif defined __alpha__
  738. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mb" : : : "memory")
  739. #elif defined __hppa__
  740. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory")
  741. #define ECB_MEMORY_FENCE_RELEASE __asm__ __volatile__ ("")
  742. #elif defined __ia64__
  743. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("mf" : : : "memory")
  744. #elif defined __m68k__
  745. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory")
  746. #elif defined __m88k__
  747. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("tb1 0,%%r0,128" : : : "memory")
  748. #elif defined __sh__
  749. #define ECB_MEMORY_FENCE __asm__ __volatile__ ("" : : : "memory")
  750. #endif
  751. #endif
  752. #endif
  753. #ifndef ECB_MEMORY_FENCE
  754. #if ECB_GCC_VERSION(4,7)
  755. /* see comment below (stdatomic.h) about the C11 memory model. */
  756. #define ECB_MEMORY_FENCE __atomic_thread_fence (__ATOMIC_SEQ_CST)
  757. #define ECB_MEMORY_FENCE_ACQUIRE __atomic_thread_fence (__ATOMIC_ACQUIRE)
  758. #define ECB_MEMORY_FENCE_RELEASE __atomic_thread_fence (__ATOMIC_RELEASE)
  759. #define ECB_MEMORY_FENCE_RELAXED __atomic_thread_fence (__ATOMIC_RELAXED)
  760. #elif ECB_CLANG_EXTENSION(c_atomic)
  761. /* see comment below (stdatomic.h) about the C11 memory model. */
  762. #define ECB_MEMORY_FENCE __c11_atomic_thread_fence (__ATOMIC_SEQ_CST)
  763. #define ECB_MEMORY_FENCE_ACQUIRE __c11_atomic_thread_fence (__ATOMIC_ACQUIRE)
  764. #define ECB_MEMORY_FENCE_RELEASE __c11_atomic_thread_fence (__ATOMIC_RELEASE)
  765. #define ECB_MEMORY_FENCE_RELAXED __c11_atomic_thread_fence (__ATOMIC_RELAXED)
  766. #elif ECB_GCC_VERSION(4,4) || defined __INTEL_COMPILER || defined __clang__
  767. #define ECB_MEMORY_FENCE __sync_synchronize ()
  768. #elif _MSC_VER >= 1500 /* VC++ 2008 */
  769. /* apparently, microsoft broke all the memory barrier stuff in Visual Studio 2008... */
  770. #pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier)
  771. #define ECB_MEMORY_FENCE _ReadWriteBarrier (); MemoryBarrier()
  772. #define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier (); MemoryBarrier() /* according to msdn, _ReadBarrier is not a load fence */
  773. #define ECB_MEMORY_FENCE_RELEASE _WriteBarrier (); MemoryBarrier()
  774. #elif _MSC_VER >= 1400 /* VC++ 2005 */
  775. #pragma intrinsic(_ReadBarrier,_WriteBarrier,_ReadWriteBarrier)
  776. #define ECB_MEMORY_FENCE _ReadWriteBarrier ()
  777. #define ECB_MEMORY_FENCE_ACQUIRE _ReadWriteBarrier () /* according to msdn, _ReadBarrier is not a load fence */
  778. #define ECB_MEMORY_FENCE_RELEASE _WriteBarrier ()
  779. #elif defined _WIN32
  780. #include <WinNT.h>
  781. #define ECB_MEMORY_FENCE MemoryBarrier () /* actually just xchg on x86... scary */
  782. #elif __SUNPRO_C >= 0x5110 || __SUNPRO_CC >= 0x5110
  783. #include <mbarrier.h>
  784. #define ECB_MEMORY_FENCE __machine_rw_barrier ()
  785. #define ECB_MEMORY_FENCE_ACQUIRE __machine_acq_barrier ()
  786. #define ECB_MEMORY_FENCE_RELEASE __machine_rel_barrier ()
  787. #define ECB_MEMORY_FENCE_RELAXED __compiler_barrier ()
  788. #elif __xlC__
  789. #define ECB_MEMORY_FENCE __sync ()
  790. #endif
  791. #endif
  792. #ifndef ECB_MEMORY_FENCE
  793. #if ECB_C11 && !defined __STDC_NO_ATOMICS__
  794. /* we assume that these memory fences work on all variables/all memory accesses, */
  795. /* not just C11 atomics and atomic accesses */
  796. #include <stdatomic.h>
  797. #define ECB_MEMORY_FENCE atomic_thread_fence (memory_order_seq_cst)
  798. #define ECB_MEMORY_FENCE_ACQUIRE atomic_thread_fence (memory_order_acquire)
  799. #define ECB_MEMORY_FENCE_RELEASE atomic_thread_fence (memory_order_release)
  800. #endif
  801. #endif
  802. #ifndef ECB_MEMORY_FENCE
  803. #if !ECB_AVOID_PTHREADS
  804. /*
  805. * if you get undefined symbol references to pthread_mutex_lock,
  806. * or failure to find pthread.h, then you should implement
  807. * the ECB_MEMORY_FENCE operations for your cpu/compiler
  808. * OR provide pthread.h and link against the posix thread library
  809. * of your system.
  810. */
  811. #include <pthread.h>
  812. #define ECB_NEEDS_PTHREADS 1
  813. #define ECB_MEMORY_FENCE_NEEDS_PTHREADS 1
  814. static pthread_mutex_t ecb_mf_lock = PTHREAD_MUTEX_INITIALIZER;
  815. #define ECB_MEMORY_FENCE do { pthread_mutex_lock (&ecb_mf_lock); pthread_mutex_unlock (&ecb_mf_lock); } while (0)
  816. #endif
  817. #endif
  818. #if !defined ECB_MEMORY_FENCE_ACQUIRE && defined ECB_MEMORY_FENCE
  819. #define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE
  820. #endif
  821. #if !defined ECB_MEMORY_FENCE_RELEASE && defined ECB_MEMORY_FENCE
  822. #define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE
  823. #endif
  824. #if !defined ECB_MEMORY_FENCE_RELAXED && defined ECB_MEMORY_FENCE
  825. #define ECB_MEMORY_FENCE_RELAXED ECB_MEMORY_FENCE /* very heavy-handed */
  826. #endif
  827. /*****************************************************************************/
  828. #if ECB_CPP
  829. #define ecb_inline static inline
  830. #elif ECB_GCC_VERSION(2,5)
  831. #define ecb_inline static __inline__
  832. #elif ECB_C99
  833. #define ecb_inline static inline
  834. #else
  835. #define ecb_inline static
  836. #endif
  837. #if ECB_GCC_VERSION(3,3)
  838. #define ecb_restrict __restrict__
  839. #elif ECB_C99
  840. #define ecb_restrict restrict
  841. #else
  842. #define ecb_restrict
  843. #endif
  844. typedef int ecb_bool;
  845. #define ECB_CONCAT_(a, b) a ## b
  846. #define ECB_CONCAT(a, b) ECB_CONCAT_(a, b)
  847. #define ECB_STRINGIFY_(a) # a
  848. #define ECB_STRINGIFY(a) ECB_STRINGIFY_(a)
  849. #define ECB_STRINGIFY_EXPR(expr) ((expr), ECB_STRINGIFY_ (expr))
  850. #define ecb_function_ ecb_inline
  851. #if ECB_GCC_VERSION(3,1) || ECB_CLANG_VERSION(2,8)
  852. #define ecb_attribute(attrlist) __attribute__ (attrlist)
  853. #else
  854. #define ecb_attribute(attrlist)
  855. #endif
  856. #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_constant_p)
  857. #define ecb_is_constant(expr) __builtin_constant_p (expr)
  858. #else
  859. /* possible C11 impl for integral types
  860. typedef struct ecb_is_constant_struct ecb_is_constant_struct;
  861. #define ecb_is_constant(expr) _Generic ((1 ? (struct ecb_is_constant_struct *)0 : (void *)((expr) - (expr)), ecb_is_constant_struct *: 0, default: 1)) */
  862. #define ecb_is_constant(expr) 0
  863. #endif
  864. #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_expect)
  865. #define ecb_expect(expr,value) __builtin_expect ((expr),(value))
  866. #else
  867. #define ecb_expect(expr,value) (expr)
  868. #endif
  869. #if ECB_GCC_VERSION(3,1) || ECB_CLANG_BUILTIN(__builtin_prefetch)
  870. #define ecb_prefetch(addr,rw,locality) __builtin_prefetch (addr, rw, locality)
  871. #else
  872. #define ecb_prefetch(addr,rw,locality)
  873. #endif
  874. /* no emulation for ecb_decltype */
  875. #if ECB_CPP11
  876. // older implementations might have problems with decltype(x)::type, work around it
  877. template<class T> struct ecb_decltype_t { typedef T type; };
  878. #define ecb_decltype(x) ecb_decltype_t<decltype (x)>::type
  879. #elif ECB_GCC_VERSION(3,0) || ECB_CLANG_VERSION(2,8)
  880. #define ecb_decltype(x) __typeof__ (x)
  881. #endif
  882. #if _MSC_VER >= 1300
  883. #define ecb_deprecated __declspec (deprecated)
  884. #else
  885. #define ecb_deprecated ecb_attribute ((__deprecated__))
  886. #endif
  887. #if _MSC_VER >= 1500
  888. #define ecb_deprecated_message(msg) __declspec (deprecated (msg))
  889. #elif ECB_GCC_VERSION(4,5)
  890. #define ecb_deprecated_message(msg) ecb_attribute ((__deprecated__ (msg))
  891. #else
  892. #define ecb_deprecated_message(msg) ecb_deprecated
  893. #endif
  894. #if _MSC_VER >= 1400
  895. #define ecb_noinline __declspec (noinline)
  896. #else
  897. #define ecb_noinline ecb_attribute ((__noinline__))
  898. #endif
  899. #define ecb_unused ecb_attribute ((__unused__))
  900. #define ecb_const ecb_attribute ((__const__))
  901. #define ecb_pure ecb_attribute ((__pure__))
  902. #if ECB_C11 || __IBMC_NORETURN
  903. /* http://www-01.ibm.com/support/knowledgecenter/SSGH3R_13.1.0/com.ibm.xlcpp131.aix.doc/language_ref/noreturn.html */
  904. #define ecb_noreturn _Noreturn
  905. #elif ECB_CPP11
  906. #define ecb_noreturn [[noreturn]]
  907. #elif _MSC_VER >= 1200
  908. /* http://msdn.microsoft.com/en-us/library/k6ktzx3s.aspx */
  909. #define ecb_noreturn __declspec (noreturn)
  910. #else
  911. #define ecb_noreturn ecb_attribute ((__noreturn__))
  912. #endif
  913. #if ECB_GCC_VERSION(4,3)
  914. #define ecb_artificial ecb_attribute ((__artificial__))
  915. #define ecb_hot ecb_attribute ((__hot__))
  916. #define ecb_cold ecb_attribute ((__cold__))
  917. #else
  918. #define ecb_artificial
  919. #define ecb_hot
  920. #define ecb_cold
  921. #endif
  922. /* put around conditional expressions if you are very sure that the */
  923. /* expression is mostly true or mostly false. note that these return */
  924. /* booleans, not the expression. */
  925. #define ecb_expect_false(expr) ecb_expect (!!(expr), 0)
  926. #define ecb_expect_true(expr) ecb_expect (!!(expr), 1)
  927. /* for compatibility to the rest of the world */
  928. #define ecb_likely(expr) ecb_expect_true (expr)
  929. #define ecb_unlikely(expr) ecb_expect_false (expr)
  930. /* count trailing zero bits and count # of one bits */
  931. #if ECB_GCC_VERSION(3,4) \
  932. || (ECB_CLANG_BUILTIN(__builtin_clz) && ECB_CLANG_BUILTIN(__builtin_clzll) \
  933. && ECB_CLANG_BUILTIN(__builtin_ctz) && ECB_CLANG_BUILTIN(__builtin_ctzll) \
  934. && ECB_CLANG_BUILTIN(__builtin_popcount))
  935. /* we assume int == 32 bit, long == 32 or 64 bit and long long == 64 bit */
  936. #define ecb_ld32(x) (__builtin_clz (x) ^ 31)
  937. #define ecb_ld64(x) (__builtin_clzll (x) ^ 63)
  938. #define ecb_ctz32(x) __builtin_ctz (x)
  939. #define ecb_ctz64(x) __builtin_ctzll (x)
  940. #define ecb_popcount32(x) __builtin_popcount (x)
  941. /* no popcountll */
  942. #else
  943. ecb_function_ ecb_const int ecb_ctz32 (uint32_t x);
  944. ecb_function_ ecb_const int
  945. ecb_ctz32 (uint32_t x)
  946. {
  947. #if 1400 <= _MSC_VER && (_M_IX86 || _M_X64 || _M_IA64 || _M_ARM)
  948. unsigned long r;
  949. _BitScanForward (&r, x);
  950. return (int)r;
  951. #else
  952. int r = 0;
  953. x &= ~x + 1; /* this isolates the lowest bit */
  954. #if ECB_branchless_on_i386
  955. r += !!(x & 0xaaaaaaaa) << 0;
  956. r += !!(x & 0xcccccccc) << 1;
  957. r += !!(x & 0xf0f0f0f0) << 2;
  958. r += !!(x & 0xff00ff00) << 3;
  959. r += !!(x & 0xffff0000) << 4;
  960. #else
  961. if (x & 0xaaaaaaaa) r += 1;
  962. if (x & 0xcccccccc) r += 2;
  963. if (x & 0xf0f0f0f0) r += 4;
  964. if (x & 0xff00ff00) r += 8;
  965. if (x & 0xffff0000) r += 16;
  966. #endif
  967. return r;
  968. #endif
  969. }
  970. ecb_function_ ecb_const int ecb_ctz64 (uint64_t x);
  971. ecb_function_ ecb_const int
  972. ecb_ctz64 (uint64_t x)
  973. {
  974. #if 1400 <= _MSC_VER && (_M_X64 || _M_IA64 || _M_ARM)
  975. unsigned long r;
  976. _BitScanForward64 (&r, x);
  977. return (int)r;
  978. #else
  979. int shift = x & 0xffffffff ? 0 : 32;
  980. return ecb_ctz32 (x >> shift) + shift;
  981. #endif
  982. }
  983. ecb_function_ ecb_const int ecb_popcount32 (uint32_t x);
  984. ecb_function_ ecb_const int
  985. ecb_popcount32 (uint32_t x)
  986. {
  987. x -= (x >> 1) & 0x55555555;
  988. x = ((x >> 2) & 0x33333333) + (x & 0x33333333);
  989. x = ((x >> 4) + x) & 0x0f0f0f0f;
  990. x *= 0x01010101;
  991. return x >> 24;
  992. }
  993. ecb_function_ ecb_const int ecb_ld32 (uint32_t x);
  994. ecb_function_ ecb_const int ecb_ld32 (uint32_t x)
  995. {
  996. #if 1400 <= _MSC_VER && (_M_IX86 || _M_X64 || _M_IA64 || _M_ARM)
  997. unsigned long r;
  998. _BitScanReverse (&r, x);
  999. return (int)r;
  1000. #else
  1001. int r = 0;
  1002. if (x >> 16) { x >>= 16; r += 16; }
  1003. if (x >> 8) { x >>= 8; r += 8; }
  1004. if (x >> 4) { x >>= 4; r += 4; }
  1005. if (x >> 2) { x >>= 2; r += 2; }
  1006. if (x >> 1) { r += 1; }
  1007. return r;
  1008. #endif
  1009. }
  1010. ecb_function_ ecb_const int ecb_ld64 (uint64_t x);
  1011. ecb_function_ ecb_const int ecb_ld64 (uint64_t x)
  1012. {
  1013. #if 1400 <= _MSC_VER && (_M_X64 || _M_IA64 || _M_ARM)
  1014. unsigned long r;
  1015. _BitScanReverse64 (&r, x);
  1016. return (int)r;
  1017. #else
  1018. int r = 0;
  1019. if (x >> 32) { x >>= 32; r += 32; }
  1020. return r + ecb_ld32 (x);
  1021. #endif
  1022. }
  1023. #endif
  1024. ecb_function_ ecb_const ecb_bool ecb_is_pot32 (uint32_t x);
  1025. ecb_function_ ecb_const ecb_bool ecb_is_pot32 (uint32_t x) { return !(x & (x - 1)); }
  1026. ecb_function_ ecb_const ecb_bool ecb_is_pot64 (uint64_t x);
  1027. ecb_function_ ecb_const ecb_bool ecb_is_pot64 (uint64_t x) { return !(x & (x - 1)); }
  1028. ecb_function_ ecb_const uint8_t ecb_bitrev8 (uint8_t x);
  1029. ecb_function_ ecb_const uint8_t ecb_bitrev8 (uint8_t x)
  1030. {
  1031. return ( (x * 0x0802U & 0x22110U)
  1032. | (x * 0x8020U & 0x88440U)) * 0x10101U >> 16;
  1033. }
  1034. ecb_function_ ecb_const uint16_t ecb_bitrev16 (uint16_t x);
  1035. ecb_function_ ecb_const uint16_t ecb_bitrev16 (uint16_t x)
  1036. {
  1037. x = ((x >> 1) & 0x5555) | ((x & 0x5555) << 1);
  1038. x = ((x >> 2) & 0x3333) | ((x & 0x3333) << 2);
  1039. x = ((x >> 4) & 0x0f0f) | ((x & 0x0f0f) << 4);
  1040. x = ( x >> 8 ) | ( x << 8);
  1041. return x;
  1042. }
  1043. ecb_function_ ecb_const uint32_t ecb_bitrev32 (uint32_t x);
  1044. ecb_function_ ecb_const uint32_t ecb_bitrev32 (uint32_t x)
  1045. {
  1046. x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);
  1047. x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);
  1048. x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4);
  1049. x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8);
  1050. x = ( x >> 16 ) | ( x << 16);
  1051. return x;
  1052. }
  1053. /* popcount64 is only available on 64 bit cpus as gcc builtin */
  1054. /* so for this version we are lazy */
  1055. ecb_function_ ecb_const int ecb_popcount64 (uint64_t x);
  1056. ecb_function_ ecb_const int
  1057. ecb_popcount64 (uint64_t x)
  1058. {
  1059. return ecb_popcount32 (x) + ecb_popcount32 (x >> 32);
  1060. }
  1061. ecb_inline ecb_const uint8_t ecb_rotl8 (uint8_t x, unsigned int count);
  1062. ecb_inline ecb_const uint8_t ecb_rotr8 (uint8_t x, unsigned int count);
  1063. ecb_inline ecb_const uint16_t ecb_rotl16 (uint16_t x, unsigned int count);
  1064. ecb_inline ecb_const uint16_t ecb_rotr16 (uint16_t x, unsigned int count);
  1065. ecb_inline ecb_const uint32_t ecb_rotl32 (uint32_t x, unsigned int count);
  1066. ecb_inline ecb_const uint32_t ecb_rotr32 (uint32_t x, unsigned int count);
  1067. ecb_inline ecb_const uint64_t ecb_rotl64 (uint64_t x, unsigned int count);
  1068. ecb_inline ecb_const uint64_t ecb_rotr64 (uint64_t x, unsigned int count);
  1069. ecb_inline ecb_const uint8_t ecb_rotl8 (uint8_t x, unsigned int count) { return (x >> ( 8 - count)) | (x << count); }
  1070. ecb_inline ecb_const uint8_t ecb_rotr8 (uint8_t x, unsigned int count) { return (x << ( 8 - count)) | (x >> count); }
  1071. ecb_inline ecb_const uint16_t ecb_rotl16 (uint16_t x, unsigned int count) { return (x >> (16 - count)) | (x << count); }
  1072. ecb_inline ecb_const uint16_t ecb_rotr16 (uint16_t x, unsigned int count) { return (x << (16 - count)) | (x >> count); }
  1073. ecb_inline ecb_const uint32_t ecb_rotl32 (uint32_t x, unsigned int count) { return (x >> (32 - count)) | (x << count); }
  1074. ecb_inline ecb_const uint32_t ecb_rotr32 (uint32_t x, unsigned int count) { return (x << (32 - count)) | (x >> count); }
  1075. ecb_inline ecb_const uint64_t ecb_rotl64 (uint64_t x, unsigned int count) { return (x >> (64 - count)) | (x << count); }
  1076. ecb_inline ecb_const uint64_t ecb_rotr64 (uint64_t x, unsigned int count) { return (x << (64 - count)) | (x >> count); }
  1077. #if ECB_CPP
  1078. inline uint8_t ecb_ctz (uint8_t v) { return ecb_ctz32 (v); }
  1079. inline uint16_t ecb_ctz (uint16_t v) { return ecb_ctz32 (v); }
  1080. inline uint32_t ecb_ctz (uint32_t v) { return ecb_ctz32 (v); }
  1081. inline uint64_t ecb_ctz (uint64_t v) { return ecb_ctz64 (v); }
  1082. inline bool ecb_is_pot (uint8_t v) { return ecb_is_pot32 (v); }
  1083. inline bool ecb_is_pot (uint16_t v) { return ecb_is_pot32 (v); }
  1084. inline bool ecb_is_pot (uint32_t v) { return ecb_is_pot32 (v); }
  1085. inline bool ecb_is_pot (uint64_t v) { return ecb_is_pot64 (v); }
  1086. inline int ecb_ld (uint8_t v) { return ecb_ld32 (v); }
  1087. inline int ecb_ld (uint16_t v) { return ecb_ld32 (v); }
  1088. inline int ecb_ld (uint32_t v) { return ecb_ld32 (v); }
  1089. inline int ecb_ld (uint64_t v) { return ecb_ld64 (v); }
  1090. inline int ecb_popcount (uint8_t v) { return ecb_popcount32 (v); }
  1091. inline int ecb_popcount (uint16_t v) { return ecb_popcount32 (v); }
  1092. inline int ecb_popcount (uint32_t v) { return ecb_popcount32 (v); }
  1093. inline int ecb_popcount (uint64_t v) { return ecb_popcount64 (v); }
  1094. inline uint8_t ecb_bitrev (uint8_t v) { return ecb_bitrev8 (v); }
  1095. inline uint16_t ecb_bitrev (uint16_t v) { return ecb_bitrev16 (v); }
  1096. inline uint32_t ecb_bitrev (uint32_t v) { return ecb_bitrev32 (v); }
  1097. inline uint8_t ecb_rotl (uint8_t v, unsigned int count) { return ecb_rotl8 (v, count); }
  1098. inline uint16_t ecb_rotl (uint16_t v, unsigned int count) { return ecb_rotl16 (v, count); }
  1099. inline uint32_t ecb_rotl (uint32_t v, unsigned int count) { return ecb_rotl32 (v, count); }
  1100. inline uint64_t ecb_rotl (uint64_t v, unsigned int count) { return ecb_rotl64 (v, count); }
  1101. inline uint8_t ecb_rotr (uint8_t v, unsigned int count) { return ecb_rotr8 (v, count); }
  1102. inline uint16_t ecb_rotr (uint16_t v, unsigned int count) { return ecb_rotr16 (v, count); }
  1103. inline uint32_t ecb_rotr (uint32_t v, unsigned int count) { return ecb_rotr32 (v, count); }
  1104. inline uint64_t ecb_rotr (uint64_t v, unsigned int count) { return ecb_rotr64 (v, count); }
  1105. #endif
  1106. #if ECB_GCC_VERSION(4,3) || (ECB_CLANG_BUILTIN(__builtin_bswap32) && ECB_CLANG_BUILTIN(__builtin_bswap64))
  1107. #if ECB_GCC_VERSION(4,8) || ECB_CLANG_BUILTIN(__builtin_bswap16)
  1108. #define ecb_bswap16(x) __builtin_bswap16 (x)
  1109. #else
  1110. #define ecb_bswap16(x) (__builtin_bswap32 (x) >> 16)
  1111. #endif
  1112. #define ecb_bswap32(x) __builtin_bswap32 (x)
  1113. #define ecb_bswap64(x) __builtin_bswap64 (x)
  1114. #elif _MSC_VER
  1115. #include <stdlib.h>
  1116. #define ecb_bswap16(x) ((uint16_t)_byteswap_ushort ((uint16_t)(x)))
  1117. #define ecb_bswap32(x) ((uint32_t)_byteswap_ulong ((uint32_t)(x)))
  1118. #define ecb_bswap64(x) ((uint64_t)_byteswap_uint64 ((uint64_t)(x)))
  1119. #else
  1120. ecb_function_ ecb_const uint16_t ecb_bswap16 (uint16_t x);
  1121. ecb_function_ ecb_const uint16_t
  1122. ecb_bswap16 (uint16_t x)
  1123. {
  1124. return ecb_rotl16 (x, 8);
  1125. }
  1126. ecb_function_ ecb_const uint32_t ecb_bswap32 (uint32_t x);
  1127. ecb_function_ ecb_const uint32_t
  1128. ecb_bswap32 (uint32_t x)
  1129. {
  1130. return (((uint32_t)ecb_bswap16 (x)) << 16) | ecb_bswap16 (x >> 16);
  1131. }
  1132. ecb_function_ ecb_const uint64_t ecb_bswap64 (uint64_t x);
  1133. ecb_function_ ecb_const uint64_t
  1134. ecb_bswap64 (uint64_t x)
  1135. {
  1136. return (((uint64_t)ecb_bswap32 (x)) << 32) | ecb_bswap32 (x >> 32);
  1137. }
  1138. #endif
  1139. #if ECB_GCC_VERSION(4,5) || ECB_CLANG_BUILTIN(__builtin_unreachable)
  1140. #define ecb_unreachable() __builtin_unreachable ()
  1141. #else
  1142. /* this seems to work fine, but gcc always emits a warning for it :/ */
  1143. ecb_inline ecb_noreturn void ecb_unreachable (void);
  1144. ecb_inline ecb_noreturn void ecb_unreachable (void) { }
  1145. #endif
  1146. /* try to tell the compiler that some condition is definitely true */
  1147. #define ecb_assume(cond) if (!(cond)) ecb_unreachable (); else 0
  1148. ecb_inline ecb_const uint32_t ecb_byteorder_helper (void);
  1149. ecb_inline ecb_const uint32_t
  1150. ecb_byteorder_helper (void)
  1151. {
  1152. /* the union code still generates code under pressure in gcc, */
  1153. /* but less than using pointers, and always seems to */
  1154. /* successfully return a constant. */
  1155. /* the reason why we have this horrible preprocessor mess */
  1156. /* is to avoid it in all cases, at least on common architectures */
  1157. /* or when using a recent enough gcc version (>= 4.6) */
  1158. #if (defined __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) \
  1159. || ((__i386 || __i386__ || _M_IX86 || ECB_GCC_AMD64 || ECB_MSVC_AMD64) && !__VOS__)
  1160. #define ECB_LITTLE_ENDIAN 1
  1161. return 0x44332211;
  1162. #elif (defined __BYTE_ORDER__ && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) \
  1163. || ((__AARCH64EB__ || __MIPSEB__ || __ARMEB__) && !__VOS__)
  1164. #define ECB_BIG_ENDIAN 1
  1165. return 0x11223344;
  1166. #else
  1167. union
  1168. {
  1169. uint8_t c[4];
  1170. uint32_t u;
  1171. } u = { 0x11, 0x22, 0x33, 0x44 };
  1172. return u.u;
  1173. #endif
  1174. }
  1175. ecb_inline ecb_const ecb_bool ecb_big_endian (void);
  1176. ecb_inline ecb_const ecb_bool ecb_big_endian (void) { return ecb_byteorder_helper () == 0x11223344; }
  1177. ecb_inline ecb_const ecb_bool ecb_little_endian (void);
  1178. ecb_inline ecb_const ecb_bool ecb_little_endian (void) { return ecb_byteorder_helper () == 0x44332211; }
  1179. /*****************************************************************************/
  1180. /* unaligned load/store */
  1181. ecb_inline uint_fast16_t ecb_be_u16_to_host (uint_fast16_t v) { return ecb_little_endian () ? ecb_bswap16 (v) : v; }
  1182. ecb_inline uint_fast32_t ecb_be_u32_to_host (uint_fast32_t v) { return ecb_little_endian () ? ecb_bswap32 (v) : v; }
  1183. ecb_inline uint_fast64_t ecb_be_u64_to_host (uint_fast64_t v) { return ecb_little_endian () ? ecb_bswap64 (v) : v; }
  1184. ecb_inline uint_fast16_t ecb_le_u16_to_host (uint_fast16_t v) { return ecb_big_endian () ? ecb_bswap16 (v) : v; }
  1185. ecb_inline uint_fast32_t ecb_le_u32_to_host (uint_fast32_t v) { return ecb_big_endian () ? ecb_bswap32 (v) : v; }
  1186. ecb_inline uint_fast64_t ecb_le_u64_to_host (uint_fast64_t v) { return ecb_big_endian () ? ecb_bswap64 (v) : v; }
  1187. ecb_inline uint_fast16_t ecb_peek_u16_u (const void *ptr) { uint16_t v; memcpy (&v, ptr, sizeof (v)); return v; }
  1188. ecb_inline uint_fast32_t ecb_peek_u32_u (const void *ptr) { uint32_t v; memcpy (&v, ptr, sizeof (v)); return v; }
  1189. ecb_inline uint_fast64_t ecb_peek_u64_u (const void *ptr) { uint64_t v; memcpy (&v, ptr, sizeof (v)); return v; }
  1190. ecb_inline uint_fast16_t ecb_peek_be_u16_u (const void *ptr) { return ecb_be_u16_to_host (ecb_peek_u16_u (ptr)); }
  1191. ecb_inline uint_fast32_t ecb_peek_be_u32_u (const void *ptr) { return ecb_be_u32_to_host (ecb_peek_u32_u (ptr)); }
  1192. ecb_inline uint_fast64_t ecb_peek_be_u64_u (const void *ptr) { return ecb_be_u64_to_host (ecb_peek_u64_u (ptr)); }
  1193. ecb_inline uint_fast16_t ecb_peek_le_u16_u (const void *ptr) { return ecb_le_u16_to_host (ecb_peek_u16_u (ptr)); }
  1194. ecb_inline uint_fast32_t ecb_peek_le_u32_u (const void *ptr) { return ecb_le_u32_to_host (ecb_peek_u32_u (ptr)); }
  1195. ecb_inline uint_fast64_t ecb_peek_le_u64_u (const void *ptr) { return ecb_le_u64_to_host (ecb_peek_u64_u (ptr)); }
  1196. ecb_inline uint_fast16_t ecb_host_to_be_u16 (uint_fast16_t v) { return ecb_little_endian () ? ecb_bswap16 (v) : v; }
  1197. ecb_inline uint_fast32_t ecb_host_to_be_u32 (uint_fast32_t v) { return ecb_little_endian () ? ecb_bswap32 (v) : v; }
  1198. ecb_inline uint_fast64_t ecb_host_to_be_u64 (uint_fast64_t v) { return ecb_little_endian () ? ecb_bswap64 (v) : v; }
  1199. ecb_inline uint_fast16_t ecb_host_to_le_u16 (uint_fast16_t v) { return ecb_big_endian () ? ecb_bswap16 (v) : v; }
  1200. ecb_inline uint_fast32_t ecb_host_to_le_u32 (uint_fast32_t v) { return ecb_big_endian () ? ecb_bswap32 (v) : v; }
  1201. ecb_inline uint_fast64_t ecb_host_to_le_u64 (uint_fast64_t v) { return ecb_big_endian () ? ecb_bswap64 (v) : v; }
  1202. ecb_inline void ecb_poke_u16_u (void *ptr, uint16_t v) { memcpy (ptr, &v, sizeof (v)); }
  1203. ecb_inline void ecb_poke_u32_u (void *ptr, uint32_t v) { memcpy (ptr, &v, sizeof (v)); }
  1204. ecb_inline void ecb_poke_u64_u (void *ptr, uint64_t v) { memcpy (ptr, &v, sizeof (v)); }
  1205. ecb_inline void ecb_poke_be_u16_u (void *ptr, uint_fast16_t v) { ecb_poke_u16_u (ptr, ecb_host_to_be_u16 (v)); }
  1206. ecb_inline void ecb_poke_be_u32_u (void *ptr, uint_fast32_t v) { ecb_poke_u32_u (ptr, ecb_host_to_be_u32 (v)); }
  1207. ecb_inline void ecb_poke_be_u64_u (void *ptr, uint_fast64_t v) { ecb_poke_u64_u (ptr, ecb_host_to_be_u64 (v)); }
  1208. ecb_inline void ecb_poke_le_u16_u (void *ptr, uint_fast16_t v) { ecb_poke_u16_u (ptr, ecb_host_to_le_u16 (v)); }
  1209. ecb_inline void ecb_poke_le_u32_u (void *ptr, uint_fast32_t v) { ecb_poke_u32_u (ptr, ecb_host_to_le_u32 (v)); }
  1210. ecb_inline void ecb_poke_le_u64_u (void *ptr, uint_fast64_t v) { ecb_poke_u64_u (ptr, ecb_host_to_le_u64 (v)); }
  1211. #if ECB_CPP
  1212. inline uint8_t ecb_bswap (uint8_t v) { return v; }
  1213. inline uint16_t ecb_bswap (uint16_t v) { return ecb_bswap16 (v); }
  1214. inline uint32_t ecb_bswap (uint32_t v) { return ecb_bswap32 (v); }
  1215. inline uint64_t ecb_bswap (uint64_t v) { return ecb_bswap64 (v); }
  1216. template<typename T> inline T ecb_be_to_host (T v) { return ecb_little_endian () ? ecb_bswap (v) : v; }
  1217. template<typename T> inline T ecb_le_to_host (T v) { return ecb_big_endian () ? ecb_bswap (v) : v; }
  1218. template<typename T> inline T ecb_peek (const void *ptr) { return *(const T *)ptr; }
  1219. template<typename T> inline T ecb_peek_be (const void *ptr) { return ecb_be_to_host (ecb_peek <T> (ptr)); }
  1220. template<typename T> inline T ecb_peek_le (const void *ptr) { return ecb_le_to_host (ecb_peek <T> (ptr)); }
  1221. template<typename T> inline T ecb_peek_u (const void *ptr) { T v; memcpy (&v, ptr, sizeof (v)); return v; }
  1222. template<typename T> inline T ecb_peek_be_u (const void *ptr) { return ecb_be_to_host (ecb_peek_u<T> (ptr)); }
  1223. template<typename T> inline T ecb_peek_le_u (const void *ptr) { return ecb_le_to_host (ecb_peek_u<T> (ptr)); }
  1224. template<typename T> inline T ecb_host_to_be (T v) { return ecb_little_endian () ? ecb_bswap (v) : v; }
  1225. template<typename T> inline T ecb_host_to_le (T v) { return ecb_big_endian () ? ecb_bswap (v) : v; }
  1226. template<typename T> inline void ecb_poke (void *ptr, T v) { *(T *)ptr = v; }
  1227. template<typename T> inline void ecb_poke_be (void *ptr, T v) { return ecb_poke <T> (ptr, ecb_host_to_be (v)); }
  1228. template<typename T> inline void ecb_poke_le (void *ptr, T v) { return ecb_poke <T> (ptr, ecb_host_to_le (v)); }
  1229. template<typename T> inline void ecb_poke_u (void *ptr, T v) { memcpy (ptr, &v, sizeof (v)); }
  1230. template<typename T> inline void ecb_poke_be_u (void *ptr, T v) { return ecb_poke_u<T> (ptr, ecb_host_to_be (v)); }
  1231. template<typename T> inline void ecb_poke_le_u (void *ptr, T v) { return ecb_poke_u<T> (ptr, ecb_host_to_le (v)); }
  1232. #endif
  1233. /*****************************************************************************/
  1234. #if ECB_GCC_VERSION(3,0) || ECB_C99
  1235. #define ecb_mod(m,n) ((m) % (n) + ((m) % (n) < 0 ? (n) : 0))
  1236. #else
  1237. #define ecb_mod(m,n) ((m) < 0 ? ((n) - 1 - ((-1 - (m)) % (n))) : ((m) % (n)))
  1238. #endif
  1239. #if ECB_CPP
  1240. template<typename T>
  1241. static inline T ecb_div_rd (T val, T div)
  1242. {
  1243. return val < 0 ? - ((-val + div - 1) / div) : (val ) / div;
  1244. }
  1245. template<typename T>
  1246. static inline T ecb_div_ru (T val, T div)
  1247. {
  1248. return val < 0 ? - ((-val ) / div) : (val + div - 1) / div;
  1249. }
  1250. #else
  1251. #define ecb_div_rd(val,div) ((val) < 0 ? - ((-(val) + (div) - 1) / (div)) : ((val) ) / (div))
  1252. #define ecb_div_ru(val,div) ((val) < 0 ? - ((-(val) ) / (div)) : ((val) + (div) - 1) / (div))
  1253. #endif
  1254. #if ecb_cplusplus_does_not_suck
  1255. /* does not work for local types (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2657.htm) */
  1256. template<typename T, int N>
  1257. static inline int ecb_array_length (const T (&arr)[N])
  1258. {
  1259. return N;
  1260. }
  1261. #else
  1262. #define ecb_array_length(name) (sizeof (name) / sizeof (name [0]))
  1263. #endif
  1264. /*****************************************************************************/
  1265. ecb_function_ ecb_const uint32_t ecb_binary16_to_binary32 (uint32_t x);
  1266. ecb_function_ ecb_const uint32_t
  1267. ecb_binary16_to_binary32 (uint32_t x)
  1268. {
  1269. unsigned int s = (x & 0x8000) << (31 - 15);
  1270. int e = (x >> 10) & 0x001f;
  1271. unsigned int m = x & 0x03ff;
  1272. if (ecb_expect_false (e == 31))
  1273. /* infinity or NaN */
  1274. e = 255 - (127 - 15);
  1275. else if (ecb_expect_false (!e))
  1276. {
  1277. if (ecb_expect_true (!m))
  1278. /* zero, handled by code below by forcing e to 0 */
  1279. e = 0 - (127 - 15);
  1280. else
  1281. {
  1282. /* subnormal, renormalise */
  1283. unsigned int s = 10 - ecb_ld32 (m);
  1284. m = (m << s) & 0x3ff; /* mask implicit bit */
  1285. e -= s - 1;
  1286. }
  1287. }
  1288. /* e and m now are normalised, or zero, (or inf or nan) */
  1289. e += 127 - 15;
  1290. return s | (e << 23) | (m << (23 - 10));
  1291. }
  1292. ecb_function_ ecb_const uint16_t ecb_binary32_to_binary16 (uint32_t x);
  1293. ecb_function_ ecb_const uint16_t
  1294. ecb_binary32_to_binary16 (uint32_t x)
  1295. {
  1296. unsigned int s = (x >> 16) & 0x00008000; /* sign bit, the easy part */
  1297. unsigned int e = ((x >> 23) & 0x000000ff) - (127 - 15); /* the desired exponent */
  1298. unsigned int m = x & 0x007fffff;
  1299. x &= 0x7fffffff;
  1300. /* if it's within range of binary16 normals, use fast path */
  1301. if (ecb_expect_true (0x38800000 <= x && x <= 0x477fefff))
  1302. {
  1303. /* mantissa round-to-even */
  1304. m += 0x00000fff + ((m >> (23 - 10)) & 1);
  1305. /* handle overflow */
  1306. if (ecb_expect_false (m >= 0x00800000))
  1307. {
  1308. m >>= 1;
  1309. e += 1;
  1310. }
  1311. return s | (e << 10) | (m >> (23 - 10));
  1312. }
  1313. /* handle large numbers and infinity */
  1314. if (ecb_expect_true (0x477fefff < x && x <= 0x7f800000))
  1315. return s | 0x7c00;
  1316. /* handle zero, subnormals and small numbers */
  1317. if (ecb_expect_true (x < 0x38800000))
  1318. {
  1319. /* zero */
  1320. if (ecb_expect_true (!x))
  1321. return s;
  1322. /* handle subnormals */
  1323. /* too small, will be zero */
  1324. if (e < (14 - 24)) /* might not be sharp, but is good enough */
  1325. return s;
  1326. m |= 0x00800000; /* make implicit bit explicit */
  1327. /* very tricky - we need to round to the nearest e (+10) bit value */
  1328. {
  1329. unsigned int bits = 14 - e;
  1330. unsigned int half = (1 << (bits - 1)) - 1;
  1331. unsigned int even = (m >> bits) & 1;
  1332. /* if this overflows, we will end up with a normalised number */
  1333. m = (m + half + even) >> bits;
  1334. }
  1335. return s | m;
  1336. }
  1337. /* handle NaNs, preserve leftmost nan bits, but make sure we don't turn them into infinities */
  1338. m >>= 13;
  1339. return s | 0x7c00 | m | !m;
  1340. }
  1341. /*******************************************************************************/
  1342. /* floating point stuff, can be disabled by defining ECB_NO_LIBM */
  1343. /* basically, everything uses "ieee pure-endian" floating point numbers */
  1344. /* the only noteworthy exception is ancient armle, which uses order 43218765 */
  1345. #if 0 \
  1346. || __i386 || __i386__ \
  1347. || ECB_GCC_AMD64 \
  1348. || __powerpc__ || __ppc__ || __powerpc64__ || __ppc64__ \
  1349. || defined __s390__ || defined __s390x__ \
  1350. || defined __mips__ \
  1351. || defined __alpha__ \
  1352. || defined __hppa__ \
  1353. || defined __ia64__ \
  1354. || defined __m68k__ \
  1355. || defined __m88k__ \
  1356. || defined __sh__ \
  1357. || defined _M_IX86 || defined ECB_MSVC_AMD64 || defined _M_IA64 \
  1358. || (defined __arm__ && (defined __ARM_EABI__ || defined __EABI__ || defined __VFP_FP__ || defined _WIN32_WCE || defined __ANDROID__)) \
  1359. || defined __aarch64__
  1360. #define ECB_STDFP 1
  1361. #else
  1362. #define ECB_STDFP 0
  1363. #endif
  1364. #ifndef ECB_NO_LIBM
  1365. #include <math.h> /* for frexp*, ldexp*, INFINITY, NAN */
  1366. /* only the oldest of old doesn't have this one. solaris. */
  1367. #ifdef INFINITY
  1368. #define ECB_INFINITY INFINITY
  1369. #else
  1370. #define ECB_INFINITY HUGE_VAL
  1371. #endif
  1372. #ifdef NAN
  1373. #define ECB_NAN NAN
  1374. #else
  1375. #define ECB_NAN ECB_INFINITY
  1376. #endif
  1377. #if ECB_C99 || _XOPEN_VERSION >= 600 || _POSIX_VERSION >= 200112L
  1378. #define ecb_ldexpf(x,e) ldexpf ((x), (e))
  1379. #define ecb_frexpf(x,e) frexpf ((x), (e))
  1380. #else
  1381. #define ecb_ldexpf(x,e) (float) ldexp ((double) (x), (e))
  1382. #define ecb_frexpf(x,e) (float) frexp ((double) (x), (e))
  1383. #endif
  1384. /* convert a float to ieee single/binary32 */
  1385. ecb_function_ ecb_const uint32_t ecb_float_to_binary32 (float x);
  1386. ecb_function_ ecb_const uint32_t
  1387. ecb_float_to_binary32 (float x)
  1388. {
  1389. uint32_t r;
  1390. #if ECB_STDFP
  1391. memcpy (&r, &x, 4);
  1392. #else
  1393. /* slow emulation, works for anything but -0 */
  1394. uint32_t m;
  1395. int e;
  1396. if (x == 0e0f ) return 0x00000000U;
  1397. if (x > +3.40282346638528860e+38f) return 0x7f800000U;
  1398. if (x < -3.40282346638528860e+38f) return 0xff800000U;
  1399. if (x != x ) return 0x7fbfffffU;
  1400. m = ecb_frexpf (x, &e) * 0x1000000U;
  1401. r = m & 0x80000000U;
  1402. if (r)
  1403. m = -m;
  1404. if (e <= -126)
  1405. {
  1406. m &= 0xffffffU;
  1407. m >>= (-125 - e);
  1408. e = -126;
  1409. }
  1410. r |= (e + 126) << 23;
  1411. r |= m & 0x7fffffU;
  1412. #endif
  1413. return r;
  1414. }
  1415. /* converts an ieee single/binary32 to a float */
  1416. ecb_function_ ecb_const float ecb_binary32_to_float (uint32_t x);
  1417. ecb_function_ ecb_const float
  1418. ecb_binary32_to_float (uint32_t x)
  1419. {
  1420. float r;
  1421. #if ECB_STDFP
  1422. memcpy (&r, &x, 4);
  1423. #else
  1424. /* emulation, only works for normals and subnormals and +0 */
  1425. int neg = x >> 31;
  1426. int e = (x >> 23) & 0xffU;
  1427. x &= 0x7fffffU;
  1428. if (e)
  1429. x |= 0x800000U;
  1430. else
  1431. e = 1;
  1432. /* we distrust ldexpf a bit and do the 2**-24 scaling by an extra multiply */
  1433. r = ecb_ldexpf (x * (0.5f / 0x800000U), e - 126);
  1434. r = neg ? -r : r;
  1435. #endif
  1436. return r;
  1437. }
  1438. /* convert a double to ieee double/binary64 */
  1439. ecb_function_ ecb_const uint64_t ecb_double_to_binary64 (double x);
  1440. ecb_function_ ecb_const uint64_t
  1441. ecb_double_to_binary64 (double x)
  1442. {
  1443. uint64_t r;
  1444. #if ECB_STDFP
  1445. memcpy (&r, &x, 8);
  1446. #else
  1447. /* slow emulation, works for anything but -0 */
  1448. uint64_t m;
  1449. int e;
  1450. if (x == 0e0 ) return 0x0000000000000000U;
  1451. if (x > +1.79769313486231470e+308) return 0x7ff0000000000000U;
  1452. if (x < -1.79769313486231470e+308) return 0xfff0000000000000U;
  1453. if (x != x ) return 0X7ff7ffffffffffffU;
  1454. m = frexp (x, &e) * 0x20000000000000U;
  1455. r = m & 0x8000000000000000;;
  1456. if (r)
  1457. m = -m;
  1458. if (e <= -1022)
  1459. {
  1460. m &= 0x1fffffffffffffU;
  1461. m >>= (-1021 - e);
  1462. e = -1022;
  1463. }
  1464. r |= ((uint64_t)(e + 1022)) << 52;
  1465. r |= m & 0xfffffffffffffU;
  1466. #endif
  1467. return r;
  1468. }
  1469. /* converts an ieee double/binary64 to a double */
  1470. ecb_function_ ecb_const double ecb_binary64_to_double (uint64_t x);
  1471. ecb_function_ ecb_const double
  1472. ecb_binary64_to_double (uint64_t x)
  1473. {
  1474. double r;
  1475. #if ECB_STDFP
  1476. memcpy (&r, &x, 8);
  1477. #else
  1478. /* emulation, only works for normals and subnormals and +0 */
  1479. int neg = x >> 63;
  1480. int e = (x >> 52) & 0x7ffU;
  1481. x &= 0xfffffffffffffU;
  1482. if (e)
  1483. x |= 0x10000000000000U;
  1484. else
  1485. e = 1;
  1486. /* we distrust ldexp a bit and do the 2**-53 scaling by an extra multiply */
  1487. r = ldexp (x * (0.5 / 0x10000000000000U), e - 1022);
  1488. r = neg ? -r : r;
  1489. #endif
  1490. return r;
  1491. }
  1492. /* convert a float to ieee half/binary16 */
  1493. ecb_function_ ecb_const uint16_t ecb_float_to_binary16 (float x);
  1494. ecb_function_ ecb_const uint16_t
  1495. ecb_float_to_binary16 (float x)
  1496. {
  1497. return ecb_binary32_to_binary16 (ecb_float_to_binary32 (x));
  1498. }
  1499. /* convert an ieee half/binary16 to float */
  1500. ecb_function_ ecb_const float ecb_binary16_to_float (uint16_t x);
  1501. ecb_function_ ecb_const float
  1502. ecb_binary16_to_float (uint16_t x)
  1503. {
  1504. return ecb_binary32_to_float (ecb_binary16_to_binary32 (x));
  1505. }
  1506. #endif
  1507. #endif
  1508. /* ECB.H END */
  1509. #if ECB_MEMORY_FENCE_NEEDS_PTHREADS
  1510. /* if your architecture doesn't need memory fences, e.g. because it is
  1511. * single-cpu/core, or if you use libev in a project that doesn't use libev
  1512. * from multiple threads, then you can define ECB_NO_THREADS when compiling
  1513. * libev, in which cases the memory fences become nops.
  1514. * alternatively, you can remove this #error and link against libpthread,
  1515. * which will then provide the memory fences.
  1516. */
  1517. # error "memory fences not defined for your architecture, please report"
  1518. #endif
  1519. #ifndef ECB_MEMORY_FENCE
  1520. # define ECB_MEMORY_FENCE do { } while (0)
  1521. # define ECB_MEMORY_FENCE_ACQUIRE ECB_MEMORY_FENCE
  1522. # define ECB_MEMORY_FENCE_RELEASE ECB_MEMORY_FENCE
  1523. #endif
  1524. #define inline_size ecb_inline
  1525. #if EV_FEATURE_CODE
  1526. # define inline_speed ecb_inline
  1527. #else
  1528. # define inline_speed ecb_noinline static
  1529. #endif
  1530. /*****************************************************************************/
  1531. /* raw syscall wrappers */
  1532. #if EV_NEED_SYSCALL
  1533. #include <sys/syscall.h>
  1534. /*
  1535. * define some syscall wrappers for common architectures
  1536. * this is mostly for nice looks during debugging, not performance.
  1537. * our syscalls return < 0, not == -1, on error. which is good
  1538. * enough for linux aio.
  1539. * TODO: arm is also common nowadays, maybe even mips and x86
  1540. * TODO: after implementing this, it suddenly looks like overkill, but its hard to remove...
  1541. */
  1542. #if __GNUC__ && __linux && ECB_AMD64 && !EV_FEATURE_CODE
  1543. /* the costly errno access probably kills this for size optimisation */
  1544. #define ev_syscall(nr,narg,arg1,arg2,arg3,arg4,arg5,arg6) \
  1545. ({ \
  1546. long res; \
  1547. register unsigned long r6 __asm__ ("r9" ); \
  1548. register unsigned long r5 __asm__ ("r8" ); \
  1549. register unsigned long r4 __asm__ ("r10"); \
  1550. register unsigned long r3 __asm__ ("rdx"); \
  1551. register unsigned long r2 __asm__ ("rsi"); \
  1552. register unsigned long r1 __asm__ ("rdi"); \
  1553. if (narg >= 6) r6 = (unsigned long)(arg6); \
  1554. if (narg >= 5) r5 = (unsigned long)(arg5); \
  1555. if (narg >= 4) r4 = (unsigned long)(arg4); \
  1556. if (narg >= 3) r3 = (unsigned long)(arg3); \
  1557. if (narg >= 2) r2 = (unsigned long)(arg2); \
  1558. if (narg >= 1) r1 = (unsigned long)(arg1); \
  1559. __asm__ __volatile__ ( \
  1560. "syscall\n\t" \
  1561. : "=a" (res) \
  1562. : "0" (nr), "r" (r1), "r" (r2), "r" (r3), "r" (r4), "r" (r5) \
  1563. : "cc", "r11", "cx", "memory"); \
  1564. errno = -res; \
  1565. res; \
  1566. })
  1567. #endif
  1568. #ifdef ev_syscall
  1569. #define ev_syscall0(nr) ev_syscall (nr, 0, 0, 0, 0, 0, 0, 0)
  1570. #define ev_syscall1(nr,arg1) ev_syscall (nr, 1, arg1, 0, 0, 0, 0, 0)
  1571. #define ev_syscall2(nr,arg1,arg2) ev_syscall (nr, 2, arg1, arg2, 0, 0, 0, 0)
  1572. #define ev_syscall3(nr,arg1,arg2,arg3) ev_syscall (nr, 3, arg1, arg2, arg3, 0, 0, 0)
  1573. #define ev_syscall4(nr,arg1,arg2,arg3,arg4) ev_syscall (nr, 3, arg1, arg2, arg3, arg4, 0, 0)
  1574. #define ev_syscall5(nr,arg1,arg2,arg3,arg4,arg5) ev_syscall (nr, 5, arg1, arg2, arg3, arg4, arg5, 0)
  1575. #define ev_syscall6(nr,arg1,arg2,arg3,arg4,arg5,arg6) ev_syscall (nr, 6, arg1, arg2, arg3, arg4, arg5,arg6)
  1576. #else
  1577. #define ev_syscall0(nr) syscall (nr)
  1578. #define ev_syscall1(nr,arg1) syscall (nr, arg1)
  1579. #define ev_syscall2(nr,arg1,arg2) syscall (nr, arg1, arg2)
  1580. #define ev_syscall3(nr,arg1,arg2,arg3) syscall (nr, arg1, arg2, arg3)
  1581. #define ev_syscall4(nr,arg1,arg2,arg3,arg4) syscall (nr, arg1, arg2, arg3, arg4)
  1582. #define ev_syscall5(nr,arg1,arg2,arg3,arg4,arg5) syscall (nr, arg1, arg2, arg3, arg4, arg5)
  1583. #define ev_syscall6(nr,arg1,arg2,arg3,arg4,arg5,arg6) syscall (nr, arg1, arg2, arg3, arg4, arg5,arg6)
  1584. #endif
  1585. #endif
  1586. /*****************************************************************************/
  1587. #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
  1588. #if EV_MINPRI == EV_MAXPRI
  1589. # define ABSPRI(w) (((W)w), 0)
  1590. #else
  1591. # define ABSPRI(w) (((W)w)->priority - EV_MINPRI)
  1592. #endif
  1593. #define EMPTY /* required for microsofts broken pseudo-c compiler */
  1594. typedef ev_watcher *W;
  1595. typedef ev_watcher_list *WL;
  1596. typedef ev_watcher_time *WT;
  1597. #define ev_active(w) ((W)(w))->active
  1598. #define ev_at(w) ((WT)(w))->at
  1599. #if EV_USE_REALTIME
  1600. /* sig_atomic_t is used to avoid per-thread variables or locking but still */
  1601. /* giving it a reasonably high chance of working on typical architectures */
  1602. static EV_ATOMIC_T have_realtime; /* did clock_gettime (CLOCK_REALTIME) work? */
  1603. #endif
  1604. #if EV_USE_MONOTONIC
  1605. static EV_ATOMIC_T have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
  1606. static EV_ATOMIC_T monotinic_clock_id;
  1607. #endif
  1608. static EV_ATOMIC_T have_cheap_timer = 0;
  1609. #ifndef EV_FD_TO_WIN32_HANDLE
  1610. # define EV_FD_TO_WIN32_HANDLE(fd) _get_osfhandle (fd)
  1611. #endif
  1612. #ifndef EV_WIN32_HANDLE_TO_FD
  1613. # define EV_WIN32_HANDLE_TO_FD(handle) _open_osfhandle (handle, 0)
  1614. #endif
  1615. #ifndef EV_WIN32_CLOSE_FD
  1616. # define EV_WIN32_CLOSE_FD(fd) close (fd)
  1617. #endif
  1618. #ifdef _WIN32
  1619. # include "ev_win32.c"
  1620. #endif
  1621. /*****************************************************************************/
  1622. #if EV_USE_LINUXAIO
  1623. # include <linux/aio_abi.h> /* probably only needed for aio_context_t */
  1624. #endif
  1625. /* define a suitable floor function (only used by periodics atm) */
  1626. #if EV_USE_FLOOR
  1627. # include <math.h>
  1628. # define ev_floor(v) floor (v)
  1629. #else
  1630. #include <float.h>
  1631. /* a floor() replacement function, should be independent of ev_tstamp type */
  1632. ecb_noinline
  1633. static ev_tstamp
  1634. ev_floor (ev_tstamp v)
  1635. {
  1636. /* the choice of shift factor is not terribly important */
  1637. #if FLT_RADIX != 2 /* assume FLT_RADIX == 10 */
  1638. const ev_tstamp shift = sizeof (unsigned long) >= 8 ? 10000000000000000000. : 1000000000.;
  1639. #else
  1640. const ev_tstamp shift = sizeof (unsigned long) >= 8 ? 18446744073709551616. : 4294967296.;
  1641. #endif
  1642. /* special treatment for negative arguments */
  1643. if (ecb_expect_false (v < 0.))
  1644. {
  1645. ev_tstamp f = -ev_floor (-v);
  1646. return f - (f == v ? 0 : 1);
  1647. }
  1648. /* argument too large for an unsigned long? then reduce it */
  1649. if (ecb_expect_false (v >= shift))
  1650. {
  1651. ev_tstamp f;
  1652. if (v == v - 1.)
  1653. return v; /* very large numbers are assumed to be integer */
  1654. f = shift * ev_floor (v * (1. / shift));
  1655. return f + ev_floor (v - f);
  1656. }
  1657. /* fits into an unsigned long */
  1658. return (unsigned long)v;
  1659. }
  1660. #endif
  1661. /*****************************************************************************/
  1662. #ifdef __linux
  1663. # include <sys/utsname.h>
  1664. #endif
  1665. ecb_noinline ecb_cold
  1666. static unsigned int
  1667. ev_linux_version (void)
  1668. {
  1669. #ifdef __linux
  1670. unsigned int v = 0;
  1671. struct utsname buf;
  1672. int i;
  1673. char *p = buf.release;
  1674. if (uname (&buf))
  1675. return 0;
  1676. for (i = 3+1; --i; )
  1677. {
  1678. unsigned int c = 0;
  1679. for (;;)
  1680. {
  1681. if (*p >= '0' && *p <= '9')
  1682. c = c * 10 + *p++ - '0';
  1683. else
  1684. {
  1685. p += *p == '.';
  1686. break;
  1687. }
  1688. }
  1689. v = (v << 8) | c;
  1690. }
  1691. return v;
  1692. #else
  1693. return 0;
  1694. #endif
  1695. }
  1696. /*****************************************************************************/
  1697. #if EV_AVOID_STDIO
  1698. ecb_noinline ecb_cold
  1699. static void
  1700. ev_printerr (const char *msg)
  1701. {
  1702. write (STDERR_FILENO, msg, strlen (msg));
  1703. }
  1704. #endif
  1705. static void (*syserr_cb)(const char *msg) EV_NOEXCEPT;
  1706. ecb_cold
  1707. void
  1708. ev_set_syserr_cb (void (*cb)(const char *msg) EV_NOEXCEPT) EV_NOEXCEPT
  1709. {
  1710. syserr_cb = cb;
  1711. }
  1712. ecb_noinline ecb_cold
  1713. static void
  1714. ev_syserr (const char *msg)
  1715. {
  1716. if (!msg)
  1717. msg = "(libev) system error";
  1718. if (syserr_cb)
  1719. syserr_cb (msg);
  1720. else
  1721. {
  1722. #if EV_AVOID_STDIO
  1723. ev_printerr (msg);
  1724. ev_printerr (": ");
  1725. ev_printerr (strerror (errno));
  1726. ev_printerr ("\n");
  1727. #else
  1728. perror (msg);
  1729. #endif
  1730. abort ();
  1731. }
  1732. }
  1733. static void *
  1734. ev_realloc_emul (void *ptr, long size) EV_NOEXCEPT
  1735. {
  1736. /* some systems, notably openbsd and darwin, fail to properly
  1737. * implement realloc (x, 0) (as required by both ansi c-89 and
  1738. * the single unix specification, so work around them here.
  1739. * recently, also (at least) fedora and debian started breaking it,
  1740. * despite documenting it otherwise.
  1741. */
  1742. if (size)
  1743. return realloc (ptr, size);
  1744. free (ptr);
  1745. return 0;
  1746. }
  1747. static void *(*alloc)(void *ptr, long size) EV_NOEXCEPT = ev_realloc_emul;
  1748. ecb_cold
  1749. void
  1750. ev_set_allocator (void *(*cb)(void *ptr, long size) EV_NOEXCEPT) EV_NOEXCEPT
  1751. {
  1752. alloc = cb;
  1753. }
  1754. inline_speed void *
  1755. ev_realloc (void *ptr, long size)
  1756. {
  1757. ptr = alloc (ptr, size);
  1758. if (!ptr && size)
  1759. {
  1760. #if EV_AVOID_STDIO
  1761. ev_printerr ("(libev) memory allocation failed, aborting.\n");
  1762. #else
  1763. fprintf (stderr, "(libev) cannot allocate %ld bytes, aborting.", size);
  1764. #endif
  1765. abort ();
  1766. }
  1767. return ptr;
  1768. }
  1769. #define ev_malloc(size) ev_realloc (0, (size))
  1770. #define ev_free(ptr) ev_realloc ((ptr), 0)
  1771. /*****************************************************************************/
  1772. /* set in reify when reification needed */
  1773. #define EV_ANFD_REIFY 1
  1774. /* file descriptor info structure */
  1775. typedef struct
  1776. {
  1777. WL head;
  1778. unsigned char events; /* the events watched for */
  1779. unsigned char reify; /* flag set when this ANFD needs reification (EV_ANFD_REIFY, EV__IOFDSET) */
  1780. unsigned char emask; /* some backends store the actual kernel mask in here */
  1781. unsigned char eflags; /* flags field for use by backends */
  1782. #if EV_USE_EPOLL
  1783. unsigned int egen; /* generation counter to counter epoll bugs */
  1784. #endif
  1785. #if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP
  1786. SOCKET handle;
  1787. #endif
  1788. #if EV_USE_IOCP
  1789. OVERLAPPED or, ow;
  1790. #endif
  1791. } ANFD;
  1792. /* stores the pending event set for a given watcher */
  1793. typedef struct
  1794. {
  1795. W w;
  1796. int events; /* the pending event set for the given watcher */
  1797. } ANPENDING;
  1798. #if EV_USE_INOTIFY
  1799. /* hash table entry per inotify-id */
  1800. typedef struct
  1801. {
  1802. WL head;
  1803. } ANFS;
  1804. #endif
  1805. /* Heap Entry */
  1806. #if EV_HEAP_CACHE_AT
  1807. /* a heap element */
  1808. typedef struct {
  1809. ev_tstamp at;
  1810. WT w;
  1811. } ANHE;
  1812. #define ANHE_w(he) (he).w /* access watcher, read-write */
  1813. #define ANHE_at(he) (he).at /* access cached at, read-only */
  1814. #define ANHE_at_cache(he) (he).at = (he).w->at /* update at from watcher */
  1815. #else
  1816. /* a heap element */
  1817. typedef WT ANHE;
  1818. #define ANHE_w(he) (he)
  1819. #define ANHE_at(he) (he)->at
  1820. #define ANHE_at_cache(he)
  1821. #endif
  1822. #if EV_MULTIPLICITY
  1823. struct ev_loop
  1824. {
  1825. ev_tstamp ev_rt_now;
  1826. #define ev_rt_now ((loop)->ev_rt_now)
  1827. #define VAR(name,decl) decl;
  1828. #include "ev_vars.h"
  1829. #undef VAR
  1830. };
  1831. #include "ev_wrap.h"
  1832. static struct ev_loop default_loop_struct;
  1833. EV_API_DECL struct ev_loop *ev_default_loop_ptr = 0; /* needs to be initialised to make it a definition despite extern */
  1834. #else
  1835. EV_API_DECL ev_tstamp ev_rt_now = EV_TS_CONST (0.); /* needs to be initialised to make it a definition despite extern */
  1836. #define VAR(name,decl) static decl;
  1837. #include "ev_vars.h"
  1838. #undef VAR
  1839. static int ev_default_loop_ptr;
  1840. #endif
  1841. #if EV_FEATURE_API
  1842. # define EV_RELEASE_CB if (ecb_expect_false (release_cb)) release_cb (EV_A)
  1843. # define EV_ACQUIRE_CB if (ecb_expect_false (acquire_cb)) acquire_cb (EV_A)
  1844. # define EV_INVOKE_PENDING invoke_cb (EV_A)
  1845. #else
  1846. # define EV_RELEASE_CB (void)0
  1847. # define EV_ACQUIRE_CB (void)0
  1848. # define EV_INVOKE_PENDING ev_invoke_pending (EV_A)
  1849. #endif
  1850. #define EVBREAK_RECURSE 0x80
  1851. /*****************************************************************************/
  1852. #ifndef EV_HAVE_EV_TIME
  1853. ev_tstamp
  1854. ev_time (void) EV_NOEXCEPT
  1855. {
  1856. #if EV_USE_REALTIME
  1857. if (ecb_expect_true (have_realtime))
  1858. {
  1859. struct timespec ts;
  1860. clock_gettime (CLOCK_REALTIME, &ts);
  1861. return EV_TS_GET (ts);
  1862. }
  1863. #endif
  1864. {
  1865. struct timeval tv;
  1866. gettimeofday (&tv, 0);
  1867. return EV_TV_GET (tv);
  1868. }
  1869. }
  1870. #endif
  1871. inline_size ev_tstamp
  1872. get_clock (void)
  1873. {
  1874. #if EV_USE_MONOTONIC
  1875. if (ecb_expect_true (have_monotonic))
  1876. {
  1877. struct timespec ts;
  1878. clock_gettime (monotinic_clock_id, &ts);
  1879. return ((ev_tstamp)ts.tv_sec) + ts.tv_nsec * 1e-9;
  1880. }
  1881. #endif
  1882. return ev_time ();
  1883. }
  1884. #if EV_MULTIPLICITY
  1885. ev_tstamp
  1886. ev_now (EV_P) EV_NOEXCEPT
  1887. {
  1888. return ev_rt_now;
  1889. }
  1890. #endif
  1891. void
  1892. ev_sleep (ev_tstamp delay) EV_NOEXCEPT
  1893. {
  1894. if (delay > EV_TS_CONST (0.))
  1895. {
  1896. #if EV_USE_NANOSLEEP
  1897. struct timespec ts;
  1898. EV_TS_SET (ts, delay);
  1899. nanosleep (&ts, 0);
  1900. #elif defined _WIN32
  1901. /* maybe this should round up, as ms is very low resolution */
  1902. /* compared to select (µs) or nanosleep (ns) */
  1903. Sleep ((unsigned long)(EV_TS_TO_MSEC (delay)));
  1904. #else
  1905. struct timeval tv;
  1906. /* here we rely on sys/time.h + sys/types.h + unistd.h providing select */
  1907. /* something not guaranteed by newer posix versions, but guaranteed */
  1908. /* by older ones */
  1909. EV_TV_SET (tv, delay);
  1910. select (0, 0, 0, 0, &tv);
  1911. #endif
  1912. }
  1913. }
  1914. /*****************************************************************************/
  1915. #define MALLOC_ROUND 4096 /* prefer to allocate in chunks of this size, must be 2**n and >> 4 longs */
  1916. /* find a suitable new size for the given array, */
  1917. /* hopefully by rounding to a nice-to-malloc size */
  1918. inline_size int
  1919. array_nextsize (int elem, int cur, int cnt)
  1920. {
  1921. int ncur = cur + 1;
  1922. do
  1923. ncur <<= 1;
  1924. while (cnt > ncur);
  1925. /* if size is large, round to MALLOC_ROUND - 4 * longs to accommodate malloc overhead */
  1926. if (elem * ncur > MALLOC_ROUND - sizeof (void *) * 4)
  1927. {
  1928. ncur *= elem;
  1929. ncur = (ncur + elem + (MALLOC_ROUND - 1) + sizeof (void *) * 4) & ~(MALLOC_ROUND - 1);
  1930. ncur = ncur - sizeof (void *) * 4;
  1931. ncur /= elem;
  1932. }
  1933. return ncur;
  1934. }
  1935. ecb_noinline ecb_cold
  1936. static void *
  1937. array_realloc (int elem, void *base, int *cur, int cnt)
  1938. {
  1939. *cur = array_nextsize (elem, *cur, cnt);
  1940. return ev_realloc (base, elem * *cur);
  1941. }
  1942. #define array_needsize_noinit(base,offset,count)
  1943. #define array_needsize_zerofill(base,offset,count) \
  1944. memset ((void *)(base + offset), 0, sizeof (*(base)) * (count))
  1945. #define array_needsize(type,base,cur,cnt,init) \
  1946. if (ecb_expect_false ((cnt) > (cur))) \
  1947. { \
  1948. ecb_unused int ocur_ = (cur); \
  1949. (base) = (type *)array_realloc \
  1950. (sizeof (type), (base), &(cur), (cnt)); \
  1951. init ((base), ocur_, ((cur) - ocur_)); \
  1952. }
  1953. #if 0
  1954. #define array_slim(type,stem) \
  1955. if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
  1956. { \
  1957. stem ## max = array_roundsize (stem ## cnt >> 1); \
  1958. base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\
  1959. fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
  1960. }
  1961. #endif
  1962. #define array_free(stem, idx) \
  1963. ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0; stem ## s idx = 0
  1964. /*****************************************************************************/
  1965. /* dummy callback for pending events */
  1966. ecb_noinline
  1967. static void
  1968. pendingcb (EV_P_ ev_prepare *w, int revents)
  1969. {
  1970. }
  1971. ecb_noinline
  1972. void
  1973. ev_feed_event (EV_P_ void *w, int revents) EV_NOEXCEPT
  1974. {
  1975. W w_ = (W)w;
  1976. int pri = ABSPRI (w_);
  1977. if (ecb_expect_false (w_->pending))
  1978. pendings [pri][w_->pending - 1].events |= revents;
  1979. else
  1980. {
  1981. w_->pending = ++pendingcnt [pri];
  1982. array_needsize (ANPENDING, pendings [pri], pendingmax [pri], w_->pending, array_needsize_noinit);
  1983. pendings [pri][w_->pending - 1].w = w_;
  1984. pendings [pri][w_->pending - 1].events = revents;
  1985. }
  1986. pendingpri = NUMPRI - 1;
  1987. }
  1988. inline_speed void
  1989. feed_reverse (EV_P_ W w)
  1990. {
  1991. array_needsize (W, rfeeds, rfeedmax, rfeedcnt + 1, array_needsize_noinit);
  1992. rfeeds [rfeedcnt++] = w;
  1993. }
  1994. inline_size void
  1995. feed_reverse_done (EV_P_ int revents)
  1996. {
  1997. do
  1998. ev_feed_event (EV_A_ rfeeds [--rfeedcnt], revents);
  1999. while (rfeedcnt);
  2000. }
  2001. inline_speed void
  2002. queue_events (EV_P_ W *events, int eventcnt, int type)
  2003. {
  2004. int i;
  2005. for (i = 0; i < eventcnt; ++i)
  2006. ev_feed_event (EV_A_ events [i], type);
  2007. }
  2008. /*****************************************************************************/
  2009. inline_speed void
  2010. fd_event_nocheck (EV_P_ int fd, int revents)
  2011. {
  2012. ANFD *anfd = anfds + fd;
  2013. ev_io *w;
  2014. for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
  2015. {
  2016. int ev = w->events & revents;
  2017. if (ev)
  2018. ev_feed_event (EV_A_ (W)w, ev);
  2019. }
  2020. }
  2021. /* do not submit kernel events for fds that have reify set */
  2022. /* because that means they changed while we were polling for new events */
  2023. inline_speed void
  2024. fd_event (EV_P_ int fd, int revents)
  2025. {
  2026. ANFD *anfd = anfds + fd;
  2027. if (ecb_expect_true (!anfd->reify))
  2028. fd_event_nocheck (EV_A_ fd, revents);
  2029. }
  2030. void
  2031. ev_feed_fd_event (EV_P_ int fd, int revents) EV_NOEXCEPT
  2032. {
  2033. if (fd >= 0 && fd < anfdmax)
  2034. fd_event_nocheck (EV_A_ fd, revents);
  2035. }
  2036. /* make sure the external fd watch events are in-sync */
  2037. /* with the kernel/libev internal state */
  2038. inline_size void
  2039. fd_reify (EV_P)
  2040. {
  2041. int i;
  2042. /* most backends do not modify the fdchanges list in backend_modfiy.
  2043. * except io_uring, which has fixed-size buffers which might force us
  2044. * to handle events in backend_modify, causing fdchanges to be amended,
  2045. * which could result in an endless loop.
  2046. * to avoid this, we do not dynamically handle fds that were added
  2047. * during fd_reify. that means that for those backends, fdchangecnt
  2048. * might be non-zero during poll, which must cause them to not block.
  2049. * to not put too much of a burden on other backends, this detail
  2050. * needs to be handled in the backend.
  2051. */
  2052. int changecnt = fdchangecnt;
  2053. #if EV_SELECT_IS_WINSOCKET || EV_USE_IOCP
  2054. for (i = 0; i < changecnt; ++i)
  2055. {
  2056. int fd = fdchanges [i];
  2057. ANFD *anfd = anfds + fd;
  2058. if (anfd->reify & EV__IOFDSET && anfd->head)
  2059. {
  2060. SOCKET handle = EV_FD_TO_WIN32_HANDLE (fd);
  2061. if (handle != anfd->handle)
  2062. {
  2063. unsigned long arg;
  2064. assert (("libev: only socket fds supported in this configuration", ioctlsocket (handle, FIONREAD, &arg) == 0));
  2065. /* handle changed, but fd didn't - we need to do it in two steps */
  2066. backend_modify (EV_A_ fd, anfd->events, 0);
  2067. anfd->events = 0;
  2068. anfd->handle = handle;
  2069. }
  2070. }
  2071. }
  2072. #endif
  2073. for (i = 0; i < changecnt; ++i)
  2074. {
  2075. int fd = fdchanges [i];
  2076. ANFD *anfd = anfds + fd;
  2077. ev_io *w;
  2078. unsigned char o_events = anfd->events;
  2079. unsigned char o_reify = anfd->reify;
  2080. anfd->reify = 0;
  2081. /*if (ecb_expect_true (o_reify & EV_ANFD_REIFY)) probably a deoptimisation */
  2082. {
  2083. anfd->events = 0;
  2084. for (w = (ev_io *)anfd->head; w; w = (ev_io *)((WL)w)->next)
  2085. anfd->events |= (unsigned char)w->events;
  2086. if (o_events != anfd->events)
  2087. o_reify = EV__IOFDSET; /* actually |= */
  2088. }
  2089. if (o_reify & EV__IOFDSET)
  2090. backend_modify (EV_A_ fd, o_events, anfd->events);
  2091. }
  2092. /* normally, fdchangecnt hasn't changed. if it has, then new fds have been added.
  2093. * this is a rare case (see beginning comment in this function), so we copy them to the
  2094. * front and hope the backend handles this case.
  2095. */
  2096. if (ecb_expect_false (fdchangecnt != changecnt))
  2097. memmove (fdchanges, fdchanges + changecnt, (fdchangecnt - changecnt) * sizeof (*fdchanges));
  2098. fdchangecnt -= changecnt;
  2099. }
  2100. /* something about the given fd changed */
  2101. inline_size
  2102. void
  2103. fd_change (EV_P_ int fd, int flags)
  2104. {
  2105. unsigned char reify = anfds [fd].reify;
  2106. anfds [fd].reify = reify | flags;
  2107. if (ecb_expect_true (!reify))
  2108. {
  2109. ++fdchangecnt;
  2110. array_needsize (int, fdchanges, fdchangemax, fdchangecnt, array_needsize_noinit);
  2111. fdchanges [fdchangecnt - 1] = fd;
  2112. }
  2113. }
  2114. /* the given fd is invalid/unusable, so make sure it doesn't hurt us anymore */
  2115. inline_speed ecb_cold void
  2116. fd_kill (EV_P_ int fd)
  2117. {
  2118. ev_io *w;
  2119. while ((w = (ev_io *)anfds [fd].head))
  2120. {
  2121. ev_io_stop (EV_A_ w);
  2122. ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
  2123. }
  2124. }
  2125. /* check whether the given fd is actually valid, for error recovery */
  2126. inline_size ecb_cold int
  2127. fd_valid (int fd)
  2128. {
  2129. #ifdef _WIN32
  2130. return EV_FD_TO_WIN32_HANDLE (fd) != -1;
  2131. #else
  2132. return fcntl (fd, F_GETFD) != -1;
  2133. #endif
  2134. }
  2135. /* called on EBADF to verify fds */
  2136. ecb_noinline ecb_cold
  2137. static void
  2138. fd_ebadf (EV_P)
  2139. {
  2140. int fd;
  2141. for (fd = 0; fd < anfdmax; ++fd)
  2142. if (anfds [fd].events)
  2143. if (!fd_valid (fd) && errno == EBADF)
  2144. fd_kill (EV_A_ fd);
  2145. }
  2146. /* called on ENOMEM in select/poll to kill some fds and retry */
  2147. ecb_noinline ecb_cold
  2148. static void
  2149. fd_enomem (EV_P)
  2150. {
  2151. int fd;
  2152. for (fd = anfdmax; fd--; )
  2153. if (anfds [fd].events)
  2154. {
  2155. fd_kill (EV_A_ fd);
  2156. break;
  2157. }
  2158. }
  2159. /* usually called after fork if backend needs to re-arm all fds from scratch */
  2160. ecb_noinline
  2161. static void
  2162. fd_rearm_all (EV_P)
  2163. {
  2164. int fd;
  2165. for (fd = 0; fd < anfdmax; ++fd)
  2166. if (anfds [fd].events)
  2167. {
  2168. anfds [fd].events = 0;
  2169. anfds [fd].emask = 0;
  2170. fd_change (EV_A_ fd, EV__IOFDSET | EV_ANFD_REIFY);
  2171. }
  2172. }
  2173. /* used to prepare libev internal fd's */
  2174. /* this is not fork-safe */
  2175. inline_speed void
  2176. fd_intern (int fd)
  2177. {
  2178. #ifdef _WIN32
  2179. unsigned long arg = 1;
  2180. ioctlsocket (EV_FD_TO_WIN32_HANDLE (fd), FIONBIO, &arg);
  2181. #else
  2182. fcntl (fd, F_SETFD, FD_CLOEXEC);
  2183. fcntl (fd, F_SETFL, O_NONBLOCK);
  2184. #endif
  2185. }
  2186. /*****************************************************************************/
  2187. /*
  2188. * the heap functions want a real array index. array index 0 is guaranteed to not
  2189. * be in-use at any time. the first heap entry is at array [HEAP0]. DHEAP gives
  2190. * the branching factor of the d-tree.
  2191. */
  2192. /*
  2193. * at the moment we allow libev the luxury of two heaps,
  2194. * a small-code-size 2-heap one and a ~1.5kb larger 4-heap
  2195. * which is more cache-efficient.
  2196. * the difference is about 5% with 50000+ watchers.
  2197. */
  2198. #if EV_USE_4HEAP
  2199. #define DHEAP 4
  2200. #define HEAP0 (DHEAP - 1) /* index of first element in heap */
  2201. #define HPARENT(k) ((((k) - HEAP0 - 1) / DHEAP) + HEAP0)
  2202. #define UPHEAP_DONE(p,k) ((p) == (k))
  2203. /* away from the root */
  2204. inline_speed void
  2205. downheap (ANHE *heap, int N, int k)
  2206. {
  2207. ANHE he = heap [k];
  2208. ANHE *E = heap + N + HEAP0;
  2209. for (;;)
  2210. {
  2211. ev_tstamp minat;
  2212. ANHE *minpos;
  2213. ANHE *pos = heap + DHEAP * (k - HEAP0) + HEAP0 + 1;
  2214. /* find minimum child */
  2215. if (ecb_expect_true (pos + DHEAP - 1 < E))
  2216. {
  2217. /* fast path */ (minpos = pos + 0), (minat = ANHE_at (*minpos));
  2218. if ( minat > ANHE_at (pos [1])) (minpos = pos + 1), (minat = ANHE_at (*minpos));
  2219. if ( minat > ANHE_at (pos [2])) (minpos = pos + 2), (minat = ANHE_at (*minpos));
  2220. if ( minat > ANHE_at (pos [3])) (minpos = pos + 3), (minat = ANHE_at (*minpos));
  2221. }
  2222. else if (pos < E)
  2223. {
  2224. /* slow path */ (minpos = pos + 0), (minat = ANHE_at (*minpos));
  2225. if (pos + 1 < E && minat > ANHE_at (pos [1])) (minpos = pos + 1), (minat = ANHE_at (*minpos));
  2226. if (pos + 2 < E && minat > ANHE_at (pos [2])) (minpos = pos + 2), (minat = ANHE_at (*minpos));
  2227. if (pos + 3 < E && minat > ANHE_at (pos [3])) (minpos = pos + 3), (minat = ANHE_at (*minpos));
  2228. }
  2229. else
  2230. break;
  2231. if (ANHE_at (he) <= minat)
  2232. break;
  2233. heap [k] = *minpos;
  2234. ev_active (ANHE_w (*minpos)) = k;
  2235. k = minpos - heap;
  2236. }
  2237. heap [k] = he;
  2238. ev_active (ANHE_w (he)) = k;
  2239. }
  2240. #else /* not 4HEAP */
  2241. #define HEAP0 1
  2242. #define HPARENT(k) ((k) >> 1)
  2243. #define UPHEAP_DONE(p,k) (!(p))
  2244. /* away from the root */
  2245. inline_speed void
  2246. downheap (ANHE *heap, int N, int k)
  2247. {
  2248. ANHE he = heap [k];
  2249. for (;;)
  2250. {
  2251. int c = k << 1;
  2252. if (c >= N + HEAP0)
  2253. break;
  2254. c += c + 1 < N + HEAP0 && ANHE_at (heap [c]) > ANHE_at (heap [c + 1])
  2255. ? 1 : 0;
  2256. if (ANHE_at (he) <= ANHE_at (heap [c]))
  2257. break;
  2258. heap [k] = heap [c];
  2259. ev_active (ANHE_w (heap [k])) = k;
  2260. k = c;
  2261. }
  2262. heap [k] = he;
  2263. ev_active (ANHE_w (he)) = k;
  2264. }
  2265. #endif
  2266. /* towards the root */
  2267. inline_speed void
  2268. upheap (ANHE *heap, int k)
  2269. {
  2270. ANHE he = heap [k];
  2271. for (;;)
  2272. {
  2273. int p = HPARENT (k);
  2274. if (UPHEAP_DONE (p, k) || ANHE_at (heap [p]) <= ANHE_at (he))
  2275. break;
  2276. heap [k] = heap [p];
  2277. ev_active (ANHE_w (heap [k])) = k;
  2278. k = p;
  2279. }
  2280. heap [k] = he;
  2281. ev_active (ANHE_w (he)) = k;
  2282. }
  2283. /* move an element suitably so it is in a correct place */
  2284. inline_size void
  2285. adjustheap (ANHE *heap, int N, int k)
  2286. {
  2287. if (k > HEAP0 && ANHE_at (heap [k]) <= ANHE_at (heap [HPARENT (k)]))
  2288. upheap (heap, k);
  2289. else
  2290. downheap (heap, N, k);
  2291. }
  2292. /* rebuild the heap: this function is used only once and executed rarely */
  2293. inline_size void
  2294. reheap (ANHE *heap, int N)
  2295. {
  2296. int i;
  2297. /* we don't use floyds algorithm, upheap is simpler and is more cache-efficient */
  2298. /* also, this is easy to implement and correct for both 2-heaps and 4-heaps */
  2299. for (i = 0; i < N; ++i)
  2300. upheap (heap, i + HEAP0);
  2301. }
  2302. /*****************************************************************************/
  2303. /* associate signal watchers to a signal */
  2304. typedef struct
  2305. {
  2306. EV_ATOMIC_T pending;
  2307. #if EV_MULTIPLICITY
  2308. EV_P;
  2309. #endif
  2310. WL head;
  2311. } ANSIG;
  2312. static ANSIG signals [EV_NSIG - 1];
  2313. /*****************************************************************************/
  2314. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  2315. ecb_noinline ecb_cold
  2316. static void
  2317. evpipe_init (EV_P)
  2318. {
  2319. if (!ev_is_active (&pipe_w))
  2320. {
  2321. int fds [2];
  2322. # if EV_USE_EVENTFD
  2323. fds [0] = -1;
  2324. fds [1] = eventfd (0, EFD_NONBLOCK | EFD_CLOEXEC);
  2325. if (fds [1] < 0 && errno == EINVAL)
  2326. fds [1] = eventfd (0, 0);
  2327. if (fds [1] < 0)
  2328. # endif
  2329. {
  2330. while (pipe (fds))
  2331. ev_syserr ("(libev) error creating signal/async pipe");
  2332. fd_intern (fds [0]);
  2333. }
  2334. evpipe [0] = fds [0];
  2335. if (evpipe [1] < 0)
  2336. evpipe [1] = fds [1]; /* first call, set write fd */
  2337. else
  2338. {
  2339. /* on subsequent calls, do not change evpipe [1] */
  2340. /* so that evpipe_write can always rely on its value. */
  2341. /* this branch does not do anything sensible on windows, */
  2342. /* so must not be executed on windows */
  2343. dup2 (fds [1], evpipe [1]);
  2344. close (fds [1]);
  2345. }
  2346. fd_intern (evpipe [1]);
  2347. ev_io_set (&pipe_w, evpipe [0] < 0 ? evpipe [1] : evpipe [0], EV_READ);
  2348. ev_io_start (EV_A_ &pipe_w);
  2349. ev_unref (EV_A); /* watcher should not keep loop alive */
  2350. }
  2351. }
  2352. inline_speed void
  2353. evpipe_write (EV_P_ EV_ATOMIC_T *flag)
  2354. {
  2355. ECB_MEMORY_FENCE; /* push out the write before this function was called, acquire flag */
  2356. if (ecb_expect_true (*flag))
  2357. return;
  2358. *flag = 1;
  2359. ECB_MEMORY_FENCE_RELEASE; /* make sure flag is visible before the wakeup */
  2360. pipe_write_skipped = 1;
  2361. ECB_MEMORY_FENCE; /* make sure pipe_write_skipped is visible before we check pipe_write_wanted */
  2362. if (pipe_write_wanted)
  2363. {
  2364. int old_errno;
  2365. pipe_write_skipped = 0;
  2366. ECB_MEMORY_FENCE_RELEASE;
  2367. old_errno = errno; /* save errno because write will clobber it */
  2368. #if EV_USE_EVENTFD
  2369. if (evpipe [0] < 0)
  2370. {
  2371. uint64_t counter = 1;
  2372. write (evpipe [1], &counter, sizeof (uint64_t));
  2373. }
  2374. else
  2375. #endif
  2376. {
  2377. #ifdef _WIN32
  2378. WSABUF buf;
  2379. DWORD sent;
  2380. buf.buf = (char *)&buf;
  2381. buf.len = 1;
  2382. WSASend (EV_FD_TO_WIN32_HANDLE (evpipe [1]), &buf, 1, &sent, 0, 0, 0);
  2383. #else
  2384. write (evpipe [1], &(evpipe [1]), 1);
  2385. #endif
  2386. }
  2387. errno = old_errno;
  2388. }
  2389. }
  2390. /* called whenever the libev signal pipe */
  2391. /* got some events (signal, async) */
  2392. static void
  2393. pipecb (EV_P_ ev_io *iow, int revents)
  2394. {
  2395. int i;
  2396. if (revents & EV_READ)
  2397. {
  2398. #if EV_USE_EVENTFD
  2399. if (evpipe [0] < 0)
  2400. {
  2401. uint64_t counter;
  2402. read (evpipe [1], &counter, sizeof (uint64_t));
  2403. }
  2404. else
  2405. #endif
  2406. {
  2407. char dummy[4];
  2408. #ifdef _WIN32
  2409. WSABUF buf;
  2410. DWORD recvd;
  2411. DWORD flags = 0;
  2412. buf.buf = dummy;
  2413. buf.len = sizeof (dummy);
  2414. WSARecv (EV_FD_TO_WIN32_HANDLE (evpipe [0]), &buf, 1, &recvd, &flags, 0, 0);
  2415. #else
  2416. read (evpipe [0], &dummy, sizeof (dummy));
  2417. #endif
  2418. }
  2419. }
  2420. pipe_write_skipped = 0;
  2421. ECB_MEMORY_FENCE; /* push out skipped, acquire flags */
  2422. #if EV_SIGNAL_ENABLE
  2423. if (sig_pending)
  2424. {
  2425. sig_pending = 0;
  2426. ECB_MEMORY_FENCE;
  2427. for (i = EV_NSIG - 1; i--; )
  2428. if (ecb_expect_false (signals [i].pending))
  2429. ev_feed_signal_event (EV_A_ i + 1);
  2430. }
  2431. #endif
  2432. #if EV_ASYNC_ENABLE
  2433. if (async_pending)
  2434. {
  2435. async_pending = 0;
  2436. ECB_MEMORY_FENCE;
  2437. for (i = asynccnt; i--; )
  2438. if (asyncs [i]->sent)
  2439. {
  2440. asyncs [i]->sent = 0;
  2441. ECB_MEMORY_FENCE_RELEASE;
  2442. ev_feed_event (EV_A_ asyncs [i], EV_ASYNC);
  2443. }
  2444. }
  2445. #endif
  2446. }
  2447. /*****************************************************************************/
  2448. void
  2449. ev_feed_signal (int signum) EV_NOEXCEPT
  2450. {
  2451. #if EV_MULTIPLICITY
  2452. EV_P;
  2453. ECB_MEMORY_FENCE_ACQUIRE;
  2454. EV_A = signals [signum - 1].loop;
  2455. if (!EV_A)
  2456. return;
  2457. #endif
  2458. signals [signum - 1].pending = 1;
  2459. evpipe_write (EV_A_ &sig_pending);
  2460. }
  2461. static void
  2462. ev_sighandler (int signum)
  2463. {
  2464. #ifdef _WIN32
  2465. signal (signum, ev_sighandler);
  2466. #endif
  2467. ev_feed_signal (signum);
  2468. }
  2469. ecb_noinline
  2470. void
  2471. ev_feed_signal_event (EV_P_ int signum) EV_NOEXCEPT
  2472. {
  2473. WL w;
  2474. if (ecb_expect_false (signum <= 0 || signum >= EV_NSIG))
  2475. return;
  2476. --signum;
  2477. #if EV_MULTIPLICITY
  2478. /* it is permissible to try to feed a signal to the wrong loop */
  2479. /* or, likely more useful, feeding a signal nobody is waiting for */
  2480. if (ecb_expect_false (signals [signum].loop != EV_A))
  2481. return;
  2482. #endif
  2483. signals [signum].pending = 0;
  2484. ECB_MEMORY_FENCE_RELEASE;
  2485. for (w = signals [signum].head; w; w = w->next)
  2486. ev_feed_event (EV_A_ (W)w, EV_SIGNAL);
  2487. }
  2488. #if EV_USE_SIGNALFD
  2489. static void
  2490. sigfdcb (EV_P_ ev_io *iow, int revents)
  2491. {
  2492. struct signalfd_siginfo si[2], *sip; /* these structs are big */
  2493. for (;;)
  2494. {
  2495. ssize_t res = read (sigfd, si, sizeof (si));
  2496. /* not ISO-C, as res might be -1, but works with SuS */
  2497. for (sip = si; (char *)sip < (char *)si + res; ++sip)
  2498. ev_feed_signal_event (EV_A_ sip->ssi_signo);
  2499. if (res < (ssize_t)sizeof (si))
  2500. break;
  2501. }
  2502. }
  2503. #endif
  2504. #endif
  2505. /*****************************************************************************/
  2506. #if EV_CHILD_ENABLE
  2507. static WL childs [EV_PID_HASHSIZE];
  2508. static ev_signal childev;
  2509. #ifndef WIFCONTINUED
  2510. # define WIFCONTINUED(status) 0
  2511. #endif
  2512. /* handle a single child status event */
  2513. inline_speed void
  2514. child_reap (EV_P_ int chain, int pid, int status)
  2515. {
  2516. ev_child *w;
  2517. int traced = WIFSTOPPED (status) || WIFCONTINUED (status);
  2518. for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next)
  2519. {
  2520. if ((w->pid == pid || !w->pid)
  2521. && (!traced || (w->flags & 1)))
  2522. {
  2523. ev_set_priority (w, EV_MAXPRI); /* need to do it *now*, this *must* be the same prio as the signal watcher itself */
  2524. w->rpid = pid;
  2525. w->rstatus = status;
  2526. ev_feed_event (EV_A_ (W)w, EV_CHILD);
  2527. }
  2528. }
  2529. }
  2530. #ifndef WCONTINUED
  2531. # define WCONTINUED 0
  2532. #endif
  2533. /* called on sigchld etc., calls waitpid */
  2534. static void
  2535. childcb (EV_P_ ev_signal *sw, int revents)
  2536. {
  2537. int pid, status;
  2538. /* some systems define WCONTINUED but then fail to support it (linux 2.4) */
  2539. if (0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
  2540. if (!WCONTINUED
  2541. || errno != EINVAL
  2542. || 0 >= (pid = waitpid (-1, &status, WNOHANG | WUNTRACED)))
  2543. return;
  2544. /* make sure we are called again until all children have been reaped */
  2545. /* we need to do it this way so that the callback gets called before we continue */
  2546. ev_feed_event (EV_A_ (W)sw, EV_SIGNAL);
  2547. child_reap (EV_A_ pid, pid, status);
  2548. if ((EV_PID_HASHSIZE) > 1)
  2549. child_reap (EV_A_ 0, pid, status); /* this might trigger a watcher twice, but feed_event catches that */
  2550. }
  2551. #endif
  2552. /*****************************************************************************/
  2553. #if EV_USE_TIMERFD
  2554. static void periodics_reschedule (EV_P);
  2555. static void
  2556. timerfdcb (EV_P_ ev_io *iow, int revents)
  2557. {
  2558. struct itimerspec its = { 0 };
  2559. its.it_value.tv_sec = ev_rt_now + (int)MAX_BLOCKTIME2;
  2560. timerfd_settime (timerfd, TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET, &its, 0);
  2561. ev_rt_now = ev_time ();
  2562. /* periodics_reschedule only needs ev_rt_now */
  2563. /* but maybe in the future we want the full treatment. */
  2564. /*
  2565. now_floor = EV_TS_CONST (0.);
  2566. time_update (EV_A_ EV_TSTAMP_HUGE);
  2567. */
  2568. #if EV_PERIODIC_ENABLE
  2569. periodics_reschedule (EV_A);
  2570. #endif
  2571. }
  2572. ecb_noinline ecb_cold
  2573. static void
  2574. evtimerfd_init (EV_P)
  2575. {
  2576. if (!ev_is_active (&timerfd_w))
  2577. {
  2578. timerfd = timerfd_create (CLOCK_REALTIME, TFD_NONBLOCK | TFD_CLOEXEC);
  2579. if (timerfd >= 0)
  2580. {
  2581. fd_intern (timerfd); /* just to be sure */
  2582. ev_io_init (&timerfd_w, timerfdcb, timerfd, EV_READ);
  2583. ev_set_priority (&timerfd_w, EV_MINPRI);
  2584. ev_io_start (EV_A_ &timerfd_w);
  2585. ev_unref (EV_A); /* watcher should not keep loop alive */
  2586. /* (re-) arm timer */
  2587. timerfdcb (EV_A_ 0, 0);
  2588. }
  2589. }
  2590. }
  2591. #endif
  2592. /*****************************************************************************/
  2593. #if EV_USE_IOCP
  2594. # include "ev_iocp.c"
  2595. #endif
  2596. #if EV_USE_PORT
  2597. # include "ev_port.c"
  2598. #endif
  2599. #if EV_USE_KQUEUE
  2600. # include "ev_kqueue.c"
  2601. #endif
  2602. #if EV_USE_EPOLL
  2603. # include "ev_epoll.c"
  2604. #endif
  2605. #if EV_USE_LINUXAIO
  2606. # include "ev_linuxaio.c"
  2607. #endif
  2608. #if EV_USE_IOURING
  2609. # include "ev_iouring.c"
  2610. #endif
  2611. #if EV_USE_POLL
  2612. # include "ev_poll.c"
  2613. #endif
  2614. #if EV_USE_SELECT
  2615. # include "ev_select.c"
  2616. #endif
  2617. ecb_cold int
  2618. ev_version_major (void) EV_NOEXCEPT
  2619. {
  2620. return EV_VERSION_MAJOR;
  2621. }
  2622. ecb_cold int
  2623. ev_version_minor (void) EV_NOEXCEPT
  2624. {
  2625. return EV_VERSION_MINOR;
  2626. }
  2627. /* return true if we are running with elevated privileges and should ignore env variables */
  2628. inline_size ecb_cold int
  2629. enable_secure (void)
  2630. {
  2631. #ifdef _WIN32
  2632. return 0;
  2633. #else
  2634. return getuid () != geteuid ()
  2635. || getgid () != getegid ();
  2636. #endif
  2637. }
  2638. ecb_cold
  2639. unsigned int
  2640. ev_supported_backends (void) EV_NOEXCEPT
  2641. {
  2642. unsigned int flags = 0;
  2643. if (EV_USE_PORT ) flags |= EVBACKEND_PORT;
  2644. if (EV_USE_KQUEUE ) flags |= EVBACKEND_KQUEUE;
  2645. if (EV_USE_EPOLL ) flags |= EVBACKEND_EPOLL;
  2646. if (EV_USE_LINUXAIO ) flags |= EVBACKEND_LINUXAIO;
  2647. if (EV_USE_IOURING && ev_linux_version () >= 0x050601) flags |= EVBACKEND_IOURING; /* 5.6.1+ */
  2648. if (EV_USE_POLL ) flags |= EVBACKEND_POLL;
  2649. if (EV_USE_SELECT ) flags |= EVBACKEND_SELECT;
  2650. return flags;
  2651. }
  2652. ecb_cold
  2653. unsigned int
  2654. ev_recommended_backends (void) EV_NOEXCEPT
  2655. {
  2656. unsigned int flags = ev_supported_backends ();
  2657. #ifndef __NetBSD__
  2658. /* kqueue is borked on everything but netbsd apparently */
  2659. /* it usually doesn't work correctly on anything but sockets and pipes */
  2660. flags &= ~EVBACKEND_KQUEUE;
  2661. #endif
  2662. #ifdef __APPLE__
  2663. /* only select works correctly on that "unix-certified" platform */
  2664. flags &= ~EVBACKEND_KQUEUE; /* horribly broken, even for sockets */
  2665. flags &= ~EVBACKEND_POLL; /* poll is based on kqueue from 10.5 onwards */
  2666. #endif
  2667. #ifdef __FreeBSD__
  2668. flags &= ~EVBACKEND_POLL; /* poll return value is unusable (http://forums.freebsd.org/archive/index.php/t-10270.html) */
  2669. #endif
  2670. /* TODO: linuxaio is very experimental */
  2671. #if !EV_RECOMMEND_LINUXAIO
  2672. flags &= ~EVBACKEND_LINUXAIO;
  2673. #endif
  2674. /* TODO: linuxaio is super experimental */
  2675. #if !EV_RECOMMEND_IOURING
  2676. flags &= ~EVBACKEND_IOURING;
  2677. #endif
  2678. return flags;
  2679. }
  2680. ecb_cold
  2681. unsigned int
  2682. ev_embeddable_backends (void) EV_NOEXCEPT
  2683. {
  2684. int flags = EVBACKEND_EPOLL | EVBACKEND_KQUEUE | EVBACKEND_PORT | EVBACKEND_IOURING;
  2685. /* epoll embeddability broken on all linux versions up to at least 2.6.23 */
  2686. if (ev_linux_version () < 0x020620) /* disable it on linux < 2.6.32 */
  2687. flags &= ~EVBACKEND_EPOLL;
  2688. /* EVBACKEND_LINUXAIO is theoretically embeddable, but suffers from a performance overhead */
  2689. return flags;
  2690. }
  2691. unsigned int
  2692. ev_backend (EV_P) EV_NOEXCEPT
  2693. {
  2694. return backend;
  2695. }
  2696. #if EV_FEATURE_API
  2697. unsigned int
  2698. ev_iteration (EV_P) EV_NOEXCEPT
  2699. {
  2700. return loop_count;
  2701. }
  2702. unsigned int
  2703. ev_depth (EV_P) EV_NOEXCEPT
  2704. {
  2705. return loop_depth;
  2706. }
  2707. void
  2708. ev_set_io_collect_interval (EV_P_ ev_tstamp interval) EV_NOEXCEPT
  2709. {
  2710. io_blocktime = interval;
  2711. }
  2712. void
  2713. ev_set_timeout_collect_interval (EV_P_ ev_tstamp interval) EV_NOEXCEPT
  2714. {
  2715. timeout_blocktime = interval;
  2716. }
  2717. void
  2718. ev_set_userdata (EV_P_ void *data) EV_NOEXCEPT
  2719. {
  2720. userdata = data;
  2721. }
  2722. void *
  2723. ev_userdata (EV_P) EV_NOEXCEPT
  2724. {
  2725. return userdata;
  2726. }
  2727. void
  2728. ev_set_invoke_pending_cb (EV_P_ ev_loop_callback invoke_pending_cb) EV_NOEXCEPT
  2729. {
  2730. invoke_cb = invoke_pending_cb;
  2731. }
  2732. void
  2733. ev_set_loop_release_cb (EV_P_ void (*release)(EV_P) EV_NOEXCEPT, void (*acquire)(EV_P) EV_NOEXCEPT) EV_NOEXCEPT
  2734. {
  2735. release_cb = release;
  2736. acquire_cb = acquire;
  2737. }
  2738. #endif
  2739. /* initialise a loop structure, must be zero-initialised */
  2740. ecb_noinline ecb_cold
  2741. static void
  2742. loop_init (EV_P_ unsigned int flags) EV_NOEXCEPT
  2743. {
  2744. if (!backend)
  2745. {
  2746. origflags = flags;
  2747. #if EV_USE_REALTIME
  2748. if (!have_realtime)
  2749. {
  2750. struct timespec ts;
  2751. if (!clock_gettime (CLOCK_REALTIME, &ts))
  2752. have_realtime = 1;
  2753. }
  2754. #endif
  2755. #if EV_USE_MONOTONIC
  2756. if (!have_monotonic)
  2757. {
  2758. struct timespec ts;
  2759. if (!clock_gettime (CLOCK_MONOTONIC, &ts)) {
  2760. have_monotonic = 1;
  2761. monotinic_clock_id = CLOCK_MONOTONIC;
  2762. #define CHECK_CLOCK_SOURCE(id) do { \
  2763. if (!clock_gettime ((id), &ts) && \
  2764. !clock_getres ((id), &ts)) { \
  2765. if (ts.tv_sec == 0 && ts.tv_nsec < 10ULL * 1000000) { \
  2766. monotinic_clock_id = (id); \
  2767. have_cheap_timer = 1; \
  2768. } \
  2769. } \
  2770. } while(0)
  2771. #ifdef CLOCK_MONOTONIC_COARSE
  2772. CHECK_CLOCK_SOURCE(CLOCK_MONOTONIC_COARSE);
  2773. #elif defined(CLOCK_MONOTONIC_FAST) /* BSD stuff */
  2774. CHECK_CLOCK_SOURCE(CLOCK_MONOTONIC_FAST);
  2775. #elif defined(CLOCK_MONOTONIC_RAW_APPROX) /* OSX stuff */
  2776. CHECK_CLOCK_SOURCE(CLOCK_MONOTONIC_RAW_APPROX);
  2777. #endif
  2778. #undef CHECK_CLOCK_SOURCE
  2779. }
  2780. }
  2781. #endif
  2782. /* pid check not overridable via env */
  2783. #ifndef _WIN32
  2784. if (flags & EVFLAG_FORKCHECK)
  2785. curpid = getpid ();
  2786. #endif
  2787. if (!(flags & EVFLAG_NOENV)
  2788. && !enable_secure ()
  2789. && getenv ("LIBEV_FLAGS"))
  2790. flags = atoi (getenv ("LIBEV_FLAGS"));
  2791. ev_rt_now = ev_time ();
  2792. mn_now = get_clock ();
  2793. now_floor = mn_now;
  2794. rtmn_diff = ev_rt_now - mn_now;
  2795. #if EV_FEATURE_API
  2796. invoke_cb = ev_invoke_pending;
  2797. #endif
  2798. io_blocktime = 0.;
  2799. timeout_blocktime = 0.;
  2800. backend = 0;
  2801. backend_fd = -1;
  2802. sig_pending = 0;
  2803. #if EV_ASYNC_ENABLE
  2804. async_pending = 0;
  2805. #endif
  2806. pipe_write_skipped = 0;
  2807. pipe_write_wanted = 0;
  2808. evpipe [0] = -1;
  2809. evpipe [1] = -1;
  2810. #if EV_USE_INOTIFY
  2811. fs_fd = flags & EVFLAG_NOINOTIFY ? -1 : -2;
  2812. #endif
  2813. #if EV_USE_SIGNALFD
  2814. sigfd = flags & EVFLAG_SIGNALFD ? -2 : -1;
  2815. #endif
  2816. #if EV_USE_TIMERFD
  2817. timerfd = flags & EVFLAG_NOTIMERFD ? -1 : -2;
  2818. #endif
  2819. if (!(flags & EVBACKEND_MASK))
  2820. flags |= ev_recommended_backends ();
  2821. #if EV_USE_IOCP
  2822. if (!backend && (flags & EVBACKEND_IOCP )) backend = iocp_init (EV_A_ flags);
  2823. #endif
  2824. #if EV_USE_PORT
  2825. if (!backend && (flags & EVBACKEND_PORT )) backend = port_init (EV_A_ flags);
  2826. #endif
  2827. #if EV_USE_KQUEUE
  2828. if (!backend && (flags & EVBACKEND_KQUEUE )) backend = kqueue_init (EV_A_ flags);
  2829. #endif
  2830. #if EV_USE_IOURING
  2831. if (!backend && (flags & EVBACKEND_IOURING )) backend = iouring_init (EV_A_ flags);
  2832. #endif
  2833. #if EV_USE_LINUXAIO
  2834. if (!backend && (flags & EVBACKEND_LINUXAIO)) backend = linuxaio_init (EV_A_ flags);
  2835. #endif
  2836. #if EV_USE_EPOLL
  2837. if (!backend && (flags & EVBACKEND_EPOLL )) backend = epoll_init (EV_A_ flags);
  2838. #endif
  2839. #if EV_USE_POLL
  2840. if (!backend && (flags & EVBACKEND_POLL )) backend = poll_init (EV_A_ flags);
  2841. #endif
  2842. #if EV_USE_SELECT
  2843. if (!backend && (flags & EVBACKEND_SELECT )) backend = select_init (EV_A_ flags);
  2844. #endif
  2845. ev_prepare_init (&pending_w, pendingcb);
  2846. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  2847. ev_init (&pipe_w, pipecb);
  2848. ev_set_priority (&pipe_w, EV_MAXPRI);
  2849. #endif
  2850. }
  2851. }
  2852. EV_INLINE struct ev_loop *
  2853. ev_default_loop_uc_ (void) EV_NOEXCEPT
  2854. {
  2855. return ev_default_loop_ptr;
  2856. }
  2857. EV_INLINE int
  2858. ev_is_default_loop (EV_P) EV_NOEXCEPT
  2859. {
  2860. return EV_A == EV_DEFAULT_UC;
  2861. }
  2862. /* free up a loop structure */
  2863. ecb_cold
  2864. void
  2865. ev_loop_destroy (EV_P)
  2866. {
  2867. int i;
  2868. #if EV_MULTIPLICITY
  2869. /* mimic free (0) */
  2870. if (!EV_A)
  2871. return;
  2872. #endif
  2873. #if EV_CLEANUP_ENABLE
  2874. /* queue cleanup watchers (and execute them) */
  2875. if (ecb_expect_false (cleanupcnt))
  2876. {
  2877. queue_events (EV_A_ (W *)cleanups, cleanupcnt, EV_CLEANUP);
  2878. EV_INVOKE_PENDING;
  2879. }
  2880. #endif
  2881. #if EV_CHILD_ENABLE
  2882. if (ev_is_default_loop (EV_A) && ev_is_active (&childev))
  2883. {
  2884. ev_ref (EV_A); /* child watcher */
  2885. ev_signal_stop (EV_A_ &childev);
  2886. }
  2887. #endif
  2888. if (ev_is_active (&pipe_w))
  2889. {
  2890. /*ev_ref (EV_A);*/
  2891. /*ev_io_stop (EV_A_ &pipe_w);*/
  2892. if (evpipe [0] >= 0) EV_WIN32_CLOSE_FD (evpipe [0]);
  2893. if (evpipe [1] >= 0) EV_WIN32_CLOSE_FD (evpipe [1]);
  2894. }
  2895. #if EV_USE_SIGNALFD
  2896. if (ev_is_active (&sigfd_w))
  2897. close (sigfd);
  2898. #endif
  2899. #if EV_USE_TIMERFD
  2900. if (ev_is_active (&timerfd_w))
  2901. close (timerfd);
  2902. #endif
  2903. #if EV_USE_INOTIFY
  2904. if (fs_fd >= 0)
  2905. close (fs_fd);
  2906. #endif
  2907. if (backend_fd >= 0)
  2908. close (backend_fd);
  2909. #if EV_USE_IOCP
  2910. if (backend == EVBACKEND_IOCP ) iocp_destroy (EV_A);
  2911. #endif
  2912. #if EV_USE_PORT
  2913. if (backend == EVBACKEND_PORT ) port_destroy (EV_A);
  2914. #endif
  2915. #if EV_USE_KQUEUE
  2916. if (backend == EVBACKEND_KQUEUE ) kqueue_destroy (EV_A);
  2917. #endif
  2918. #if EV_USE_IOURING
  2919. if (backend == EVBACKEND_IOURING ) iouring_destroy (EV_A);
  2920. #endif
  2921. #if EV_USE_LINUXAIO
  2922. if (backend == EVBACKEND_LINUXAIO) linuxaio_destroy (EV_A);
  2923. #endif
  2924. #if EV_USE_EPOLL
  2925. if (backend == EVBACKEND_EPOLL ) epoll_destroy (EV_A);
  2926. #endif
  2927. #if EV_USE_POLL
  2928. if (backend == EVBACKEND_POLL ) poll_destroy (EV_A);
  2929. #endif
  2930. #if EV_USE_SELECT
  2931. if (backend == EVBACKEND_SELECT ) select_destroy (EV_A);
  2932. #endif
  2933. for (i = NUMPRI; i--; )
  2934. {
  2935. array_free (pending, [i]);
  2936. #if EV_IDLE_ENABLE
  2937. array_free (idle, [i]);
  2938. #endif
  2939. }
  2940. ev_free (anfds); anfds = 0; anfdmax = 0;
  2941. /* have to use the microsoft-never-gets-it-right macro */
  2942. array_free (rfeed, EMPTY);
  2943. array_free (fdchange, EMPTY);
  2944. array_free (timer, EMPTY);
  2945. #if EV_PERIODIC_ENABLE
  2946. array_free (periodic, EMPTY);
  2947. #endif
  2948. #if EV_FORK_ENABLE
  2949. array_free (fork, EMPTY);
  2950. #endif
  2951. #if EV_CLEANUP_ENABLE
  2952. array_free (cleanup, EMPTY);
  2953. #endif
  2954. array_free (prepare, EMPTY);
  2955. array_free (check, EMPTY);
  2956. #if EV_ASYNC_ENABLE
  2957. array_free (async, EMPTY);
  2958. #endif
  2959. backend = 0;
  2960. #if EV_MULTIPLICITY
  2961. if (ev_is_default_loop (EV_A))
  2962. #endif
  2963. ev_default_loop_ptr = 0;
  2964. #if EV_MULTIPLICITY
  2965. else
  2966. ev_free (EV_A);
  2967. #endif
  2968. }
  2969. #if EV_USE_INOTIFY
  2970. inline_size void infy_fork (EV_P);
  2971. #endif
  2972. inline_size void
  2973. loop_fork (EV_P)
  2974. {
  2975. #if EV_USE_PORT
  2976. if (backend == EVBACKEND_PORT ) port_fork (EV_A);
  2977. #endif
  2978. #if EV_USE_KQUEUE
  2979. if (backend == EVBACKEND_KQUEUE ) kqueue_fork (EV_A);
  2980. #endif
  2981. #if EV_USE_IOURING
  2982. if (backend == EVBACKEND_IOURING ) iouring_fork (EV_A);
  2983. #endif
  2984. #if EV_USE_LINUXAIO
  2985. if (backend == EVBACKEND_LINUXAIO) linuxaio_fork (EV_A);
  2986. #endif
  2987. #if EV_USE_EPOLL
  2988. if (backend == EVBACKEND_EPOLL ) epoll_fork (EV_A);
  2989. #endif
  2990. #if EV_USE_INOTIFY
  2991. infy_fork (EV_A);
  2992. #endif
  2993. if (postfork != 2)
  2994. {
  2995. #if EV_USE_SIGNALFD
  2996. /* surprisingly, nothing needs to be done for signalfd, accoridng to docs, it does the right thing on fork */
  2997. #endif
  2998. #if EV_USE_TIMERFD
  2999. if (ev_is_active (&timerfd_w))
  3000. {
  3001. ev_ref (EV_A);
  3002. ev_io_stop (EV_A_ &timerfd_w);
  3003. close (timerfd);
  3004. timerfd = -2;
  3005. evtimerfd_init (EV_A);
  3006. /* reschedule periodics, in case we missed something */
  3007. ev_feed_event (EV_A_ &timerfd_w, EV_CUSTOM);
  3008. }
  3009. #endif
  3010. #if EV_SIGNAL_ENABLE || EV_ASYNC_ENABLE
  3011. if (ev_is_active (&pipe_w))
  3012. {
  3013. /* pipe_write_wanted must be false now, so modifying fd vars should be safe */
  3014. ev_ref (EV_A);
  3015. ev_io_stop (EV_A_ &pipe_w);
  3016. if (evpipe [0] >= 0)
  3017. EV_WIN32_CLOSE_FD (evpipe [0]);
  3018. evpipe_init (EV_A);
  3019. /* iterate over everything, in case we missed something before */
  3020. ev_feed_event (EV_A_ &pipe_w, EV_CUSTOM);
  3021. }
  3022. #endif
  3023. }
  3024. postfork = 0;
  3025. }
  3026. #if EV_MULTIPLICITY
  3027. ecb_cold
  3028. struct ev_loop *
  3029. ev_loop_new (unsigned int flags) EV_NOEXCEPT
  3030. {
  3031. EV_P = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop));
  3032. memset (EV_A, 0, sizeof (struct ev_loop));
  3033. loop_init (EV_A_ flags);
  3034. if (ev_backend (EV_A))
  3035. return EV_A;
  3036. ev_free (EV_A);
  3037. return 0;
  3038. }
  3039. #endif /* multiplicity */
  3040. #if EV_VERIFY
  3041. ecb_noinline ecb_cold
  3042. static void
  3043. verify_watcher (EV_P_ W w)
  3044. {
  3045. assert (("libev: watcher has invalid priority", ABSPRI (w) >= 0 && ABSPRI (w) < NUMPRI));
  3046. if (w->pending)
  3047. assert (("libev: pending watcher not on pending queue", pendings [ABSPRI (w)][w->pending - 1].w == w));
  3048. }
  3049. ecb_noinline ecb_cold
  3050. static void
  3051. verify_heap (EV_P_ ANHE *heap, int N)
  3052. {
  3053. int i;
  3054. for (i = HEAP0; i < N + HEAP0; ++i)
  3055. {
  3056. assert (("libev: active index mismatch in heap", ev_active (ANHE_w (heap [i])) == i));
  3057. assert (("libev: heap condition violated", i == HEAP0 || ANHE_at (heap [HPARENT (i)]) <= ANHE_at (heap [i])));
  3058. assert (("libev: heap at cache mismatch", ANHE_at (heap [i]) == ev_at (ANHE_w (heap [i]))));
  3059. verify_watcher (EV_A_ (W)ANHE_w (heap [i]));
  3060. }
  3061. }
  3062. ecb_noinline ecb_cold
  3063. static void
  3064. array_verify (EV_P_ W *ws, int cnt)
  3065. {
  3066. while (cnt--)
  3067. {
  3068. assert (("libev: active index mismatch", ev_active (ws [cnt]) == cnt + 1));
  3069. verify_watcher (EV_A_ ws [cnt]);
  3070. }
  3071. }
  3072. #endif
  3073. #if EV_FEATURE_API
  3074. void ecb_cold
  3075. ev_verify (EV_P) EV_NOEXCEPT
  3076. {
  3077. #if EV_VERIFY
  3078. int i;
  3079. WL w, w2;
  3080. assert (activecnt >= -1);
  3081. assert (fdchangemax >= fdchangecnt);
  3082. for (i = 0; i < fdchangecnt; ++i)
  3083. assert (("libev: negative fd in fdchanges", fdchanges [i] >= 0));
  3084. assert (anfdmax >= 0);
  3085. for (i = 0; i < anfdmax; ++i)
  3086. {
  3087. int j = 0;
  3088. for (w = w2 = anfds [i].head; w; w = w->next)
  3089. {
  3090. verify_watcher (EV_A_ (W)w);
  3091. if (j++ & 1)
  3092. {
  3093. assert (("libev: io watcher list contains a loop", w != w2));
  3094. w2 = w2->next;
  3095. }
  3096. assert (("libev: inactive fd watcher on anfd list", ev_active (w) == 1));
  3097. assert (("libev: fd mismatch between watcher and anfd", ((ev_io *)w)->fd == i));
  3098. }
  3099. }
  3100. assert (timermax >= timercnt);
  3101. verify_heap (EV_A_ timers, timercnt);
  3102. #if EV_PERIODIC_ENABLE
  3103. assert (periodicmax >= periodiccnt);
  3104. verify_heap (EV_A_ periodics, periodiccnt);
  3105. #endif
  3106. for (i = NUMPRI; i--; )
  3107. {
  3108. assert (pendingmax [i] >= pendingcnt [i]);
  3109. #if EV_IDLE_ENABLE
  3110. assert (idleall >= 0);
  3111. assert (idlemax [i] >= idlecnt [i]);
  3112. array_verify (EV_A_ (W *)idles [i], idlecnt [i]);
  3113. #endif
  3114. }
  3115. #if EV_FORK_ENABLE
  3116. assert (forkmax >= forkcnt);
  3117. array_verify (EV_A_ (W *)forks, forkcnt);
  3118. #endif
  3119. #if EV_CLEANUP_ENABLE
  3120. assert (cleanupmax >= cleanupcnt);
  3121. array_verify (EV_A_ (W *)cleanups, cleanupcnt);
  3122. #endif
  3123. #if EV_ASYNC_ENABLE
  3124. assert (asyncmax >= asynccnt);
  3125. array_verify (EV_A_ (W *)asyncs, asynccnt);
  3126. #endif
  3127. #if EV_PREPARE_ENABLE
  3128. assert (preparemax >= preparecnt);
  3129. array_verify (EV_A_ (W *)prepares, preparecnt);
  3130. #endif
  3131. #if EV_CHECK_ENABLE
  3132. assert (checkmax >= checkcnt);
  3133. array_verify (EV_A_ (W *)checks, checkcnt);
  3134. #endif
  3135. # if 0
  3136. #if EV_CHILD_ENABLE
  3137. for (w = (ev_child *)childs [chain & ((EV_PID_HASHSIZE) - 1)]; w; w = (ev_child *)((WL)w)->next)
  3138. for (signum = EV_NSIG; signum--; ) if (signals [signum].pending)
  3139. #endif
  3140. # endif
  3141. #endif
  3142. }
  3143. #endif
  3144. #if EV_MULTIPLICITY
  3145. ecb_cold
  3146. struct ev_loop *
  3147. #else
  3148. int
  3149. #endif
  3150. ev_default_loop (unsigned int flags) EV_NOEXCEPT
  3151. {
  3152. if (!ev_default_loop_ptr)
  3153. {
  3154. #if EV_MULTIPLICITY
  3155. EV_P = ev_default_loop_ptr = &default_loop_struct;
  3156. #else
  3157. ev_default_loop_ptr = 1;
  3158. #endif
  3159. loop_init (EV_A_ flags);
  3160. if (ev_backend (EV_A))
  3161. {
  3162. #if EV_CHILD_ENABLE
  3163. ev_signal_init (&childev, childcb, SIGCHLD);
  3164. ev_set_priority (&childev, EV_MAXPRI);
  3165. ev_signal_start (EV_A_ &childev);
  3166. ev_unref (EV_A); /* child watcher should not keep loop alive */
  3167. #endif
  3168. }
  3169. else
  3170. ev_default_loop_ptr = 0;
  3171. }
  3172. return ev_default_loop_ptr;
  3173. }
  3174. void
  3175. ev_loop_fork (EV_P) EV_NOEXCEPT
  3176. {
  3177. postfork = 1;
  3178. }
  3179. /*****************************************************************************/
  3180. void
  3181. ev_invoke (EV_P_ void *w, int revents)
  3182. {
  3183. EV_CB_INVOKE ((W)w, revents);
  3184. }
  3185. unsigned int
  3186. ev_pending_count (EV_P) EV_NOEXCEPT
  3187. {
  3188. int pri;
  3189. unsigned int count = 0;
  3190. for (pri = NUMPRI; pri--; )
  3191. count += pendingcnt [pri];
  3192. return count;
  3193. }
  3194. ecb_noinline
  3195. void
  3196. ev_invoke_pending (EV_P)
  3197. {
  3198. pendingpri = NUMPRI;
  3199. do
  3200. {
  3201. --pendingpri;
  3202. /* pendingpri possibly gets modified in the inner loop */
  3203. while (pendingcnt [pendingpri])
  3204. {
  3205. ANPENDING *p = pendings [pendingpri] + --pendingcnt [pendingpri];
  3206. p->w->pending = 0;
  3207. EV_CB_INVOKE (p->w, p->events);
  3208. EV_FREQUENT_CHECK;
  3209. }
  3210. }
  3211. while (pendingpri);
  3212. }
  3213. #if EV_IDLE_ENABLE
  3214. /* make idle watchers pending. this handles the "call-idle */
  3215. /* only when higher priorities are idle" logic */
  3216. inline_size void
  3217. idle_reify (EV_P)
  3218. {
  3219. if (ecb_expect_false (idleall))
  3220. {
  3221. int pri;
  3222. for (pri = NUMPRI; pri--; )
  3223. {
  3224. if (pendingcnt [pri])
  3225. break;
  3226. if (idlecnt [pri])
  3227. {
  3228. queue_events (EV_A_ (W *)idles [pri], idlecnt [pri], EV_IDLE);
  3229. break;
  3230. }
  3231. }
  3232. }
  3233. }
  3234. #endif
  3235. /* make timers pending */
  3236. inline_size void
  3237. timers_reify (EV_P)
  3238. {
  3239. EV_FREQUENT_CHECK;
  3240. if (timercnt && ANHE_at (timers [HEAP0]) < mn_now)
  3241. {
  3242. do
  3243. {
  3244. ev_timer *w = (ev_timer *)ANHE_w (timers [HEAP0]);
  3245. /*assert (("libev: inactive timer on timer heap detected", ev_is_active (w)));*/
  3246. /* first reschedule or stop timer */
  3247. if (w->repeat)
  3248. {
  3249. ev_at (w) += w->repeat;
  3250. if (ev_at (w) < mn_now)
  3251. ev_at (w) = mn_now;
  3252. assert (("libev: negative ev_timer repeat value found while processing timers", w->repeat > EV_TS_CONST (0.)));
  3253. ANHE_at_cache (timers [HEAP0]);
  3254. downheap (timers, timercnt, HEAP0);
  3255. }
  3256. else
  3257. ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */
  3258. EV_FREQUENT_CHECK;
  3259. feed_reverse (EV_A_ (W)w);
  3260. }
  3261. while (timercnt && ANHE_at (timers [HEAP0]) < mn_now);
  3262. feed_reverse_done (EV_A_ EV_TIMER);
  3263. }
  3264. }
  3265. #if EV_PERIODIC_ENABLE
  3266. ecb_noinline
  3267. static void
  3268. periodic_recalc (EV_P_ ev_periodic *w)
  3269. {
  3270. ev_tstamp interval = w->interval > MIN_INTERVAL ? w->interval : MIN_INTERVAL;
  3271. ev_tstamp at = w->offset + interval * ev_floor ((ev_rt_now - w->offset) / interval);
  3272. /* the above almost always errs on the low side */
  3273. while (at <= ev_rt_now)
  3274. {
  3275. ev_tstamp nat = at + w->interval;
  3276. /* when resolution fails us, we use ev_rt_now */
  3277. if (ecb_expect_false (nat == at))
  3278. {
  3279. at = ev_rt_now;
  3280. break;
  3281. }
  3282. at = nat;
  3283. }
  3284. ev_at (w) = at;
  3285. }
  3286. /* make periodics pending */
  3287. inline_size void
  3288. periodics_reify (EV_P)
  3289. {
  3290. EV_FREQUENT_CHECK;
  3291. while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now)
  3292. {
  3293. do
  3294. {
  3295. ev_periodic *w = (ev_periodic *)ANHE_w (periodics [HEAP0]);
  3296. /*assert (("libev: inactive timer on periodic heap detected", ev_is_active (w)));*/
  3297. /* first reschedule or stop timer */
  3298. if (w->reschedule_cb)
  3299. {
  3300. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  3301. assert (("libev: ev_periodic reschedule callback returned time in the past", ev_at (w) >= ev_rt_now));
  3302. ANHE_at_cache (periodics [HEAP0]);
  3303. downheap (periodics, periodiccnt, HEAP0);
  3304. }
  3305. else if (w->interval)
  3306. {
  3307. periodic_recalc (EV_A_ w);
  3308. ANHE_at_cache (periodics [HEAP0]);
  3309. downheap (periodics, periodiccnt, HEAP0);
  3310. }
  3311. else
  3312. ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */
  3313. EV_FREQUENT_CHECK;
  3314. feed_reverse (EV_A_ (W)w);
  3315. }
  3316. while (periodiccnt && ANHE_at (periodics [HEAP0]) < ev_rt_now);
  3317. feed_reverse_done (EV_A_ EV_PERIODIC);
  3318. }
  3319. }
  3320. /* simply recalculate all periodics */
  3321. /* TODO: maybe ensure that at least one event happens when jumping forward? */
  3322. ecb_noinline ecb_cold
  3323. static void
  3324. periodics_reschedule (EV_P)
  3325. {
  3326. int i;
  3327. /* adjust periodics after time jump */
  3328. for (i = HEAP0; i < periodiccnt + HEAP0; ++i)
  3329. {
  3330. ev_periodic *w = (ev_periodic *)ANHE_w (periodics [i]);
  3331. if (w->reschedule_cb)
  3332. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  3333. else if (w->interval)
  3334. periodic_recalc (EV_A_ w);
  3335. ANHE_at_cache (periodics [i]);
  3336. }
  3337. reheap (periodics, periodiccnt);
  3338. }
  3339. #endif
  3340. /* adjust all timers by a given offset */
  3341. ecb_noinline ecb_cold
  3342. static void
  3343. timers_reschedule (EV_P_ ev_tstamp adjust)
  3344. {
  3345. int i;
  3346. for (i = 0; i < timercnt; ++i)
  3347. {
  3348. ANHE *he = timers + i + HEAP0;
  3349. ANHE_w (*he)->at += adjust;
  3350. ANHE_at_cache (*he);
  3351. }
  3352. }
  3353. /* fetch new monotonic and realtime times from the kernel */
  3354. /* also detect if there was a timejump, and act accordingly */
  3355. inline_speed void
  3356. time_update (EV_P_ ev_tstamp max_block)
  3357. {
  3358. #if EV_USE_MONOTONIC
  3359. if (ecb_expect_true (have_monotonic))
  3360. {
  3361. int i;
  3362. ev_tstamp odiff = rtmn_diff;
  3363. mn_now = get_clock ();
  3364. /* only fetch the realtime clock every 0.5*MIN_TIMEJUMP seconds */
  3365. /* interpolate in the meantime */
  3366. if (ecb_expect_true (mn_now - now_floor < EV_TS_CONST (MIN_TIMEJUMP * .5)))
  3367. {
  3368. ev_rt_now = rtmn_diff + mn_now;
  3369. return;
  3370. }
  3371. now_floor = mn_now;
  3372. ev_rt_now = ev_time ();
  3373. /* loop a few times, before making important decisions.
  3374. * on the choice of "4": one iteration isn't enough,
  3375. * in case we get preempted during the calls to
  3376. * ev_time and get_clock. a second call is almost guaranteed
  3377. * to succeed in that case, though. and looping a few more times
  3378. * doesn't hurt either as we only do this on time-jumps or
  3379. * in the unlikely event of having been preempted here.
  3380. */
  3381. for (i = 4; --i; )
  3382. {
  3383. ev_tstamp diff;
  3384. rtmn_diff = ev_rt_now - mn_now;
  3385. diff = odiff - rtmn_diff;
  3386. if (ecb_expect_true ((diff < EV_TS_CONST (0.) ? -diff : diff) < EV_TS_CONST (MIN_TIMEJUMP)))
  3387. return; /* all is well */
  3388. ev_rt_now = ev_time ();
  3389. mn_now = get_clock ();
  3390. now_floor = mn_now;
  3391. }
  3392. /* no timer adjustment, as the monotonic clock doesn't jump */
  3393. /* timers_reschedule (EV_A_ rtmn_diff - odiff) */
  3394. # if EV_PERIODIC_ENABLE
  3395. periodics_reschedule (EV_A);
  3396. # endif
  3397. }
  3398. else
  3399. #endif
  3400. {
  3401. ev_rt_now = ev_time ();
  3402. if (ecb_expect_false (mn_now > ev_rt_now || ev_rt_now > mn_now + max_block + EV_TS_CONST (MIN_TIMEJUMP)))
  3403. {
  3404. /* adjust timers. this is easy, as the offset is the same for all of them */
  3405. timers_reschedule (EV_A_ ev_rt_now - mn_now);
  3406. #if EV_PERIODIC_ENABLE
  3407. periodics_reschedule (EV_A);
  3408. #endif
  3409. }
  3410. mn_now = ev_rt_now;
  3411. }
  3412. }
  3413. int
  3414. ev_run (EV_P_ int flags)
  3415. {
  3416. #if EV_FEATURE_API
  3417. ++loop_depth;
  3418. #endif
  3419. assert (("libev: ev_loop recursion during release detected", loop_done != EVBREAK_RECURSE));
  3420. loop_done = EVBREAK_CANCEL;
  3421. EV_INVOKE_PENDING; /* in case we recurse, ensure ordering stays nice and clean */
  3422. do
  3423. {
  3424. #if EV_VERIFY >= 2
  3425. ev_verify (EV_A);
  3426. #endif
  3427. #ifndef _WIN32
  3428. if (ecb_expect_false (curpid)) /* penalise the forking check even more */
  3429. if (ecb_expect_false (getpid () != curpid))
  3430. {
  3431. curpid = getpid ();
  3432. postfork = 1;
  3433. }
  3434. #endif
  3435. #if EV_FORK_ENABLE
  3436. /* we might have forked, so queue fork handlers */
  3437. if (ecb_expect_false (postfork))
  3438. if (forkcnt)
  3439. {
  3440. queue_events (EV_A_ (W *)forks, forkcnt, EV_FORK);
  3441. EV_INVOKE_PENDING;
  3442. }
  3443. #endif
  3444. #if EV_PREPARE_ENABLE
  3445. /* queue prepare watchers (and execute them) */
  3446. if (ecb_expect_false (preparecnt))
  3447. {
  3448. queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE);
  3449. EV_INVOKE_PENDING;
  3450. }
  3451. #endif
  3452. if (ecb_expect_false (loop_done))
  3453. break;
  3454. /* we might have forked, so reify kernel state if necessary */
  3455. if (ecb_expect_false (postfork))
  3456. loop_fork (EV_A);
  3457. /* update fd-related kernel structures */
  3458. fd_reify (EV_A);
  3459. /* calculate blocking time */
  3460. {
  3461. ev_tstamp waittime = 0.;
  3462. ev_tstamp sleeptime = 0.;
  3463. /* remember old timestamp for io_blocktime calculation */
  3464. ev_tstamp prev_mn_now = mn_now;
  3465. /* update time to cancel out callback processing overhead */
  3466. time_update (EV_A_ EV_TS_CONST (EV_TSTAMP_HUGE));
  3467. /* from now on, we want a pipe-wake-up */
  3468. pipe_write_wanted = 1;
  3469. ECB_MEMORY_FENCE; /* make sure pipe_write_wanted is visible before we check for potential skips */
  3470. if (ecb_expect_true (!(flags & EVRUN_NOWAIT || idleall || !activecnt || pipe_write_skipped)))
  3471. {
  3472. waittime = EV_TS_CONST (MAX_BLOCKTIME);
  3473. #if EV_USE_TIMERFD
  3474. /* sleep a lot longer when we can reliably detect timejumps */
  3475. if (ecb_expect_true (timerfd >= 0))
  3476. waittime = EV_TS_CONST (MAX_BLOCKTIME2);
  3477. #endif
  3478. #if !EV_PERIODIC_ENABLE
  3479. /* without periodics but with monotonic clock there is no need */
  3480. /* for any time jump detection, so sleep longer */
  3481. if (ecb_expect_true (have_monotonic))
  3482. waittime = EV_TS_CONST (MAX_BLOCKTIME2);
  3483. #endif
  3484. if (timercnt)
  3485. {
  3486. ev_tstamp to = ANHE_at (timers [HEAP0]) - mn_now;
  3487. if (waittime > to) waittime = to;
  3488. }
  3489. #if EV_PERIODIC_ENABLE
  3490. if (periodiccnt)
  3491. {
  3492. ev_tstamp to = ANHE_at (periodics [HEAP0]) - ev_rt_now;
  3493. if (waittime > to) waittime = to;
  3494. }
  3495. #endif
  3496. /* don't let timeouts decrease the waittime below timeout_blocktime */
  3497. if (ecb_expect_false (waittime < timeout_blocktime))
  3498. waittime = timeout_blocktime;
  3499. /* now there are two more special cases left, either we have
  3500. * already-expired timers, so we should not sleep, or we have timers
  3501. * that expire very soon, in which case we need to wait for a minimum
  3502. * amount of time for some event loop backends.
  3503. */
  3504. if (ecb_expect_false (waittime < backend_mintime))
  3505. waittime = waittime <= EV_TS_CONST (0.)
  3506. ? EV_TS_CONST (0.)
  3507. : backend_mintime;
  3508. /* extra check because io_blocktime is commonly 0 */
  3509. if (ecb_expect_false (io_blocktime))
  3510. {
  3511. sleeptime = io_blocktime - (mn_now - prev_mn_now);
  3512. if (sleeptime > waittime - backend_mintime)
  3513. sleeptime = waittime - backend_mintime;
  3514. if (ecb_expect_true (sleeptime > EV_TS_CONST (0.)))
  3515. {
  3516. ev_sleep (sleeptime);
  3517. waittime -= sleeptime;
  3518. }
  3519. }
  3520. }
  3521. #if EV_FEATURE_API
  3522. ++loop_count;
  3523. #endif
  3524. assert ((loop_done = EVBREAK_RECURSE, 1)); /* assert for side effect */
  3525. backend_poll (EV_A_ waittime);
  3526. assert ((loop_done = EVBREAK_CANCEL, 1)); /* assert for side effect */
  3527. pipe_write_wanted = 0; /* just an optimisation, no fence needed */
  3528. ECB_MEMORY_FENCE_ACQUIRE;
  3529. if (pipe_write_skipped)
  3530. {
  3531. assert (("libev: pipe_w not active, but pipe not written", ev_is_active (&pipe_w)));
  3532. ev_feed_event (EV_A_ &pipe_w, EV_CUSTOM);
  3533. }
  3534. /* update ev_rt_now, do magic */
  3535. time_update (EV_A_ waittime + sleeptime);
  3536. }
  3537. /* queue pending timers and reschedule them */
  3538. timers_reify (EV_A); /* relative timers called last */
  3539. #if EV_PERIODIC_ENABLE
  3540. periodics_reify (EV_A); /* absolute timers called first */
  3541. #endif
  3542. #if EV_IDLE_ENABLE
  3543. /* queue idle watchers unless other events are pending */
  3544. idle_reify (EV_A);
  3545. #endif
  3546. #if EV_CHECK_ENABLE
  3547. /* queue check watchers, to be executed first */
  3548. if (ecb_expect_false (checkcnt))
  3549. queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK);
  3550. #endif
  3551. EV_INVOKE_PENDING;
  3552. }
  3553. while (ecb_expect_true (
  3554. activecnt
  3555. && !loop_done
  3556. && !(flags & (EVRUN_ONCE | EVRUN_NOWAIT))
  3557. ));
  3558. if (loop_done == EVBREAK_ONE)
  3559. loop_done = EVBREAK_CANCEL;
  3560. #if EV_FEATURE_API
  3561. --loop_depth;
  3562. #endif
  3563. return activecnt;
  3564. }
  3565. void
  3566. ev_break (EV_P_ int how) EV_NOEXCEPT
  3567. {
  3568. loop_done = how;
  3569. }
  3570. void
  3571. ev_ref (EV_P) EV_NOEXCEPT
  3572. {
  3573. ++activecnt;
  3574. }
  3575. void
  3576. ev_unref (EV_P) EV_NOEXCEPT
  3577. {
  3578. --activecnt;
  3579. }
  3580. void
  3581. ev_now_update (EV_P) EV_NOEXCEPT
  3582. {
  3583. time_update (EV_A_ EV_TSTAMP_HUGE);
  3584. }
  3585. void
  3586. ev_suspend (EV_P) EV_NOEXCEPT
  3587. {
  3588. ev_now_update (EV_A);
  3589. }
  3590. void
  3591. ev_resume (EV_P) EV_NOEXCEPT
  3592. {
  3593. ev_tstamp mn_prev = mn_now;
  3594. ev_now_update (EV_A);
  3595. timers_reschedule (EV_A_ mn_now - mn_prev);
  3596. #if EV_PERIODIC_ENABLE
  3597. /* TODO: really do this? */
  3598. periodics_reschedule (EV_A);
  3599. #endif
  3600. }
  3601. /*****************************************************************************/
  3602. /* singly-linked list management, used when the expected list length is short */
  3603. inline_size void
  3604. wlist_add (WL *head, WL elem)
  3605. {
  3606. elem->next = *head;
  3607. *head = elem;
  3608. }
  3609. inline_size void
  3610. wlist_del (WL *head, WL elem)
  3611. {
  3612. while (*head)
  3613. {
  3614. if (ecb_expect_true (*head == elem))
  3615. {
  3616. *head = elem->next;
  3617. break;
  3618. }
  3619. head = &(*head)->next;
  3620. }
  3621. }
  3622. /* internal, faster, version of ev_clear_pending */
  3623. inline_speed void
  3624. clear_pending (EV_P_ W w)
  3625. {
  3626. if (w->pending)
  3627. {
  3628. pendings [ABSPRI (w)][w->pending - 1].w = (W)&pending_w;
  3629. w->pending = 0;
  3630. }
  3631. }
  3632. int
  3633. ev_clear_pending (EV_P_ void *w) EV_NOEXCEPT
  3634. {
  3635. W w_ = (W)w;
  3636. int pending = w_->pending;
  3637. if (ecb_expect_true (pending))
  3638. {
  3639. ANPENDING *p = pendings [ABSPRI (w_)] + pending - 1;
  3640. p->w = (W)&pending_w;
  3641. w_->pending = 0;
  3642. return p->events;
  3643. }
  3644. else
  3645. return 0;
  3646. }
  3647. inline_size void
  3648. pri_adjust (EV_P_ W w)
  3649. {
  3650. int pri = ev_priority (w);
  3651. pri = pri < EV_MINPRI ? EV_MINPRI : pri;
  3652. pri = pri > EV_MAXPRI ? EV_MAXPRI : pri;
  3653. ev_set_priority (w, pri);
  3654. }
  3655. inline_speed void
  3656. ev_start (EV_P_ W w, int active)
  3657. {
  3658. pri_adjust (EV_A_ w);
  3659. w->active = active;
  3660. ev_ref (EV_A);
  3661. }
  3662. inline_size void
  3663. ev_stop (EV_P_ W w)
  3664. {
  3665. ev_unref (EV_A);
  3666. w->active = 0;
  3667. }
  3668. /*****************************************************************************/
  3669. ecb_noinline
  3670. void
  3671. ev_io_start (EV_P_ ev_io *w) EV_NOEXCEPT
  3672. {
  3673. int fd = w->fd;
  3674. if (ecb_expect_false (ev_is_active (w)))
  3675. return;
  3676. assert (("libev: ev_io_start called with negative fd", fd >= 0));
  3677. assert (("libev: ev_io_start called with illegal event mask", !(w->events & ~(EV__IOFDSET | EV_READ | EV_WRITE))));
  3678. #if EV_VERIFY >= 2
  3679. assert (("libev: ev_io_start called on watcher with invalid fd", fd_valid (fd)));
  3680. #endif
  3681. EV_FREQUENT_CHECK;
  3682. ev_start (EV_A_ (W)w, 1);
  3683. array_needsize (ANFD, anfds, anfdmax, fd + 1, array_needsize_zerofill);
  3684. wlist_add (&anfds[fd].head, (WL)w);
  3685. /* common bug, apparently */
  3686. assert (("libev: ev_io_start called with corrupted watcher", ((WL)w)->next != (WL)w));
  3687. fd_change (EV_A_ fd, w->events & EV__IOFDSET | EV_ANFD_REIFY);
  3688. w->events &= ~EV__IOFDSET;
  3689. EV_FREQUENT_CHECK;
  3690. }
  3691. ecb_noinline
  3692. void
  3693. ev_io_stop (EV_P_ ev_io *w) EV_NOEXCEPT
  3694. {
  3695. clear_pending (EV_A_ (W)w);
  3696. if (ecb_expect_false (!ev_is_active (w)))
  3697. return;
  3698. assert (("libev: ev_io_stop called with illegal fd (must stay constant after start!)", w->fd >= 0 && w->fd < anfdmax));
  3699. #if EV_VERIFY >= 2
  3700. assert (("libev: ev_io_stop called on watcher with invalid fd", fd_valid (w->fd)));
  3701. #endif
  3702. EV_FREQUENT_CHECK;
  3703. wlist_del (&anfds[w->fd].head, (WL)w);
  3704. ev_stop (EV_A_ (W)w);
  3705. fd_change (EV_A_ w->fd, EV_ANFD_REIFY);
  3706. EV_FREQUENT_CHECK;
  3707. }
  3708. ecb_noinline
  3709. void
  3710. ev_timer_start (EV_P_ ev_timer *w) EV_NOEXCEPT
  3711. {
  3712. if (ecb_expect_false (ev_is_active (w)))
  3713. return;
  3714. ev_at (w) += mn_now;
  3715. assert (("libev: ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
  3716. EV_FREQUENT_CHECK;
  3717. ++timercnt;
  3718. ev_start (EV_A_ (W)w, timercnt + HEAP0 - 1);
  3719. array_needsize (ANHE, timers, timermax, ev_active (w) + 1, array_needsize_noinit);
  3720. ANHE_w (timers [ev_active (w)]) = (WT)w;
  3721. ANHE_at_cache (timers [ev_active (w)]);
  3722. upheap (timers, ev_active (w));
  3723. EV_FREQUENT_CHECK;
  3724. /*assert (("libev: internal timer heap corruption", timers [ev_active (w)] == (WT)w));*/
  3725. }
  3726. ecb_noinline
  3727. void
  3728. ev_timer_stop (EV_P_ ev_timer *w) EV_NOEXCEPT
  3729. {
  3730. clear_pending (EV_A_ (W)w);
  3731. if (ecb_expect_false (!ev_is_active (w)))
  3732. return;
  3733. EV_FREQUENT_CHECK;
  3734. {
  3735. int active = ev_active (w);
  3736. assert (("libev: internal timer heap corruption", ANHE_w (timers [active]) == (WT)w));
  3737. --timercnt;
  3738. if (ecb_expect_true (active < timercnt + HEAP0))
  3739. {
  3740. timers [active] = timers [timercnt + HEAP0];
  3741. adjustheap (timers, timercnt, active);
  3742. }
  3743. }
  3744. ev_at (w) -= mn_now;
  3745. ev_stop (EV_A_ (W)w);
  3746. EV_FREQUENT_CHECK;
  3747. }
  3748. ecb_noinline
  3749. void
  3750. ev_timer_again (EV_P_ ev_timer *w) EV_NOEXCEPT
  3751. {
  3752. EV_FREQUENT_CHECK;
  3753. clear_pending (EV_A_ (W)w);
  3754. if (ev_is_active (w))
  3755. {
  3756. if (w->repeat)
  3757. {
  3758. ev_at (w) = mn_now + w->repeat;
  3759. ANHE_at_cache (timers [ev_active (w)]);
  3760. adjustheap (timers, timercnt, ev_active (w));
  3761. }
  3762. else
  3763. ev_timer_stop (EV_A_ w);
  3764. }
  3765. else if (w->repeat)
  3766. {
  3767. ev_at (w) = w->repeat;
  3768. ev_timer_start (EV_A_ w);
  3769. }
  3770. EV_FREQUENT_CHECK;
  3771. }
  3772. ev_tstamp
  3773. ev_timer_remaining (EV_P_ ev_timer *w) EV_NOEXCEPT
  3774. {
  3775. return ev_at (w) - (ev_is_active (w) ? mn_now : EV_TS_CONST (0.));
  3776. }
  3777. #if EV_PERIODIC_ENABLE
  3778. ecb_noinline
  3779. void
  3780. ev_periodic_start (EV_P_ ev_periodic *w) EV_NOEXCEPT
  3781. {
  3782. if (ecb_expect_false (ev_is_active (w)))
  3783. return;
  3784. #if EV_USE_TIMERFD
  3785. if (timerfd == -2)
  3786. evtimerfd_init (EV_A);
  3787. #endif
  3788. if (w->reschedule_cb)
  3789. ev_at (w) = w->reschedule_cb (w, ev_rt_now);
  3790. else if (w->interval)
  3791. {
  3792. assert (("libev: ev_periodic_start called with negative interval value", w->interval >= 0.));
  3793. periodic_recalc (EV_A_ w);
  3794. }
  3795. else
  3796. ev_at (w) = w->offset;
  3797. EV_FREQUENT_CHECK;
  3798. ++periodiccnt;
  3799. ev_start (EV_A_ (W)w, periodiccnt + HEAP0 - 1);
  3800. array_needsize (ANHE, periodics, periodicmax, ev_active (w) + 1, array_needsize_noinit);
  3801. ANHE_w (periodics [ev_active (w)]) = (WT)w;
  3802. ANHE_at_cache (periodics [ev_active (w)]);
  3803. upheap (periodics, ev_active (w));
  3804. EV_FREQUENT_CHECK;
  3805. /*assert (("libev: internal periodic heap corruption", ANHE_w (periodics [ev_active (w)]) == (WT)w));*/
  3806. }
  3807. ecb_noinline
  3808. void
  3809. ev_periodic_stop (EV_P_ ev_periodic *w) EV_NOEXCEPT
  3810. {
  3811. clear_pending (EV_A_ (W)w);
  3812. if (ecb_expect_false (!ev_is_active (w)))
  3813. return;
  3814. EV_FREQUENT_CHECK;
  3815. {
  3816. int active = ev_active (w);
  3817. assert (("libev: internal periodic heap corruption", ANHE_w (periodics [active]) == (WT)w));
  3818. --periodiccnt;
  3819. if (ecb_expect_true (active < periodiccnt + HEAP0))
  3820. {
  3821. periodics [active] = periodics [periodiccnt + HEAP0];
  3822. adjustheap (periodics, periodiccnt, active);
  3823. }
  3824. }
  3825. ev_stop (EV_A_ (W)w);
  3826. EV_FREQUENT_CHECK;
  3827. }
  3828. ecb_noinline
  3829. void
  3830. ev_periodic_again (EV_P_ ev_periodic *w) EV_NOEXCEPT
  3831. {
  3832. /* TODO: use adjustheap and recalculation */
  3833. ev_periodic_stop (EV_A_ w);
  3834. ev_periodic_start (EV_A_ w);
  3835. }
  3836. #endif
  3837. #ifndef SA_RESTART
  3838. # define SA_RESTART 0
  3839. #endif
  3840. #if EV_SIGNAL_ENABLE
  3841. ecb_noinline
  3842. void
  3843. ev_signal_start (EV_P_ ev_signal *w) EV_NOEXCEPT
  3844. {
  3845. if (ecb_expect_false (ev_is_active (w)))
  3846. return;
  3847. assert (("libev: ev_signal_start called with illegal signal number", w->signum > 0 && w->signum < EV_NSIG));
  3848. #if EV_MULTIPLICITY
  3849. assert (("libev: a signal must not be attached to two different loops",
  3850. !signals [w->signum - 1].loop || signals [w->signum - 1].loop == loop));
  3851. signals [w->signum - 1].loop = EV_A;
  3852. ECB_MEMORY_FENCE_RELEASE;
  3853. #endif
  3854. EV_FREQUENT_CHECK;
  3855. #if EV_USE_SIGNALFD
  3856. if (sigfd == -2)
  3857. {
  3858. sigfd = signalfd (-1, &sigfd_set, SFD_NONBLOCK | SFD_CLOEXEC);
  3859. if (sigfd < 0 && errno == EINVAL)
  3860. sigfd = signalfd (-1, &sigfd_set, 0); /* retry without flags */
  3861. if (sigfd >= 0)
  3862. {
  3863. fd_intern (sigfd); /* doing it twice will not hurt */
  3864. sigemptyset (&sigfd_set);
  3865. ev_io_init (&sigfd_w, sigfdcb, sigfd, EV_READ);
  3866. ev_set_priority (&sigfd_w, EV_MAXPRI);
  3867. ev_io_start (EV_A_ &sigfd_w);
  3868. ev_unref (EV_A); /* signalfd watcher should not keep loop alive */
  3869. }
  3870. }
  3871. if (sigfd >= 0)
  3872. {
  3873. /* TODO: check .head */
  3874. sigaddset (&sigfd_set, w->signum);
  3875. sigprocmask (SIG_BLOCK, &sigfd_set, 0);
  3876. signalfd (sigfd, &sigfd_set, 0);
  3877. }
  3878. #endif
  3879. ev_start (EV_A_ (W)w, 1);
  3880. wlist_add (&signals [w->signum - 1].head, (WL)w);
  3881. if (!((WL)w)->next)
  3882. # if EV_USE_SIGNALFD
  3883. if (sigfd < 0) /*TODO*/
  3884. # endif
  3885. {
  3886. # ifdef _WIN32
  3887. evpipe_init (EV_A);
  3888. signal (w->signum, ev_sighandler);
  3889. # else
  3890. struct sigaction sa;
  3891. evpipe_init (EV_A);
  3892. sa.sa_handler = ev_sighandler;
  3893. sigfillset (&sa.sa_mask);
  3894. sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */
  3895. sigaction (w->signum, &sa, 0);
  3896. if (origflags & EVFLAG_NOSIGMASK)
  3897. {
  3898. sigemptyset (&sa.sa_mask);
  3899. sigaddset (&sa.sa_mask, w->signum);
  3900. sigprocmask (SIG_UNBLOCK, &sa.sa_mask, 0);
  3901. }
  3902. #endif
  3903. }
  3904. EV_FREQUENT_CHECK;
  3905. }
  3906. ecb_noinline
  3907. void
  3908. ev_signal_stop (EV_P_ ev_signal *w) EV_NOEXCEPT
  3909. {
  3910. clear_pending (EV_A_ (W)w);
  3911. if (ecb_expect_false (!ev_is_active (w)))
  3912. return;
  3913. EV_FREQUENT_CHECK;
  3914. wlist_del (&signals [w->signum - 1].head, (WL)w);
  3915. ev_stop (EV_A_ (W)w);
  3916. if (!signals [w->signum - 1].head)
  3917. {
  3918. #if EV_MULTIPLICITY
  3919. signals [w->signum - 1].loop = 0; /* unattach from signal */
  3920. #endif
  3921. #if EV_USE_SIGNALFD
  3922. if (sigfd >= 0)
  3923. {
  3924. sigset_t ss;
  3925. sigemptyset (&ss);
  3926. sigaddset (&ss, w->signum);
  3927. sigdelset (&sigfd_set, w->signum);
  3928. signalfd (sigfd, &sigfd_set, 0);
  3929. sigprocmask (SIG_UNBLOCK, &ss, 0);
  3930. }
  3931. else
  3932. #endif
  3933. signal (w->signum, SIG_DFL);
  3934. }
  3935. EV_FREQUENT_CHECK;
  3936. }
  3937. #endif
  3938. #if EV_CHILD_ENABLE
  3939. void
  3940. ev_child_start (EV_P_ ev_child *w) EV_NOEXCEPT
  3941. {
  3942. #if EV_MULTIPLICITY
  3943. assert (("libev: child watchers are only supported in the default loop", loop == ev_default_loop_ptr));
  3944. #endif
  3945. if (ecb_expect_false (ev_is_active (w)))
  3946. return;
  3947. EV_FREQUENT_CHECK;
  3948. ev_start (EV_A_ (W)w, 1);
  3949. wlist_add (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w);
  3950. EV_FREQUENT_CHECK;
  3951. }
  3952. void
  3953. ev_child_stop (EV_P_ ev_child *w) EV_NOEXCEPT
  3954. {
  3955. clear_pending (EV_A_ (W)w);
  3956. if (ecb_expect_false (!ev_is_active (w)))
  3957. return;
  3958. EV_FREQUENT_CHECK;
  3959. wlist_del (&childs [w->pid & ((EV_PID_HASHSIZE) - 1)], (WL)w);
  3960. ev_stop (EV_A_ (W)w);
  3961. EV_FREQUENT_CHECK;
  3962. }
  3963. #endif
  3964. #if EV_STAT_ENABLE
  3965. # ifdef _WIN32
  3966. # undef lstat
  3967. # define lstat(a,b) _stati64 (a,b)
  3968. # endif
  3969. #define DEF_STAT_INTERVAL 5.0074891
  3970. #define NFS_STAT_INTERVAL 30.1074891 /* for filesystems potentially failing inotify */
  3971. #define MIN_STAT_INTERVAL 0.1074891
  3972. ecb_noinline static void stat_timer_cb (EV_P_ ev_timer *w_, int revents);
  3973. #if EV_USE_INOTIFY
  3974. /* the * 2 is to allow for alignment padding, which for some reason is >> 8 */
  3975. # define EV_INOTIFY_BUFSIZE (sizeof (struct inotify_event) * 2 + NAME_MAX)
  3976. ecb_noinline
  3977. static void
  3978. infy_add (EV_P_ ev_stat *w)
  3979. {
  3980. w->wd = inotify_add_watch (fs_fd, w->path,
  3981. IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF | IN_MODIFY
  3982. | IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO
  3983. | IN_DONT_FOLLOW | IN_MASK_ADD);
  3984. if (w->wd >= 0)
  3985. {
  3986. struct statfs sfs;
  3987. /* now local changes will be tracked by inotify, but remote changes won't */
  3988. /* unless the filesystem is known to be local, we therefore still poll */
  3989. /* also do poll on <2.6.25, but with normal frequency */
  3990. if (!fs_2625)
  3991. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  3992. else if (!statfs (w->path, &sfs)
  3993. && (sfs.f_type == 0x1373 /* devfs */
  3994. || sfs.f_type == 0x4006 /* fat */
  3995. || sfs.f_type == 0x4d44 /* msdos */
  3996. || sfs.f_type == 0xEF53 /* ext2/3 */
  3997. || sfs.f_type == 0x72b6 /* jffs2 */
  3998. || sfs.f_type == 0x858458f6 /* ramfs */
  3999. || sfs.f_type == 0x5346544e /* ntfs */
  4000. || sfs.f_type == 0x3153464a /* jfs */
  4001. || sfs.f_type == 0x9123683e /* btrfs */
  4002. || sfs.f_type == 0x52654973 /* reiser3 */
  4003. || sfs.f_type == 0x01021994 /* tmpfs */
  4004. || sfs.f_type == 0x58465342 /* xfs */))
  4005. w->timer.repeat = 0.; /* filesystem is local, kernel new enough */
  4006. else
  4007. w->timer.repeat = w->interval ? w->interval : NFS_STAT_INTERVAL; /* remote, use reduced frequency */
  4008. }
  4009. else
  4010. {
  4011. /* can't use inotify, continue to stat */
  4012. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  4013. /* if path is not there, monitor some parent directory for speedup hints */
  4014. /* note that exceeding the hardcoded path limit is not a correctness issue, */
  4015. /* but an efficiency issue only */
  4016. if ((errno == ENOENT || errno == EACCES) && strlen (w->path) < 4096)
  4017. {
  4018. char path [4096];
  4019. strcpy (path, w->path);
  4020. do
  4021. {
  4022. int mask = IN_MASK_ADD | IN_DELETE_SELF | IN_MOVE_SELF
  4023. | (errno == EACCES ? IN_ATTRIB : IN_CREATE | IN_MOVED_TO);
  4024. char *pend = strrchr (path, '/');
  4025. if (!pend || pend == path)
  4026. break;
  4027. *pend = 0;
  4028. w->wd = inotify_add_watch (fs_fd, path, mask);
  4029. }
  4030. while (w->wd < 0 && (errno == ENOENT || errno == EACCES));
  4031. }
  4032. }
  4033. if (w->wd >= 0)
  4034. wlist_add (&fs_hash [w->wd & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w);
  4035. /* now re-arm timer, if required */
  4036. if (ev_is_active (&w->timer)) ev_ref (EV_A);
  4037. ev_timer_again (EV_A_ &w->timer);
  4038. if (ev_is_active (&w->timer)) ev_unref (EV_A);
  4039. }
  4040. ecb_noinline
  4041. static void
  4042. infy_del (EV_P_ ev_stat *w)
  4043. {
  4044. int slot;
  4045. int wd = w->wd;
  4046. if (wd < 0)
  4047. return;
  4048. w->wd = -2;
  4049. slot = wd & ((EV_INOTIFY_HASHSIZE) - 1);
  4050. wlist_del (&fs_hash [slot].head, (WL)w);
  4051. /* remove this watcher, if others are watching it, they will rearm */
  4052. inotify_rm_watch (fs_fd, wd);
  4053. }
  4054. ecb_noinline
  4055. static void
  4056. infy_wd (EV_P_ int slot, int wd, struct inotify_event *ev)
  4057. {
  4058. if (slot < 0)
  4059. /* overflow, need to check for all hash slots */
  4060. for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot)
  4061. infy_wd (EV_A_ slot, wd, ev);
  4062. else
  4063. {
  4064. WL w_;
  4065. for (w_ = fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head; w_; )
  4066. {
  4067. ev_stat *w = (ev_stat *)w_;
  4068. w_ = w_->next; /* lets us remove this watcher and all before it */
  4069. if (w->wd == wd || wd == -1)
  4070. {
  4071. if (ev->mask & (IN_IGNORED | IN_UNMOUNT | IN_DELETE_SELF))
  4072. {
  4073. wlist_del (&fs_hash [slot & ((EV_INOTIFY_HASHSIZE) - 1)].head, (WL)w);
  4074. w->wd = -1;
  4075. infy_add (EV_A_ w); /* re-add, no matter what */
  4076. }
  4077. stat_timer_cb (EV_A_ &w->timer, 0);
  4078. }
  4079. }
  4080. }
  4081. }
  4082. static void
  4083. infy_cb (EV_P_ ev_io *w, int revents)
  4084. {
  4085. char buf [EV_INOTIFY_BUFSIZE];
  4086. int ofs;
  4087. int len = read (fs_fd, buf, sizeof (buf));
  4088. for (ofs = 0; ofs < len; )
  4089. {
  4090. struct inotify_event *ev = (struct inotify_event *)(buf + ofs);
  4091. infy_wd (EV_A_ ev->wd, ev->wd, ev);
  4092. ofs += sizeof (struct inotify_event) + ev->len;
  4093. }
  4094. }
  4095. inline_size ecb_cold
  4096. void
  4097. ev_check_2625 (EV_P)
  4098. {
  4099. /* kernels < 2.6.25 are borked
  4100. * http://www.ussg.indiana.edu/hypermail/linux/kernel/0711.3/1208.html
  4101. */
  4102. if (ev_linux_version () < 0x020619)
  4103. return;
  4104. fs_2625 = 1;
  4105. }
  4106. inline_size int
  4107. infy_newfd (void)
  4108. {
  4109. #if defined IN_CLOEXEC && defined IN_NONBLOCK
  4110. int fd = inotify_init1 (IN_CLOEXEC | IN_NONBLOCK);
  4111. if (fd >= 0)
  4112. return fd;
  4113. #endif
  4114. return inotify_init ();
  4115. }
  4116. inline_size void
  4117. infy_init (EV_P)
  4118. {
  4119. if (fs_fd != -2)
  4120. return;
  4121. fs_fd = -1;
  4122. ev_check_2625 (EV_A);
  4123. fs_fd = infy_newfd ();
  4124. if (fs_fd >= 0)
  4125. {
  4126. fd_intern (fs_fd);
  4127. ev_io_init (&fs_w, infy_cb, fs_fd, EV_READ);
  4128. ev_set_priority (&fs_w, EV_MAXPRI);
  4129. ev_io_start (EV_A_ &fs_w);
  4130. ev_unref (EV_A);
  4131. }
  4132. }
  4133. inline_size void
  4134. infy_fork (EV_P)
  4135. {
  4136. int slot;
  4137. if (fs_fd < 0)
  4138. return;
  4139. ev_ref (EV_A);
  4140. ev_io_stop (EV_A_ &fs_w);
  4141. close (fs_fd);
  4142. fs_fd = infy_newfd ();
  4143. if (fs_fd >= 0)
  4144. {
  4145. fd_intern (fs_fd);
  4146. ev_io_set (&fs_w, fs_fd, EV_READ);
  4147. ev_io_start (EV_A_ &fs_w);
  4148. ev_unref (EV_A);
  4149. }
  4150. for (slot = 0; slot < (EV_INOTIFY_HASHSIZE); ++slot)
  4151. {
  4152. WL w_ = fs_hash [slot].head;
  4153. fs_hash [slot].head = 0;
  4154. while (w_)
  4155. {
  4156. ev_stat *w = (ev_stat *)w_;
  4157. w_ = w_->next; /* lets us add this watcher */
  4158. w->wd = -1;
  4159. if (fs_fd >= 0)
  4160. infy_add (EV_A_ w); /* re-add, no matter what */
  4161. else
  4162. {
  4163. w->timer.repeat = w->interval ? w->interval : DEF_STAT_INTERVAL;
  4164. if (ev_is_active (&w->timer)) ev_ref (EV_A);
  4165. ev_timer_again (EV_A_ &w->timer);
  4166. if (ev_is_active (&w->timer)) ev_unref (EV_A);
  4167. }
  4168. }
  4169. }
  4170. }
  4171. #endif
  4172. #ifdef _WIN32
  4173. # define EV_LSTAT(p,b) _stati64 (p, b)
  4174. #else
  4175. # define EV_LSTAT(p,b) lstat (p, b)
  4176. #endif
  4177. void
  4178. ev_stat_stat (EV_P_ ev_stat *w) EV_NOEXCEPT
  4179. {
  4180. if (lstat (w->path, &w->attr) < 0)
  4181. w->attr.st_nlink = 0;
  4182. else if (!w->attr.st_nlink)
  4183. w->attr.st_nlink = 1;
  4184. }
  4185. ecb_noinline
  4186. static void
  4187. stat_timer_cb (EV_P_ ev_timer *w_, int revents)
  4188. {
  4189. ev_stat *w = (ev_stat *)(((char *)w_) - offsetof (ev_stat, timer));
  4190. ev_statdata prev = w->attr;
  4191. ev_stat_stat (EV_A_ w);
  4192. /* memcmp doesn't work on netbsd, they.... do stuff to their struct stat */
  4193. if (
  4194. prev.st_dev != w->attr.st_dev
  4195. || prev.st_ino != w->attr.st_ino
  4196. || prev.st_mode != w->attr.st_mode
  4197. || prev.st_nlink != w->attr.st_nlink
  4198. || prev.st_uid != w->attr.st_uid
  4199. || prev.st_gid != w->attr.st_gid
  4200. || prev.st_rdev != w->attr.st_rdev
  4201. || prev.st_size != w->attr.st_size
  4202. || prev.st_atime != w->attr.st_atime
  4203. || prev.st_mtime != w->attr.st_mtime
  4204. || prev.st_ctime != w->attr.st_ctime
  4205. ) {
  4206. /* we only update w->prev on actual differences */
  4207. /* in case we test more often than invoke the callback, */
  4208. /* to ensure that prev is always different to attr */
  4209. w->prev = prev;
  4210. #if EV_USE_INOTIFY
  4211. if (fs_fd >= 0)
  4212. {
  4213. infy_del (EV_A_ w);
  4214. infy_add (EV_A_ w);
  4215. ev_stat_stat (EV_A_ w); /* avoid race... */
  4216. }
  4217. #endif
  4218. ev_feed_event (EV_A_ w, EV_STAT);
  4219. }
  4220. }
  4221. void
  4222. ev_stat_start (EV_P_ ev_stat *w) EV_NOEXCEPT
  4223. {
  4224. if (ecb_expect_false (ev_is_active (w)))
  4225. return;
  4226. ev_stat_stat (EV_A_ w);
  4227. if (w->interval < MIN_STAT_INTERVAL && w->interval)
  4228. w->interval = MIN_STAT_INTERVAL;
  4229. ev_timer_init (&w->timer, stat_timer_cb, 0., w->interval ? w->interval : DEF_STAT_INTERVAL);
  4230. ev_set_priority (&w->timer, ev_priority (w));
  4231. #if EV_USE_INOTIFY
  4232. infy_init (EV_A);
  4233. if (fs_fd >= 0)
  4234. infy_add (EV_A_ w);
  4235. else
  4236. #endif
  4237. {
  4238. ev_timer_again (EV_A_ &w->timer);
  4239. ev_unref (EV_A);
  4240. }
  4241. ev_start (EV_A_ (W)w, 1);
  4242. EV_FREQUENT_CHECK;
  4243. }
  4244. void
  4245. ev_stat_stop (EV_P_ ev_stat *w) EV_NOEXCEPT
  4246. {
  4247. clear_pending (EV_A_ (W)w);
  4248. if (ecb_expect_false (!ev_is_active (w)))
  4249. return;
  4250. EV_FREQUENT_CHECK;
  4251. #if EV_USE_INOTIFY
  4252. infy_del (EV_A_ w);
  4253. #endif
  4254. if (ev_is_active (&w->timer))
  4255. {
  4256. ev_ref (EV_A);
  4257. ev_timer_stop (EV_A_ &w->timer);
  4258. }
  4259. ev_stop (EV_A_ (W)w);
  4260. EV_FREQUENT_CHECK;
  4261. }
  4262. #endif
  4263. #if EV_IDLE_ENABLE
  4264. void
  4265. ev_idle_start (EV_P_ ev_idle *w) EV_NOEXCEPT
  4266. {
  4267. if (ecb_expect_false (ev_is_active (w)))
  4268. return;
  4269. pri_adjust (EV_A_ (W)w);
  4270. EV_FREQUENT_CHECK;
  4271. {
  4272. int active = ++idlecnt [ABSPRI (w)];
  4273. ++idleall;
  4274. ev_start (EV_A_ (W)w, active);
  4275. array_needsize (ev_idle *, idles [ABSPRI (w)], idlemax [ABSPRI (w)], active, array_needsize_noinit);
  4276. idles [ABSPRI (w)][active - 1] = w;
  4277. }
  4278. EV_FREQUENT_CHECK;
  4279. }
  4280. void
  4281. ev_idle_stop (EV_P_ ev_idle *w) EV_NOEXCEPT
  4282. {
  4283. clear_pending (EV_A_ (W)w);
  4284. if (ecb_expect_false (!ev_is_active (w)))
  4285. return;
  4286. EV_FREQUENT_CHECK;
  4287. {
  4288. int active = ev_active (w);
  4289. idles [ABSPRI (w)][active - 1] = idles [ABSPRI (w)][--idlecnt [ABSPRI (w)]];
  4290. ev_active (idles [ABSPRI (w)][active - 1]) = active;
  4291. ev_stop (EV_A_ (W)w);
  4292. --idleall;
  4293. }
  4294. EV_FREQUENT_CHECK;
  4295. }
  4296. #endif
  4297. #if EV_PREPARE_ENABLE
  4298. void
  4299. ev_prepare_start (EV_P_ ev_prepare *w) EV_NOEXCEPT
  4300. {
  4301. if (ecb_expect_false (ev_is_active (w)))
  4302. return;
  4303. EV_FREQUENT_CHECK;
  4304. ev_start (EV_A_ (W)w, ++preparecnt);
  4305. array_needsize (ev_prepare *, prepares, preparemax, preparecnt, array_needsize_noinit);
  4306. prepares [preparecnt - 1] = w;
  4307. EV_FREQUENT_CHECK;
  4308. }
  4309. void
  4310. ev_prepare_stop (EV_P_ ev_prepare *w) EV_NOEXCEPT
  4311. {
  4312. clear_pending (EV_A_ (W)w);
  4313. if (ecb_expect_false (!ev_is_active (w)))
  4314. return;
  4315. EV_FREQUENT_CHECK;
  4316. {
  4317. int active = ev_active (w);
  4318. prepares [active - 1] = prepares [--preparecnt];
  4319. ev_active (prepares [active - 1]) = active;
  4320. }
  4321. ev_stop (EV_A_ (W)w);
  4322. EV_FREQUENT_CHECK;
  4323. }
  4324. #endif
  4325. #if EV_CHECK_ENABLE
  4326. void
  4327. ev_check_start (EV_P_ ev_check *w) EV_NOEXCEPT
  4328. {
  4329. if (ecb_expect_false (ev_is_active (w)))
  4330. return;
  4331. EV_FREQUENT_CHECK;
  4332. ev_start (EV_A_ (W)w, ++checkcnt);
  4333. array_needsize (ev_check *, checks, checkmax, checkcnt, array_needsize_noinit);
  4334. checks [checkcnt - 1] = w;
  4335. EV_FREQUENT_CHECK;
  4336. }
  4337. void
  4338. ev_check_stop (EV_P_ ev_check *w) EV_NOEXCEPT
  4339. {
  4340. clear_pending (EV_A_ (W)w);
  4341. if (ecb_expect_false (!ev_is_active (w)))
  4342. return;
  4343. EV_FREQUENT_CHECK;
  4344. {
  4345. int active = ev_active (w);
  4346. checks [active - 1] = checks [--checkcnt];
  4347. ev_active (checks [active - 1]) = active;
  4348. }
  4349. ev_stop (EV_A_ (W)w);
  4350. EV_FREQUENT_CHECK;
  4351. }
  4352. #endif
  4353. #if EV_EMBED_ENABLE
  4354. ecb_noinline
  4355. void
  4356. ev_embed_sweep (EV_P_ ev_embed *w) EV_NOEXCEPT
  4357. {
  4358. ev_run (w->other, EVRUN_NOWAIT);
  4359. }
  4360. static void
  4361. embed_io_cb (EV_P_ ev_io *io, int revents)
  4362. {
  4363. ev_embed *w = (ev_embed *)(((char *)io) - offsetof (ev_embed, io));
  4364. if (ev_cb (w))
  4365. ev_feed_event (EV_A_ (W)w, EV_EMBED);
  4366. else
  4367. ev_run (w->other, EVRUN_NOWAIT);
  4368. }
  4369. static void
  4370. embed_prepare_cb (EV_P_ ev_prepare *prepare, int revents)
  4371. {
  4372. ev_embed *w = (ev_embed *)(((char *)prepare) - offsetof (ev_embed, prepare));
  4373. {
  4374. EV_P = w->other;
  4375. while (fdchangecnt)
  4376. {
  4377. fd_reify (EV_A);
  4378. ev_run (EV_A_ EVRUN_NOWAIT);
  4379. }
  4380. }
  4381. }
  4382. #if EV_FORK_ENABLE
  4383. static void
  4384. embed_fork_cb (EV_P_ ev_fork *fork_w, int revents)
  4385. {
  4386. ev_embed *w = (ev_embed *)(((char *)fork_w) - offsetof (ev_embed, fork));
  4387. ev_embed_stop (EV_A_ w);
  4388. {
  4389. EV_P = w->other;
  4390. ev_loop_fork (EV_A);
  4391. ev_run (EV_A_ EVRUN_NOWAIT);
  4392. }
  4393. ev_embed_start (EV_A_ w);
  4394. }
  4395. #endif
  4396. #if 0
  4397. static void
  4398. embed_idle_cb (EV_P_ ev_idle *idle, int revents)
  4399. {
  4400. ev_idle_stop (EV_A_ idle);
  4401. }
  4402. #endif
  4403. void
  4404. ev_embed_start (EV_P_ ev_embed *w) EV_NOEXCEPT
  4405. {
  4406. if (ecb_expect_false (ev_is_active (w)))
  4407. return;
  4408. {
  4409. EV_P = w->other;
  4410. assert (("libev: loop to be embedded is not embeddable", backend & ev_embeddable_backends ()));
  4411. ev_io_init (&w->io, embed_io_cb, backend_fd, EV_READ);
  4412. }
  4413. EV_FREQUENT_CHECK;
  4414. ev_set_priority (&w->io, ev_priority (w));
  4415. ev_io_start (EV_A_ &w->io);
  4416. ev_prepare_init (&w->prepare, embed_prepare_cb);
  4417. ev_set_priority (&w->prepare, EV_MINPRI);
  4418. ev_prepare_start (EV_A_ &w->prepare);
  4419. #if EV_FORK_ENABLE
  4420. ev_fork_init (&w->fork, embed_fork_cb);
  4421. ev_fork_start (EV_A_ &w->fork);
  4422. #endif
  4423. /*ev_idle_init (&w->idle, e,bed_idle_cb);*/
  4424. ev_start (EV_A_ (W)w, 1);
  4425. EV_FREQUENT_CHECK;
  4426. }
  4427. void
  4428. ev_embed_stop (EV_P_ ev_embed *w) EV_NOEXCEPT
  4429. {
  4430. clear_pending (EV_A_ (W)w);
  4431. if (ecb_expect_false (!ev_is_active (w)))
  4432. return;
  4433. EV_FREQUENT_CHECK;
  4434. ev_io_stop (EV_A_ &w->io);
  4435. ev_prepare_stop (EV_A_ &w->prepare);
  4436. #if EV_FORK_ENABLE
  4437. ev_fork_stop (EV_A_ &w->fork);
  4438. #endif
  4439. ev_stop (EV_A_ (W)w);
  4440. EV_FREQUENT_CHECK;
  4441. }
  4442. #endif
  4443. #if EV_FORK_ENABLE
  4444. void
  4445. ev_fork_start (EV_P_ ev_fork *w) EV_NOEXCEPT
  4446. {
  4447. if (ecb_expect_false (ev_is_active (w)))
  4448. return;
  4449. EV_FREQUENT_CHECK;
  4450. ev_start (EV_A_ (W)w, ++forkcnt);
  4451. array_needsize (ev_fork *, forks, forkmax, forkcnt, array_needsize_noinit);
  4452. forks [forkcnt - 1] = w;
  4453. EV_FREQUENT_CHECK;
  4454. }
  4455. void
  4456. ev_fork_stop (EV_P_ ev_fork *w) EV_NOEXCEPT
  4457. {
  4458. clear_pending (EV_A_ (W)w);
  4459. if (ecb_expect_false (!ev_is_active (w)))
  4460. return;
  4461. EV_FREQUENT_CHECK;
  4462. {
  4463. int active = ev_active (w);
  4464. forks [active - 1] = forks [--forkcnt];
  4465. ev_active (forks [active - 1]) = active;
  4466. }
  4467. ev_stop (EV_A_ (W)w);
  4468. EV_FREQUENT_CHECK;
  4469. }
  4470. #endif
  4471. #if EV_CLEANUP_ENABLE
  4472. void
  4473. ev_cleanup_start (EV_P_ ev_cleanup *w) EV_NOEXCEPT
  4474. {
  4475. if (ecb_expect_false (ev_is_active (w)))
  4476. return;
  4477. EV_FREQUENT_CHECK;
  4478. ev_start (EV_A_ (W)w, ++cleanupcnt);
  4479. array_needsize (ev_cleanup *, cleanups, cleanupmax, cleanupcnt, array_needsize_noinit);
  4480. cleanups [cleanupcnt - 1] = w;
  4481. /* cleanup watchers should never keep a refcount on the loop */
  4482. ev_unref (EV_A);
  4483. EV_FREQUENT_CHECK;
  4484. }
  4485. void
  4486. ev_cleanup_stop (EV_P_ ev_cleanup *w) EV_NOEXCEPT
  4487. {
  4488. clear_pending (EV_A_ (W)w);
  4489. if (ecb_expect_false (!ev_is_active (w)))
  4490. return;
  4491. EV_FREQUENT_CHECK;
  4492. ev_ref (EV_A);
  4493. {
  4494. int active = ev_active (w);
  4495. cleanups [active - 1] = cleanups [--cleanupcnt];
  4496. ev_active (cleanups [active - 1]) = active;
  4497. }
  4498. ev_stop (EV_A_ (W)w);
  4499. EV_FREQUENT_CHECK;
  4500. }
  4501. #endif
  4502. #if EV_ASYNC_ENABLE
  4503. void
  4504. ev_async_start (EV_P_ ev_async *w) EV_NOEXCEPT
  4505. {
  4506. if (ecb_expect_false (ev_is_active (w)))
  4507. return;
  4508. w->sent = 0;
  4509. evpipe_init (EV_A);
  4510. EV_FREQUENT_CHECK;
  4511. ev_start (EV_A_ (W)w, ++asynccnt);
  4512. array_needsize (ev_async *, asyncs, asyncmax, asynccnt, array_needsize_noinit);
  4513. asyncs [asynccnt - 1] = w;
  4514. EV_FREQUENT_CHECK;
  4515. }
  4516. void
  4517. ev_async_stop (EV_P_ ev_async *w) EV_NOEXCEPT
  4518. {
  4519. clear_pending (EV_A_ (W)w);
  4520. if (ecb_expect_false (!ev_is_active (w)))
  4521. return;
  4522. EV_FREQUENT_CHECK;
  4523. {
  4524. int active = ev_active (w);
  4525. asyncs [active - 1] = asyncs [--asynccnt];
  4526. ev_active (asyncs [active - 1]) = active;
  4527. }
  4528. ev_stop (EV_A_ (W)w);
  4529. EV_FREQUENT_CHECK;
  4530. }
  4531. void
  4532. ev_async_send (EV_P_ ev_async *w) EV_NOEXCEPT
  4533. {
  4534. w->sent = 1;
  4535. evpipe_write (EV_A_ &async_pending);
  4536. }
  4537. #endif
  4538. /*****************************************************************************/
  4539. struct ev_once
  4540. {
  4541. ev_io io;
  4542. ev_timer to;
  4543. void (*cb)(int revents, void *arg);
  4544. void *arg;
  4545. };
  4546. static void
  4547. once_cb (EV_P_ struct ev_once *once, int revents)
  4548. {
  4549. void (*cb)(int revents, void *arg) = once->cb;
  4550. void *arg = once->arg;
  4551. ev_io_stop (EV_A_ &once->io);
  4552. ev_timer_stop (EV_A_ &once->to);
  4553. ev_free (once);
  4554. cb (revents, arg);
  4555. }
  4556. static void
  4557. once_cb_io (EV_P_ ev_io *w, int revents)
  4558. {
  4559. struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io));
  4560. once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->to));
  4561. }
  4562. static void
  4563. once_cb_to (EV_P_ ev_timer *w, int revents)
  4564. {
  4565. struct ev_once *once = (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to));
  4566. once_cb (EV_A_ once, revents | ev_clear_pending (EV_A_ &once->io));
  4567. }
  4568. void
  4569. ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg) EV_NOEXCEPT
  4570. {
  4571. struct ev_once *once = (struct ev_once *)ev_malloc (sizeof (struct ev_once));
  4572. once->cb = cb;
  4573. once->arg = arg;
  4574. ev_init (&once->io, once_cb_io);
  4575. if (fd >= 0)
  4576. {
  4577. ev_io_set (&once->io, fd, events);
  4578. ev_io_start (EV_A_ &once->io);
  4579. }
  4580. ev_init (&once->to, once_cb_to);
  4581. if (timeout >= 0.)
  4582. {
  4583. ev_timer_set (&once->to, timeout, 0.);
  4584. ev_timer_start (EV_A_ &once->to);
  4585. }
  4586. }
  4587. /*****************************************************************************/
  4588. #if EV_WALK_ENABLE
  4589. ecb_cold
  4590. void
  4591. ev_walk (EV_P_ int types, void (*cb)(EV_P_ int type, void *w)) EV_NOEXCEPT
  4592. {
  4593. int i, j;
  4594. ev_watcher_list *wl, *wn;
  4595. if (types & (EV_IO | EV_EMBED))
  4596. for (i = 0; i < anfdmax; ++i)
  4597. for (wl = anfds [i].head; wl; )
  4598. {
  4599. wn = wl->next;
  4600. #if EV_EMBED_ENABLE
  4601. if (ev_cb ((ev_io *)wl) == embed_io_cb)
  4602. {
  4603. if (types & EV_EMBED)
  4604. cb (EV_A_ EV_EMBED, ((char *)wl) - offsetof (struct ev_embed, io));
  4605. }
  4606. else
  4607. #endif
  4608. #if EV_USE_INOTIFY
  4609. if (ev_cb ((ev_io *)wl) == infy_cb)
  4610. ;
  4611. else
  4612. #endif
  4613. if ((ev_io *)wl != &pipe_w)
  4614. if (types & EV_IO)
  4615. cb (EV_A_ EV_IO, wl);
  4616. wl = wn;
  4617. }
  4618. if (types & (EV_TIMER | EV_STAT))
  4619. for (i = timercnt + HEAP0; i-- > HEAP0; )
  4620. #if EV_STAT_ENABLE
  4621. /*TODO: timer is not always active*/
  4622. if (ev_cb ((ev_timer *)ANHE_w (timers [i])) == stat_timer_cb)
  4623. {
  4624. if (types & EV_STAT)
  4625. cb (EV_A_ EV_STAT, ((char *)ANHE_w (timers [i])) - offsetof (struct ev_stat, timer));
  4626. }
  4627. else
  4628. #endif
  4629. if (types & EV_TIMER)
  4630. cb (EV_A_ EV_TIMER, ANHE_w (timers [i]));
  4631. #if EV_PERIODIC_ENABLE
  4632. if (types & EV_PERIODIC)
  4633. for (i = periodiccnt + HEAP0; i-- > HEAP0; )
  4634. cb (EV_A_ EV_PERIODIC, ANHE_w (periodics [i]));
  4635. #endif
  4636. #if EV_IDLE_ENABLE
  4637. if (types & EV_IDLE)
  4638. for (j = NUMPRI; j--; )
  4639. for (i = idlecnt [j]; i--; )
  4640. cb (EV_A_ EV_IDLE, idles [j][i]);
  4641. #endif
  4642. #if EV_FORK_ENABLE
  4643. if (types & EV_FORK)
  4644. for (i = forkcnt; i--; )
  4645. if (ev_cb (forks [i]) != embed_fork_cb)
  4646. cb (EV_A_ EV_FORK, forks [i]);
  4647. #endif
  4648. #if EV_ASYNC_ENABLE
  4649. if (types & EV_ASYNC)
  4650. for (i = asynccnt; i--; )
  4651. cb (EV_A_ EV_ASYNC, asyncs [i]);
  4652. #endif
  4653. #if EV_PREPARE_ENABLE
  4654. if (types & EV_PREPARE)
  4655. for (i = preparecnt; i--; )
  4656. # if EV_EMBED_ENABLE
  4657. if (ev_cb (prepares [i]) != embed_prepare_cb)
  4658. # endif
  4659. cb (EV_A_ EV_PREPARE, prepares [i]);
  4660. #endif
  4661. #if EV_CHECK_ENABLE
  4662. if (types & EV_CHECK)
  4663. for (i = checkcnt; i--; )
  4664. cb (EV_A_ EV_CHECK, checks [i]);
  4665. #endif
  4666. #if EV_SIGNAL_ENABLE
  4667. if (types & EV_SIGNAL)
  4668. for (i = 0; i < EV_NSIG - 1; ++i)
  4669. for (wl = signals [i].head; wl; )
  4670. {
  4671. wn = wl->next;
  4672. cb (EV_A_ EV_SIGNAL, wl);
  4673. wl = wn;
  4674. }
  4675. #endif
  4676. #if EV_CHILD_ENABLE
  4677. if (types & EV_CHILD)
  4678. for (i = (EV_PID_HASHSIZE); i--; )
  4679. for (wl = childs [i]; wl; )
  4680. {
  4681. wn = wl->next;
  4682. cb (EV_A_ EV_CHILD, wl);
  4683. wl = wn;
  4684. }
  4685. #endif
  4686. /* EV_STAT 0x00001000 /* stat data changed */
  4687. /* EV_EMBED 0x00010000 /* embedded event loop needs sweep */
  4688. }
  4689. #endif
  4690. void
  4691. ev_now_update_if_cheap (EV_P) EV_NOEXCEPT
  4692. {
  4693. if (have_cheap_timer) time_update (EV_A_ 1e100);
  4694. }
  4695. int
  4696. ev_active_cnt (EV_P) EV_NOEXCEPT
  4697. {
  4698. return activecnt;
  4699. }
  4700. #if EV_MULTIPLICITY
  4701. #include "ev_wrap.h"
  4702. #endif