ev.c 126 KB

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