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

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