jdebug.cpp 108 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777
  1. /*##############################################################################
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ############################################################################## */
  12. #include "platform.h"
  13. #include "jdebug.hpp"
  14. #include "jstring.hpp"
  15. #include "jhash.hpp"
  16. #include "jmisc.hpp"
  17. #include "jexcept.hpp"
  18. #include "jmutex.hpp"
  19. #include "jtime.hpp"
  20. #include <stdio.h>
  21. #include <time.h>
  22. #include <atomic>
  23. #if defined(_DEBUG) && defined(_WIN32) && !defined(USING_MPATROL)
  24. #undef new
  25. #define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
  26. #endif
  27. #ifdef _WIN32
  28. #define DPSAPI_VERSION 1
  29. #include <psapi.h>
  30. #endif
  31. #ifdef __linux__
  32. #include <sys/time.h>
  33. #include <sys/resource.h>
  34. #include <unistd.h>
  35. #include <sys/vfs.h>
  36. #include <sys/types.h>
  37. #include <sys/stat.h>
  38. #include <sys/klog.h>
  39. #include <dirent.h>
  40. #endif
  41. #ifdef __APPLE__
  42. #include <sys/param.h>
  43. #include <sys/mount.h>
  44. #include <sys/sysctl.h>
  45. #include <mach/task.h>
  46. #include <mach/mach_init.h>
  47. #include <mach/mach_host.h>
  48. #include <mach/vm_statistics.h>
  49. #endif
  50. #include "build-config.h"
  51. //===========================================================================
  52. #ifdef _DEBUG
  53. // #define _USE_MALLOC_HOOK // Only enable if you need it - slow!
  54. #else
  55. #undef _USE_MALLOC_HOOK // don't define for release - not threadsafe
  56. #endif
  57. #define _USE_RDTSC true
  58. #ifdef _USE_MALLOC_HOOK
  59. #define REPORT_LARGER_BLOCK_THAN (10*0x100000)
  60. static __int64 totalMem = 0;
  61. static __int64 hwmTotalMem = 0;
  62. #ifdef __linux__
  63. static unsigned memArea[32];
  64. #endif
  65. #endif
  66. // FIXME: Make sure this is still relevant, and if not, delete
  67. #ifndef _WIN32
  68. #ifndef __64BIT__
  69. #define USE_OLD_PU
  70. #endif
  71. #endif
  72. /* LINUX SYS: log KEY
  73. ========================
  74. PU (%) is the percentage CPU in use (unchanged from previously).
  75. MU (%) is what percentage of total (all processes) memory is in use
  76. (ram + swap) or in 32 bit is the percentage of 3GB (address space)
  77. used (whichever larger).
  78. MAL is total memory in use (i.e malloced and not freed ) by this
  79. process (= MMP+SBK)
  80. MMP is the sum of memory mapped (large) blocks in use by this process
  81. (which will be returned to OS when freed).
  82. SBK is the sbrk'ed memory i.e. smaller blocks allocated from the
  83. arena. (note this memory is unlikely to be returned to OS while the
  84. process is still running).
  85. TOT (K) is an indication of the memory footprint of the process.
  86. This is the 'arena' size (which is how much reserved by sbrk) plus the
  87. mmap memory size (MMP).
  88. RAM (K) is how much real memory is in use by all processes - it is
  89. the same as what would be reported by the 'free' command after the
  90. caches/buffers have been subtracted.
  91. SWP (K) is the swap size in use for all processes.
  92. Extended stats
  93. DSK: disk statistics for each disk (e.g. [sda] and [sdb])
  94. r/s read i/o operations per sec (over last period)
  95. kr/s K bytes read per sec
  96. w/s write i/o operations per sec
  97. kw/s K bytes written per sec
  98. busy indication how busy the disk was during period (%)
  99. NIC: network (i.e. eth0) statistics
  100. rxp/s packets received per sec
  101. rxk/s K bytes received per sec
  102. txp/s packets transmitted per sec
  103. txk/s K bytes transmitted per sec
  104. CPU:
  105. usr % at user level
  106. sys % in kernel
  107. iow % waiting for i/o
  108. */
  109. inline void skipSp(const char *&s)
  110. {
  111. while (isspace(*s))
  112. s++;
  113. }
  114. inline offset_t readHexNum(const char *&s)
  115. {
  116. offset_t ret = 0;
  117. loop {
  118. switch (*s) {
  119. case '0':
  120. case '1':
  121. case '2':
  122. case '3':
  123. case '4':
  124. case '5':
  125. case '6':
  126. case '7':
  127. case '8':
  128. case '9': ret = ret*16+(*s-'0');
  129. break;
  130. case 'A':
  131. case 'B':
  132. case 'C':
  133. case 'D':
  134. case 'E':
  135. case 'F': ret = ret*16+(*s-'A'+10);
  136. break;
  137. case 'a':
  138. case 'b':
  139. case 'c':
  140. case 'd':
  141. case 'e':
  142. case 'f': ret = ret*16+(*s-'a'+10);
  143. break;
  144. default:
  145. return ret;
  146. }
  147. s++;
  148. }
  149. return 0;
  150. }
  151. inline offset_t readDecNum(const char *&s)
  152. {
  153. offset_t ret = 0;
  154. loop {
  155. switch (*s) {
  156. case '0':
  157. case '1':
  158. case '2':
  159. case '3':
  160. case '4':
  161. case '5':
  162. case '6':
  163. case '7':
  164. case '8':
  165. case '9': ret = ret*10+(*s-'0');
  166. break;
  167. default:
  168. return ret;
  169. }
  170. s++;
  171. }
  172. return 0;
  173. }
  174. #if defined(_WIN32)
  175. static __int64 numCyclesNTicks;
  176. static __int64 ticksPerSec;
  177. static __int64 numScaleTicks;
  178. static bool useRDTSC = _USE_RDTSC;
  179. static double cycleToNanoScale;
  180. static void calibrate_timing()
  181. {
  182. #ifndef _AMD64_
  183. if (useRDTSC)
  184. {
  185. unsigned long r;
  186. __asm {
  187. mov eax, 1 ;
  188. cpuid ;
  189. mov r, edx
  190. }
  191. if ((r&0x10)==0)
  192. useRDTSC = false;
  193. }
  194. #endif
  195. if (useRDTSC) {
  196. unsigned startu = usTick();
  197. cycle_t start = getTSC();
  198. unsigned s1 = msTick();
  199. unsigned s2;
  200. while (s1==(s2=msTick()));
  201. unsigned s3;
  202. while (s2==(s3=msTick()));
  203. unsigned elapsedu = usTick()-startu;
  204. if (elapsedu) {
  205. double numPerUS=(double)(getTSC()-start)/(double)elapsedu; // this probably could be more accurate
  206. if (numPerUS>0)
  207. {
  208. cycleToNanoScale = 1000.0 / numPerUS;
  209. return;
  210. }
  211. }
  212. ERRLOG("calibrate_timing failed using RDTSC");
  213. useRDTSC = false;
  214. }
  215. static LARGE_INTEGER temp;
  216. QueryPerformanceFrequency(&temp);
  217. ticksPerSec = temp.QuadPart;
  218. numScaleTicks = ticksPerSec/100;
  219. LARGE_INTEGER t1;
  220. LARGE_INTEGER t2;
  221. QueryPerformanceCounter(&t1);
  222. t2.QuadPart=t1.QuadPart;
  223. while (t1.QuadPart==t2.QuadPart) QueryPerformanceCounter(&t1);
  224. cycle_t a1 = getTSC();
  225. t2.QuadPart = t1.QuadPart;
  226. while (t2.QuadPart-t1.QuadPart<numScaleTicks) QueryPerformanceCounter(&t2);
  227. cycle_t a2 = getTSC();
  228. numCyclesNTicks = (a2 - a1);
  229. cycleToNanoScale = ((double)numScaleTicks * 1000000000.0) / ((double)numCyclesNTicks * ticksPerSec);
  230. }
  231. __int64 cycle_to_nanosec(cycle_t cycles)
  232. {
  233. return (__int64)((double)cycles * cycleToNanoScale);
  234. }
  235. __int64 jlib_decl cycle_to_microsec(cycle_t cycles)
  236. {
  237. return (__int64)((double)cycles * cycleToNanoScale) / 1000;
  238. }
  239. __int64 jlib_decl cycle_to_millisec(cycle_t cycles)
  240. {
  241. return (__int64)((double)cycles * cycleToNanoScale) / 1000000;
  242. }
  243. cycle_t nanosec_to_cycle(__int64 ns)
  244. {
  245. return (__int64)((double)ns / cycleToNanoScale);
  246. }
  247. cycle_t jlib_decl get_cycles_now()
  248. {
  249. if (useRDTSC)
  250. return getTSC();
  251. LARGE_INTEGER temp;
  252. QueryPerformanceCounter(&temp);
  253. return temp.QuadPart;
  254. }
  255. double getCycleToNanoScale()
  256. {
  257. return cycleToNanoScale;
  258. }
  259. #else
  260. #if defined(HAS_GOOD_CYCLE_COUNTER)
  261. static bool useRDTSC = _USE_RDTSC;
  262. #endif
  263. static double cycleToNanoScale;
  264. static double cycleToMicroScale;
  265. static double cycleToMilliScale;
  266. void calibrate_timing()
  267. {
  268. #if defined(_ARCH_X86_) || defined(_ARCH_X86_64_)
  269. if (useRDTSC) {
  270. unsigned long eax;
  271. unsigned long ebx;
  272. unsigned long ecx;
  273. unsigned long edx;
  274. #if defined(_ARCH_X86_64_)
  275. __asm__ ("cpuid\n\t" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "0" (1));
  276. #else
  277. // NB PIC code and ebx usage don't mix well
  278. asm volatile("pushl %%ebx \n\t"
  279. "cpuid \n\t"
  280. "movl %%ebx, %1 \n\t"
  281. "popl %%ebx \n\t"
  282. : "=a"(eax), "=r"(ebx), "=c"(ecx), "=d"(edx)
  283. : "a"(1)
  284. : "cc");
  285. #endif
  286. if ((edx&0x10)==0)
  287. useRDTSC = false;
  288. }
  289. #endif
  290. #if defined(HAS_GOOD_CYCLE_COUNTER)
  291. if (useRDTSC) {
  292. unsigned startu = usTick();
  293. cycle_t start = getTSC();
  294. unsigned s1 = msTick();
  295. unsigned s2;
  296. while (s1==(s2=msTick()));
  297. unsigned s3;
  298. while (s2==(s3=msTick()));
  299. unsigned elapsedu = usTick()-startu;
  300. if (elapsedu) {
  301. double numPerUS=(double)(getTSC()-start)/(double)elapsedu; // this probably could be more accurate
  302. if (numPerUS>0)
  303. {
  304. cycleToNanoScale = 1000.0 / numPerUS;
  305. cycleToMicroScale = 1.0 / numPerUS;
  306. cycleToMilliScale = 0.001 / numPerUS;
  307. return;
  308. }
  309. }
  310. ERRLOG("calibrate_timing failed using RDTSC");
  311. useRDTSC = false;
  312. }
  313. #endif
  314. cycleToNanoScale = 1.0;
  315. cycleToMicroScale = 1.0;
  316. cycleToMilliScale = 1.0;
  317. }
  318. #if !defined(INLINE_GET_CYCLES_NOW) || !defined(HAS_GOOD_CYCLE_COUNTER)
  319. #if defined(CLOCK_MONOTONIC) && !defined(__APPLE__)
  320. static bool use_gettimeofday=false;
  321. #endif
  322. cycle_t jlib_decl get_cycles_now()
  323. {
  324. #if defined(HAS_GOOD_CYCLE_COUNTER)
  325. if (useRDTSC)
  326. return getTSC();
  327. #endif
  328. #ifdef __APPLE__
  329. return mach_absolute_time();
  330. #elif defined(CLOCK_MONOTONIC)
  331. if (!use_gettimeofday) {
  332. timespec tm;
  333. if (clock_gettime(CLOCK_MONOTONIC, &tm)>=0)
  334. return ((cycle_t)tm.tv_sec)*1000000000L+(tm.tv_nsec);
  335. use_gettimeofday = true;
  336. fprintf(stderr,"clock_gettime CLOCK_MONOTONIC returns %d",errno); // don't use PROGLOG
  337. }
  338. #endif
  339. struct timeval tm;
  340. gettimeofday(&tm,NULL);
  341. return ((cycle_t)tm.tv_sec)*1000000000L+(cycle_t)tm.tv_usec*1000L;
  342. }
  343. #endif
  344. __int64 jlib_decl cycle_to_nanosec(cycle_t cycles)
  345. {
  346. #if defined(HAS_GOOD_CYCLE_COUNTER)
  347. if (useRDTSC)
  348. return (__int64)((double)cycles * cycleToNanoScale);
  349. #endif
  350. #ifdef __APPLE__
  351. return cycles * (uint64_t) timebase_info.numer / (uint64_t)timebase_info.denom;
  352. #endif
  353. return cycles;
  354. }
  355. __int64 jlib_decl cycle_to_microsec(cycle_t cycles)
  356. {
  357. #if defined(HAS_GOOD_CYCLE_COUNTER)
  358. if (useRDTSC)
  359. return (__int64)((double)cycles * cycleToMicroScale);
  360. #endif
  361. return cycles / 1000;
  362. }
  363. __int64 jlib_decl cycle_to_millisec(cycle_t cycles)
  364. {
  365. #if defined(HAS_GOOD_CYCLE_COUNTER)
  366. if (useRDTSC)
  367. return (__int64)((double)cycles * cycleToMilliScale);
  368. #endif
  369. return cycles / 1000000;
  370. }
  371. cycle_t nanosec_to_cycle(__int64 ns)
  372. {
  373. #if defined(HAS_GOOD_CYCLE_COUNTER)
  374. if (useRDTSC)
  375. return (__int64)((double)ns / cycleToNanoScale);
  376. #endif
  377. return ns;
  378. }
  379. double getCycleToNanoScale()
  380. {
  381. return cycleToNanoScale;
  382. }
  383. #endif
  384. void display_time(const char *title, cycle_t diff)
  385. {
  386. DBGLOG("Time taken for %s: %" I64F "d cycles (%" I64F "dM) = %" I64F "d msec", title, diff, diff/1000000, cycle_to_nanosec(diff)/1000000);
  387. }
  388. TimeSection::TimeSection(const char * _title) : title(_title)
  389. {
  390. start_time = get_cycles_now();
  391. }
  392. TimeSection::~TimeSection()
  393. {
  394. cycle_t end_time = get_cycles_now();
  395. if (title)
  396. display_time(title, end_time-start_time);
  397. }
  398. MTimeSection::MTimeSection(ITimeReporter *_master, const char * _scope) : scope(_scope), master(_master)
  399. {
  400. start_time = get_cycles_now();
  401. }
  402. MTimeSection::~MTimeSection()
  403. {
  404. cycle_t end_time = get_cycles_now();
  405. if (master)
  406. master->addTiming(scope, end_time-start_time);
  407. else
  408. display_time(title, end_time-start_time);
  409. }
  410. class TimeSectionInfo : public MappingBase
  411. {
  412. public:
  413. TimeSectionInfo(const char * _scope, const char *_description, __int64 _cycles) : scope(_scope), description(_description), totalcycles(_cycles), maxcycles(_cycles), count(1) {};
  414. TimeSectionInfo(const char * _scope, const char *_description, __int64 _cycles, __int64 _maxcycles, unsigned _count)
  415. : scope(_scope), description(_description), totalcycles(_cycles), maxcycles(_maxcycles), count(_count) {};
  416. TimeSectionInfo(MemoryBuffer &mb)
  417. {
  418. mb.read(scope).read(description).read(totalcycles).read(maxcycles).read(count);
  419. }
  420. void serialize(MemoryBuffer &mb)
  421. {
  422. mb.read(scope).read(description).append(totalcycles).append(maxcycles).append(count);
  423. }
  424. virtual const void * getKey() const { return scope.get(); }
  425. StringAttr scope;
  426. StringAttr description;
  427. __int64 totalcycles;
  428. __int64 maxcycles;
  429. unsigned count;
  430. };
  431. class DefaultTimeReporter : implements ITimeReporter, public CInterface
  432. {
  433. StringMapOf<TimeSectionInfo> *sections;
  434. CriticalSection c;
  435. TimeSectionInfo &findSection(unsigned idx)
  436. {
  437. CriticalBlock b(c);
  438. HashIterator iter(*sections);
  439. for(iter.first(); iter.isValid(); iter.next())
  440. {
  441. if (!idx--)
  442. return (TimeSectionInfo &) iter.query();
  443. }
  444. throw MakeStringException(2, "Invalid index to DefaultTimeReporter");
  445. }
  446. public:
  447. IMPLEMENT_IINTERFACE
  448. DefaultTimeReporter()
  449. {
  450. sections = new StringMapOf<TimeSectionInfo>(true);
  451. }
  452. DefaultTimeReporter(MemoryBuffer &mb)
  453. {
  454. sections = new StringMapOf<TimeSectionInfo>(true);
  455. unsigned ns;
  456. mb.read(ns);
  457. while (ns--)
  458. {
  459. TimeSectionInfo &newinfo = * new TimeSectionInfo(mb);
  460. sections->replaceOwn(newinfo);
  461. }
  462. }
  463. ~DefaultTimeReporter()
  464. {
  465. // printTimings(); // Must explicitly call printTimings - no automatic print (too late here!)
  466. delete sections;
  467. }
  468. virtual void report(ITimeReportInfo &cb)
  469. {
  470. CriticalBlock b(c);
  471. HashIterator iter(*sections);
  472. for(iter.first(); iter.isValid(); iter.next())
  473. {
  474. TimeSectionInfo &ts = (TimeSectionInfo &)iter.query();
  475. cb.report(ts.scope, ts.description, cycle_to_nanosec(ts.totalcycles), cycle_to_nanosec(ts.maxcycles), ts.count);
  476. }
  477. }
  478. virtual void addTiming(const char * scope, cycle_t cycles)
  479. {
  480. CriticalBlock b(c);
  481. TimeSectionInfo *info = sections->find(scope);
  482. if (info)
  483. {
  484. info->totalcycles += cycles;
  485. if (cycles > info->maxcycles) info->maxcycles = cycles;
  486. info->count++;
  487. }
  488. else
  489. {
  490. TimeSectionInfo &newinfo = * new TimeSectionInfo(scope, NULL, cycles);
  491. sections->replaceOwn(newinfo);
  492. }
  493. }
  494. virtual unsigned numSections()
  495. {
  496. CriticalBlock b(c);
  497. return sections->count();
  498. }
  499. virtual StatisticKind getTimerType(unsigned idx __attribute__((unused)))
  500. {
  501. return StTimeElapsed;
  502. }
  503. virtual StatisticScopeType getScopeType(unsigned idx __attribute__((unused)))
  504. {
  505. return SSTsection;
  506. }
  507. virtual __int64 getTime(unsigned idx)
  508. {
  509. CriticalBlock b(c);
  510. return cycle_to_nanosec(findSection(idx).totalcycles);
  511. }
  512. virtual __int64 getMaxTime(unsigned idx)
  513. {
  514. CriticalBlock b(c);
  515. return cycle_to_nanosec(findSection(idx).maxcycles);
  516. }
  517. virtual unsigned getCount(unsigned idx)
  518. {
  519. CriticalBlock b(c);
  520. return findSection(idx).count;
  521. }
  522. virtual StringBuffer &getScope(unsigned idx, StringBuffer &s)
  523. {
  524. CriticalBlock b(c);
  525. return s.append(findSection(idx).scope);
  526. }
  527. virtual void reset()
  528. {
  529. CriticalBlock b(c);
  530. delete sections;
  531. sections = new StringMapOf<TimeSectionInfo>(true);
  532. }
  533. virtual StringBuffer &getTimings(StringBuffer &str)
  534. {
  535. CriticalBlock b(c);
  536. if (numSections())
  537. {
  538. for (unsigned i = 0; i < numSections(); i++)
  539. {
  540. getScope(i, str.append("Timing: ")).append(" total=")
  541. .append(getTime(i)/1000000)
  542. .append("ms max=")
  543. .append(getMaxTime(i)/1000)
  544. .append("us count=")
  545. .append(getCount(i))
  546. .append(" ave=")
  547. .append((getTime(i)/1000)/getCount(i))
  548. .append("us\n");
  549. }
  550. }
  551. return str;
  552. }
  553. virtual void printTimings()
  554. {
  555. CriticalBlock b(c);
  556. if (numSections())
  557. {
  558. StringBuffer str;
  559. PrintLog(getTimings(str).str());
  560. }
  561. }
  562. virtual void mergeTiming(const char * scope, cycle_t totalcycles, cycle_t maxcycles, const unsigned count)
  563. {
  564. CriticalBlock b(c);
  565. TimeSectionInfo *info = sections->find(scope);
  566. if (!info)
  567. {
  568. info = new TimeSectionInfo(scope, NULL, totalcycles, maxcycles, count);
  569. sections->replaceOwn(*info);
  570. }
  571. else
  572. {
  573. info->totalcycles += totalcycles;
  574. if (maxcycles > info->maxcycles) info->maxcycles = maxcycles;
  575. info->count += count;
  576. }
  577. }
  578. virtual void mergeInto(ITimeReporter &other)
  579. {
  580. CriticalBlock b(c);
  581. HashIterator iter(*sections);
  582. for(iter.first(); iter.isValid(); iter.next())
  583. {
  584. TimeSectionInfo &ts = (TimeSectionInfo &) iter.query();
  585. other.mergeTiming(ts.scope, ts.totalcycles, ts.maxcycles, ts.count);
  586. }
  587. }
  588. virtual void merge(ITimeReporter &other)
  589. {
  590. CriticalBlock b(c);
  591. other.mergeInto(*this);
  592. }
  593. virtual void serialize(MemoryBuffer &mb)
  594. {
  595. CriticalBlock b(c);
  596. mb.append(numSections());
  597. HashIterator iter(*sections);
  598. for(iter.first(); iter.isValid(); iter.next())
  599. {
  600. TimeSectionInfo &ts = (TimeSectionInfo &) iter.query();
  601. ts.serialize(mb);
  602. }
  603. }
  604. };
  605. static ITimeReporter * activeTimer = NULL;
  606. ITimeReporter * queryActiveTimer()
  607. {
  608. return activeTimer;
  609. }
  610. ITimeReporter *createStdTimeReporter() { return new DefaultTimeReporter(); }
  611. ITimeReporter *createStdTimeReporter(MemoryBuffer &mb) { return new DefaultTimeReporter(mb); }
  612. cycle_t oneSecInCycles;
  613. MODULE_INIT(INIT_PRIORITY_JDEBUG1)
  614. {
  615. // perform v. early in process startup, ideally this would grab process exclusively for the 2 100ths of a sec it performs calc.
  616. calibrate_timing();
  617. oneSecInCycles = nanosec_to_cycle(1000000000);
  618. return 1;
  619. }
  620. MODULE_INIT(INIT_PRIORITY_JDEBUG2)
  621. {
  622. activeTimer = new DefaultTimeReporter();
  623. return true;
  624. }
  625. MODULE_EXIT()
  626. {
  627. ::Release(activeTimer);
  628. activeTimer = NULL;
  629. }
  630. //===========================================================================
  631. // Performance Monitor
  632. #ifdef _WIN32
  633. #define SystemBasicInformation 0
  634. #define SystemPerformanceInformation 2
  635. #define SystemTimeInformation 3
  636. #define SystemProcessList 5
  637. typedef enum _PROCESSINFOCLASS {
  638. ProcessBasicInformation,
  639. ProcessQuotaLimits,
  640. ProcessIoCounters,
  641. ProcessVmCounters,
  642. ProcessTimes,
  643. ProcessBasePriority,
  644. ProcessRaisePriority,
  645. ProcessDebugPort,
  646. ProcessExceptionPort,
  647. ProcessAccessToken,
  648. ProcessLdtInformation,
  649. ProcessLdtSize,
  650. ProcessDefaultHardErrorMode,
  651. ProcessIoPortHandlers, // Note: this is kernel mode only
  652. ProcessPooledUsageAndLimits,
  653. ProcessWorkingSetWatch,
  654. ProcessUserModeIOPL,
  655. ProcessEnableAlignmentFaultFixup,
  656. ProcessPriorityClass,
  657. ProcessWx86Information,
  658. ProcessHandleCount,
  659. ProcessAffinityMask,
  660. ProcessPriorityBoost,
  661. ProcessDeviceMap,
  662. ProcessSessionInformation,
  663. ProcessForegroundInformation,
  664. ProcessWow64Information,
  665. MaxProcessInfoClass
  666. } PROCESSINFOCLASS;
  667. typedef LONG NTSTATUS;
  668. #define Li2Double(x) ((double)((x).HighPart) * 4.294967296E9 + (double)((x).LowPart))
  669. typedef struct
  670. {
  671. DWORD dwUnknown1;
  672. ULONG uKeMaximumIncrement;
  673. ULONG uPageSize;
  674. ULONG uMmNumberOfPhysicalPages;
  675. ULONG uMmLowestPhysicalPage;
  676. ULONG uMmHighestPhysicalPage;
  677. ULONG uAllocationGranularity;
  678. PVOID pLowestUserAddress;
  679. PVOID pMmHighestUserAddress;
  680. ULONG uKeActiveProcessors;
  681. BYTE bKeNumberProcessors;
  682. BYTE bUnknown2;
  683. WORD wUnknown3;
  684. } SYSTEM_BASIC_INFORMATION;
  685. typedef struct
  686. {
  687. LARGE_INTEGER liIdleTime;
  688. DWORD dwSpare[76];
  689. } SYSTEM_PERFORMANCE_INFORMATION;
  690. typedef struct
  691. {
  692. LARGE_INTEGER liKeBootTime;
  693. LARGE_INTEGER liKeSystemTime;
  694. LARGE_INTEGER liExpTimeZoneBias;
  695. ULONG uCurrentTimeZoneId;
  696. DWORD dwReserved;
  697. } SYSTEM_TIME_INFORMATION;
  698. struct PROCESS_BASIC_INFORMATION {
  699. long ExitStatus;
  700. void * PebBaseAddress;
  701. unsigned long AffinityMask;
  702. long BasePriority;
  703. unsigned long UniqueProcessId;
  704. unsigned long InheritedFromUniqueProcessId;
  705. };
  706. // QUOTA_LIMITS
  707. struct __IO_COUNTERS { // defined in SDK
  708. ULONGLONG ReadOperationCount;
  709. ULONGLONG WriteOperationCount;
  710. ULONGLONG OtherOperationCount;
  711. ULONGLONG ReadTransferCount;
  712. ULONGLONG WriteTransferCount;
  713. ULONGLONG OtherTransferCount;
  714. };
  715. struct VM_COUNTERS {
  716. unsigned long PeakVirtualSize;
  717. unsigned long VirtualSize;
  718. unsigned long PageFaultCount;
  719. unsigned long PeakWorkingSetSize;
  720. unsigned long WorkingSetSize;
  721. unsigned long QuotaPeakPagedPoolUsage;
  722. unsigned long QuotaPagedPoolUsage;
  723. unsigned long QuotaPeakNonPagedPoolUsage;
  724. unsigned long QuotaNonPagedPoolUsage;
  725. unsigned long PagefileUsage;
  726. unsigned long PeakPagefileUsage;
  727. };
  728. struct POOLED_USAGE_AND_LIMITS {
  729. unsigned long PeakPagedPoolUsage;
  730. unsigned long PagedPoolUsage;
  731. unsigned long PagedPoolLimit;
  732. unsigned long PeakNonPagedPoolUsage;
  733. unsigned long NonPagedPoolUsage;
  734. unsigned long NonPagedPoolLimit;
  735. unsigned long PeakPagefileUsage;
  736. unsigned long PagefileUsage;
  737. unsigned long PagefileLimit;
  738. };
  739. struct KERNEL_USER_TIMES {
  740. __int64 CreateTime;
  741. __int64 ExitTime;
  742. __int64 KernelTime;
  743. __int64 UserTime;
  744. //__int64 EllapsedTime;
  745. };
  746. // ntdll!NtQuerySystemInformation (NT specific!)
  747. //
  748. // The function copies the system information of the
  749. // specified type into a buffer
  750. //
  751. // NTSYSAPI
  752. // NTSTATUS
  753. // NTAPI
  754. // NtQuerySystemInformation(
  755. // IN UINT SystemInformationClass, // information type
  756. // OUT PVOID SystemInformation, // pointer to buffer
  757. // IN ULONG SystemInformationLength, // buffer size in bytes
  758. // OUT PULONG ReturnLength OPTIONAL // pointer to a 32-bit
  759. // // variable that receives
  760. // // the number of bytes
  761. // // written to the buffer
  762. // );
  763. //
  764. //NTSYSCALLAPI
  765. //NTSTATUS
  766. //NTAPI
  767. //NtQueryInformationProcess(
  768. // IN HANDLE ProcessHandle,
  769. // IN PROCESSINFOCLASS ProcessInformationClass,
  770. // OUT PVOID ProcessInformation,
  771. // IN ULONG ProcessInformationLength,
  772. // OUT PULONG ReturnLength OPTIONAL
  773. // );
  774. typedef LONG (WINAPI *PROCNTQSI)(UINT,PVOID,ULONG,PULONG);
  775. typedef LONG (WINAPI *PROCNTQIP)(HANDLE,UINT,PVOID,ULONG,PULONG);
  776. typedef LONG (WINAPI *PROCNTGST)(LARGE_INTEGER*, LARGE_INTEGER*, LARGE_INTEGER*);
  777. memsize_t getMapInfo(const char *type)
  778. {
  779. return 0; // TODO/UNKNOWN
  780. }
  781. memsize_t getVMInfo(const char *type)
  782. {
  783. return 0; // TODO/UNKNOWN
  784. }
  785. void getCpuInfo(unsigned &numCPUs, unsigned &CPUSpeed)
  786. {
  787. // MORE: Might be a better way to get CPU speed (actual) than the one stored in Registry
  788. LONG lRet;
  789. HKEY hKey;
  790. DWORD keyValue;
  791. DWORD valueLen = sizeof(keyValue);
  792. if ((lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0L, KEY_READ , &hKey)) != ERROR_SUCCESS)
  793. {
  794. DBGLOG("RegOpenKeyEx(HKEY_LOCAL_MACHINE, ...) failed to open CentralProcessor\\0 - SysErrorCode=%d", lRet);
  795. }
  796. else if ((lRet = RegQueryValueEx(hKey, TEXT("~MHz"), NULL, NULL, (LPBYTE) &keyValue, &valueLen)) != ERROR_SUCCESS)
  797. {
  798. DBGLOG("RegQueryValueEx() failed to get CPU speed - errorCode=%d", lRet);
  799. RegCloseKey(hKey);
  800. }
  801. else
  802. {
  803. CPUSpeed = keyValue;
  804. RegCloseKey(hKey);
  805. }
  806. SYSTEM_INFO sysInfo;
  807. GetSystemInfo(&sysInfo);
  808. numCPUs = sysInfo.dwNumberOfProcessors;
  809. }
  810. static unsigned evalAffinityCpus()
  811. {
  812. unsigned numCpus = 0;
  813. DWORD ProcessAffinityMask, SystemAffinityMask;
  814. if (GetProcessAffinityMask(GetCurrentProcess(), (PDWORD_PTR)&ProcessAffinityMask, (PDWORD_PTR)&SystemAffinityMask))
  815. {
  816. unsigned i = 0;
  817. while (ProcessAffinityMask)
  818. {
  819. if (ProcessAffinityMask & 1)
  820. ++numCpus;
  821. ProcessAffinityMask >>=1;
  822. }
  823. }
  824. else // fall back to legacy num system cpus
  825. {
  826. Owned<IException> e = makeOsException(GetLastError(), "Failed to get affinity");
  827. EXCLOG(e, NULL);
  828. unsigned cpuSpeed;
  829. getCpuInfo(numCpus, cpuSpeed);
  830. return numCpus;
  831. }
  832. return numCpus;
  833. }
  834. #else // linux
  835. memsize_t getMapInfo(const char *type)
  836. {
  837. // NOTE: 'total' heap value includes Roxiemem allocation, if present
  838. enum mapList { HEAP, STACK, SBRK, ANON };
  839. enum mapList mapType;
  840. if ( streq(type, "heap") )
  841. mapType = HEAP;
  842. else if ( streq(type, "stack") )
  843. mapType = STACK;
  844. else if ( streq(type, "sbrk") )
  845. mapType = SBRK;
  846. else if ( streq(type, "anon") )
  847. mapType = ANON;
  848. else
  849. return 0;
  850. memsize_t ret = 0;
  851. VStringBuffer procMaps("/proc/%d/maps", GetCurrentProcessId());
  852. FILE *diskfp = fopen(procMaps.str(), "r");
  853. if (!diskfp)
  854. return false;
  855. char ln[256];
  856. /*
  857. * exmaple /proc/<pid>/maps format:
  858. * addr_start -addr_end perms offset dev inode pathname
  859. * 01c3a000-01c5b000 rw-p 00000000 00:00 0 [heap]
  860. * 7f3f25217000-7f3f25a40000 rw-p 00000000 00:00 0 [stack:2362]
  861. * 7f4020a40000-7f4020a59000 rw-p 00000000 00:00 0
  862. * 7f4020a59000-7f4020a5a000 ---p 00000000 00:00 0
  863. * 7f4029bd4000-7f4029bf6000 r-xp 00000000 08:01 17576135 /lib/x86_64-linux-gnu/ld-2.15.so
  864. */
  865. while (fgets(ln, sizeof(ln), diskfp))
  866. {
  867. bool skipline = true;
  868. if ( mapType == HEAP || mapType == ANON ) // 'general' heap includes anon mmapped + sbrk
  869. {
  870. // skip file maps (beginning with /) and all other regions (except [heap if selected)
  871. if ( (mapType == HEAP && strstr(ln, "[heap")) || (!strstr(ln, " /") && !strstr(ln, " [")) )
  872. {
  873. // include only (r)ead + (w)rite and (p)rivate (not shared), skipping e(x)ecutable
  874. // and ---p guard regions
  875. if ( strstr(ln, " rw-p") )
  876. skipline = false;
  877. }
  878. }
  879. else if ( mapType == STACK )
  880. {
  881. if ( strstr(ln, "[stack") )
  882. skipline = false;
  883. }
  884. else if ( mapType == SBRK )
  885. {
  886. if ( strstr(ln, "[heap") )
  887. skipline = false;
  888. }
  889. if ( !skipline )
  890. {
  891. unsigned __int64 addrLow, addrHigh;
  892. if (2 == sscanf(ln, "%16" I64F "x-%16" I64F "x", &addrLow, &addrHigh))
  893. ret += (memsize_t)(addrHigh-addrLow);
  894. }
  895. }
  896. fclose(diskfp);
  897. return ret;
  898. }
  899. static bool matchExtract(const char * prefix, const char * line, memsize_t & value)
  900. {
  901. size32_t len = strlen(prefix);
  902. if (strncmp(prefix, line, len)==0)
  903. {
  904. char * tail = NULL;
  905. value = strtol(line+len, &tail, 10);
  906. while (isspace(*tail))
  907. tail++;
  908. if (strncmp(tail, "kB", 2) == 0)
  909. value *= 0x400;
  910. else if (strncmp(tail, "mB", 2) == 0)
  911. value *= 0x100000;
  912. else if (strncmp(tail, "gB", 2) == 0)
  913. value *= 0x40000000;
  914. return true;
  915. }
  916. return false;
  917. }
  918. memsize_t getVMInfo(const char *type)
  919. {
  920. memsize_t ret = 0;
  921. VStringBuffer name("%s:", type);
  922. VStringBuffer procMaps("/proc/self/status");
  923. FILE *diskfp = fopen(procMaps.str(), "r");
  924. if (!diskfp)
  925. return 0;
  926. char ln[256];
  927. while (fgets(ln, sizeof(ln), diskfp))
  928. {
  929. if (matchExtract(name.str(), ln, ret))
  930. break;
  931. }
  932. fclose(diskfp);
  933. return ret;
  934. }
  935. void getCpuInfo(unsigned &numCPUs, unsigned &CPUSpeed)
  936. {
  937. int cpufd = open("/proc/cpuinfo",O_RDONLY);
  938. if (cpufd==-1)
  939. return;
  940. MemoryAttr ma;
  941. char *buf = (char *)ma.allocate(0x10000);
  942. size32_t l=0;
  943. loop {
  944. size32_t rd = read(cpufd, buf+l, 0x10000-1-l);
  945. if ((int)rd<=0)
  946. break;
  947. l += rd;
  948. }
  949. buf[l] = 0;
  950. const char *bufptr = buf;
  951. char * tail;
  952. numCPUs = CPUSpeed = 0;
  953. // MORE: It is a shame that the info in this file (/proc/cpuinfo) are formatted (ie tabs .. etc)
  954. const char *cpuNumTag = "processor\t:";
  955. const char *cpuSpeedTag = "cpu MHz\t\t:";
  956. while (bufptr) {
  957. if (*bufptr =='\n')
  958. bufptr++;
  959. if (strncmp(cpuNumTag, bufptr, strlen(cpuNumTag))==0)
  960. numCPUs++;
  961. else if (strncmp(cpuSpeedTag, bufptr, strlen(cpuSpeedTag))==0)
  962. CPUSpeed = (unsigned)strtol(bufptr+strlen(cpuSpeedTag), &tail, 10);
  963. bufptr = strchr(bufptr, '\n');
  964. }
  965. close(cpufd);
  966. }
  967. static unsigned evalAffinityCpus()
  968. {
  969. #ifdef __APPLE__
  970. // MORE - could do better
  971. #else
  972. cpu_set_t cpuset;
  973. int err = pthread_getaffinity_np(GetCurrentThreadId(), sizeof(cpu_set_t), &cpuset);
  974. if (0 == err)
  975. {
  976. #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 6)
  977. return CPU_COUNT(&cpuset);
  978. #else
  979. unsigned numCpus = 0;
  980. unsigned setSize = CPU_SETSIZE;
  981. while (setSize--)
  982. {
  983. if (CPU_ISSET(setSize, &cpuset))
  984. ++numCpus;
  985. }
  986. return numCpus;
  987. #endif /* GLIBC */
  988. }
  989. #endif
  990. return 1;
  991. }
  992. // Note - values are returned in Kb
  993. static void getMemUsage(unsigned &inuse,unsigned &active,unsigned &total,unsigned &swaptotal,unsigned &swapinuse)
  994. {
  995. #ifdef __APPLE__
  996. active = 0;
  997. inuse = 0;
  998. total = 0;
  999. swaptotal = 0;
  1000. swapinuse = 0;
  1001. vm_size_t pageSize;
  1002. if (KERN_SUCCESS != host_page_size(mach_host_self(), &pageSize))
  1003. return;
  1004. mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
  1005. vm_statistics64_data_t vmstat;
  1006. if (KERN_SUCCESS != host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vmstat, &count))
  1007. return;
  1008. uint64_t totalBytes = (vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.free_count + vmstat.compressor_page_count) * pageSize;
  1009. uint64_t inuseBytes = (vmstat.wire_count + vmstat.active_count + vmstat.inactive_count + vmstat.compressor_page_count) * pageSize;
  1010. uint64_t activeBytes = (vmstat.wire_count + vmstat.active_count) * pageSize;
  1011. active = activeBytes / 1024;
  1012. inuse = inuseBytes / 1024;
  1013. total = totalBytes / 1024;
  1014. // swaptotal and swapinuse TBD
  1015. #else
  1016. unsigned free=0;
  1017. unsigned swapfree=0;
  1018. active = 0;
  1019. inuse = 0;
  1020. static int memfd = -1;
  1021. if (memfd==-1)
  1022. memfd = open("/proc/meminfo",O_RDONLY);
  1023. if (memfd==-1)
  1024. return;
  1025. char buf[2048];
  1026. size32_t l = pread(memfd, buf, sizeof(buf)-1, 0L);
  1027. if ((int)l<=0)
  1028. return;
  1029. buf[l] = 0;
  1030. const char *bufptr = buf;
  1031. char * tail;
  1032. unsigned i = 7; // supposed to match max number of items extract below
  1033. total = swaptotal = free = active = swapfree = 0;
  1034. unsigned swapcached = 0;
  1035. unsigned cached = 0;
  1036. while (bufptr&&i) {
  1037. if (*bufptr =='\n')
  1038. bufptr++;
  1039. i--;
  1040. if (strncmp("MemTotal:", bufptr, 9)==0)
  1041. total = (unsigned)strtol(bufptr+9, &tail, 10);
  1042. else if (strncmp("SwapTotal:", bufptr, 10)==0)
  1043. swaptotal = (unsigned)strtol(bufptr+10, &tail, 10);
  1044. else if (strncmp("MemFree:", bufptr, 8)==0)
  1045. free = (unsigned)strtol(bufptr+8, &tail, 10);
  1046. else if (strncmp("Active:", bufptr, 7)==0)
  1047. active = (unsigned)strtol(bufptr+7, &tail, 10);
  1048. else if (strncmp("SwapFree:", bufptr, 9)==0)
  1049. swapfree = (unsigned)strtol(bufptr+9, &tail, 10);
  1050. else if (strncmp("Cached:", bufptr, 7)==0)
  1051. cached = (unsigned)strtol(bufptr+7, &tail, 10);
  1052. else if (strncmp("SwapCached:", bufptr, 11)==0)
  1053. swapcached = (unsigned)strtol(bufptr+11, &tail, 10);
  1054. else
  1055. i++;
  1056. bufptr = strchr(bufptr, '\n');
  1057. }
  1058. inuse = total-free-cached;
  1059. swapinuse = swaptotal-swapfree-swapcached;
  1060. #endif
  1061. }
  1062. class CInt64fix
  1063. {
  1064. __int64 val;
  1065. public:
  1066. CInt64fix()
  1067. {
  1068. val = 0;
  1069. }
  1070. void set(int v)
  1071. {
  1072. __int64 ret = (unsigned)v;
  1073. while (val-ret>0x80000000LL)
  1074. ret += 0x100000000LL;
  1075. val = ret;
  1076. }
  1077. __int64 get()
  1078. {
  1079. return val;
  1080. }
  1081. };
  1082. void getMemStats(StringBuffer &out, unsigned &memused, unsigned &memtot)
  1083. {
  1084. #ifdef __linux__
  1085. __int64 total = getMapInfo("heap");
  1086. __int64 sbrkmem = getMapInfo("sbrk");
  1087. __int64 mmapmem = total - sbrkmem;
  1088. __int64 virttot = getVMInfo("VmData");
  1089. unsigned mu;
  1090. unsigned ma;
  1091. unsigned mt;
  1092. unsigned st;
  1093. unsigned su;
  1094. getMemUsage(mu,ma,mt,st,su);
  1095. unsigned muval = (unsigned)(((__int64)mu+(__int64)su)*100/((__int64)mt+(__int64)st));
  1096. if (sizeof(memsize_t)==4) {
  1097. unsigned muval2 = (virttot*100)/(3*(__int64)0x40000000);
  1098. if (muval2>muval)
  1099. muval = muval2;
  1100. }
  1101. if (muval>100)
  1102. muval = 100; // !
  1103. out.appendf("MU=%3u%% MAL=%" I64F "d MMP=%" I64F "d SBK=%" I64F "d TOT=%uK RAM=%uK SWP=%uK",
  1104. muval, total, mmapmem, sbrkmem, (unsigned)(virttot/1024), mu, su);
  1105. #ifdef _USE_MALLOC_HOOK
  1106. if (totalMem)
  1107. out.appendf(" TM=%" I64F "d",totalMem);
  1108. #endif
  1109. memused = mu+su;
  1110. memtot = mt+st;
  1111. #elif defined (__APPLE__)
  1112. __uint64 bytes;
  1113. size_t len = sizeof(bytes);
  1114. sysctlbyname("hw.memsize", &bytes, &len, NULL, 0);
  1115. // See http://miknight.blogspot.com/2005/11/resident-set-size-in-mac-os-x.html
  1116. struct task_basic_info t_info;
  1117. mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
  1118. task_info(current_task(), TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
  1119. out.appendf("RES=%" I64F "uMiB VIRT=%" I64F "uMiB TOT=%" I64F "uMiB",
  1120. (__uint64) t_info.resident_size/(1024*1024),
  1121. (__uint64) t_info.virtual_size/(1024*1024),
  1122. bytes/(1024*1024));
  1123. memused = t_info.resident_size;
  1124. memtot = t_info.virtual_size;
  1125. #elif defined (__FreeBSD___)
  1126. UNIMPLEMENTED;
  1127. #endif
  1128. }
  1129. void getDiskUsage(char const * path, unsigned __int64 & total, unsigned __int64 & inUse)
  1130. {
  1131. #if defined(__linux__) || defined(__APPLE__)
  1132. struct statfs stfs;
  1133. if(statfs(path, &stfs) < 0)
  1134. {
  1135. //PrintLog("statfs error for filesystem '%s'", path);
  1136. total = inUse = 0;
  1137. }
  1138. else
  1139. {
  1140. struct stat st;
  1141. if(stat(path, &st) < 0)
  1142. {
  1143. //PrintLog("stat error for filesystem '%s'", path);
  1144. total = inUse = 0;
  1145. }
  1146. else
  1147. {
  1148. total = (unsigned __int64)stfs.f_blocks * st.st_blksize;
  1149. inUse = total - (unsigned __int64)stfs.f_bfree * st.st_blksize;
  1150. }
  1151. }
  1152. #else
  1153. total = inUse = 0;
  1154. #endif
  1155. }
  1156. #endif
  1157. static std::atomic<unsigned> cachedNumCpus;
  1158. unsigned getAffinityCpus()
  1159. {
  1160. if (cachedNumCpus.load(std::memory_order_acquire) == 0)
  1161. cachedNumCpus.store(evalAffinityCpus(), std::memory_order_release);
  1162. return cachedNumCpus.load(std::memory_order_acquire);
  1163. }
  1164. void clearAffinityCache()
  1165. {
  1166. cachedNumCpus.store(0, std::memory_order_release);
  1167. }
  1168. void getPeakMemUsage(memsize_t &peakVm,memsize_t &peakResident)
  1169. {
  1170. peakVm = 0;
  1171. peakResident = 0;
  1172. #ifdef _WIN32
  1173. PROCESS_MEMORY_COUNTERS pmc;
  1174. if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc)))
  1175. {
  1176. peakVm = pmc.PeakWorkingSetSize;
  1177. peakResident = pmc.PeakWorkingSetSize;
  1178. }
  1179. #else
  1180. static int memfd = -1;
  1181. if (memfd==-1)
  1182. memfd = open("/proc/self/status",O_RDONLY);
  1183. if (memfd==-1)
  1184. return;
  1185. char buf[2048];
  1186. size32_t l = pread(memfd, buf, sizeof(buf)-1, 0L);
  1187. if ((int)l<=0)
  1188. return;
  1189. buf[l] = 0;
  1190. const char *bufptr = buf;
  1191. while (bufptr) {
  1192. if (*bufptr =='\n')
  1193. bufptr++;
  1194. if (!matchExtract("VmPeak:", bufptr, peakVm) &&
  1195. !matchExtract("VmHWM:", bufptr, peakResident))
  1196. {
  1197. //ignore this line
  1198. }
  1199. bufptr = strchr(bufptr, '\n');
  1200. }
  1201. #endif
  1202. }
  1203. #define RXMAX 1000000 // can be 10x bigger but this produces reasonable amounts
  1204. unsigned packetsLasttime;
  1205. __int64 packetsLastrx = -1;
  1206. __int64 packetsLasttx;
  1207. bool getPacketStats(unsigned & tx, unsigned & rx)
  1208. {
  1209. unsigned thistime = msTick();
  1210. JSocketStatistics jstats;
  1211. getSocketStatistics(jstats);
  1212. bool ret = true;
  1213. if(packetsLastrx!=-1)
  1214. {
  1215. tx = (unsigned) ((jstats.writesize-packetsLasttx)*100000/(((__int64)(packetsLasttime-thistime))*RXMAX));
  1216. rx = (unsigned) ((jstats.readsize-packetsLastrx)*100000/(((__int64)(packetsLasttime-thistime))*RXMAX));
  1217. }
  1218. else
  1219. ret = false;
  1220. packetsLastrx = jstats.readsize;
  1221. packetsLasttx = jstats.writesize;
  1222. packetsLasttime = thistime;
  1223. return ret;
  1224. }
  1225. #ifndef _WIN32
  1226. struct UserStatusInfo
  1227. {
  1228. public:
  1229. UserStatusInfo(pid_t _pid)
  1230. {
  1231. pid = _pid;
  1232. }
  1233. bool update()
  1234. {
  1235. StringBuffer fn;
  1236. fn.appendf("/proc/%d/stat", pid);
  1237. char buf[800]; /* about 40 fields, 64-bit decimal is about 20 chars */
  1238. int fd = open(fn.str(), O_RDONLY, 0);
  1239. if (fd==-1)
  1240. return false;
  1241. int rd = read(fd, buf, sizeof(buf)-1);
  1242. close(fd);
  1243. if (rd<80)
  1244. return false;
  1245. buf[rd] = 0;
  1246. char *s = strchr(buf,'(');
  1247. if (!s)
  1248. return false;
  1249. s++;
  1250. unsigned i = 0;
  1251. while (*s&&(*s!=')')&&(i<15))
  1252. cmd[i++] = *(s++);
  1253. if (*s != ')')
  1254. return false;
  1255. cmd[i] = 0;
  1256. s+=3; // Skip ") X" where X is the state
  1257. //The PID of the parent process
  1258. const char *num;
  1259. s = skipnumfld(s,num);
  1260. //int ppid = atoi(num);
  1261. // skip pgrp, session, tty_num, tpgid, flags, min_flt, cmin_flt, maj_flt, cmaj_flt
  1262. for (i=0;i<9;i++)
  1263. s = skipnumfld(s,num);
  1264. //utime - user mode time in clock ticks.
  1265. s = skipnumfld(s,num);
  1266. //printf("**N'%s'\n",num);
  1267. time.user = (unsigned)atoi64_l(num,strlen(num));
  1268. //stime - amount of time scheduled in kernel mode in clock ticks
  1269. s = skipnumfld(s,num);
  1270. //printf("**N'%s'\n",num);
  1271. time.system = (unsigned)atoi64_l(num,strlen(num));
  1272. return true;
  1273. }
  1274. public:
  1275. pid_t pid;
  1276. char cmd[16];
  1277. UserSystemTime_t time;
  1278. private:
  1279. char *skipnumfld(char *s, const char *&num)
  1280. {
  1281. while (*s && isspace(*s))
  1282. s++;
  1283. num = s;
  1284. if ((*s=='-')||(*s=='+'))
  1285. s++;
  1286. while (*s && isdigit(*s))
  1287. s++;
  1288. if (*s==' ')
  1289. *(s++) = 0; // terminate num
  1290. while (*s && isspace(*s))
  1291. s++;
  1292. return s;
  1293. }
  1294. };
  1295. struct CProcInfo: extends CInterface
  1296. {
  1297. UserStatusInfo info;
  1298. UserSystemTime_t delta;
  1299. bool active;
  1300. bool first;
  1301. CProcInfo(int _pid) : info(_pid)
  1302. {
  1303. active = false;
  1304. first = true;
  1305. }
  1306. inline pid_t pid() const { return info.pid; }
  1307. bool load()
  1308. {
  1309. UserSystemTime_t prev = info.time;
  1310. if (!info.update())
  1311. return false;
  1312. active = true;
  1313. if (first)
  1314. first = false;
  1315. else {
  1316. delta.system = info.time.system-prev.system;
  1317. delta.user = info.time.user-prev.user;
  1318. }
  1319. return true;
  1320. }
  1321. };
  1322. class CProcessMonitor
  1323. {
  1324. CIArrayOf<CProcInfo> processes;
  1325. unsigned tot_time;
  1326. bool busy;
  1327. CriticalSection sect;
  1328. static int compare(CInterface * const *i1, CInterface * const *i2)
  1329. {
  1330. CProcInfo *pi1 = QUERYINTERFACE(*i1,CProcInfo);
  1331. CProcInfo *pi2 = QUERYINTERFACE(*i2,CProcInfo);
  1332. return pi2->delta.system+pi2->delta.user-pi1->delta.system-pi1->delta.user;
  1333. }
  1334. public:
  1335. CProcessMonitor()
  1336. {
  1337. busy = false;
  1338. }
  1339. void scan()
  1340. {
  1341. #ifdef __linux__
  1342. ForEachItemIn(i1,processes)
  1343. processes.item(i1).active = false;
  1344. DIR *dir = opendir("/proc");
  1345. loop {
  1346. CriticalBlock b(sect);
  1347. struct dirent *ent = readdir(dir);
  1348. if (!ent)
  1349. break;
  1350. if ((ent->d_name[0]>='0')&&(ent->d_name[0]<='9')) {
  1351. int pid = atoi(ent->d_name);
  1352. if (pid) {
  1353. CProcInfo *pi = NULL;
  1354. ForEachItemIn(i2,processes) {
  1355. if (processes.item(i2).pid() == pid) {
  1356. pi = &processes.item(i2);
  1357. break;
  1358. }
  1359. }
  1360. if (!pi) {
  1361. pi = new CProcInfo(pid);
  1362. processes.append(*pi);
  1363. }
  1364. pi->load();
  1365. }
  1366. }
  1367. }
  1368. closedir(dir);
  1369. tot_time = 0;
  1370. ForEachItemInRev(i3,processes) {
  1371. CProcInfo &pi = processes.item(i3);
  1372. if (pi.active)
  1373. tot_time += pi.delta.system+pi.delta.user;
  1374. else
  1375. processes.remove(i3);
  1376. }
  1377. #endif
  1378. #if defined (__FreeBSD__) || defined (__APPLE__)
  1379. UNIMPLEMENTED;
  1380. #endif
  1381. }
  1382. void print(unsigned n,StringBuffer &str)
  1383. {
  1384. if (!tot_time)
  1385. return;
  1386. assertex(n);
  1387. processes.sort(compare);
  1388. StringBuffer name;
  1389. ForEachItemIn(i1,processes) {
  1390. CProcInfo &pi = processes.item(i1);
  1391. if ((pi.delta.system==0)&&(pi.delta.user==0))
  1392. break;
  1393. getThreadName(pi.pid(),0,name.clear());
  1394. str.appendf("\n TT: PI=%d PN=%s PC=%d ST=%d UT=%d%s%s",
  1395. pi.pid(),pi.info.cmd,(pi.delta.system+pi.delta.user)*100/tot_time,pi.delta.system,pi.delta.user,name.length()?" TN=":"",name.str());
  1396. if (--n==0)
  1397. break;
  1398. }
  1399. }
  1400. void printBusy(unsigned pc,StringBuffer &str)
  1401. {
  1402. if (pc>90) {
  1403. scan();
  1404. if (busy)
  1405. print(3,str); // print top 3
  1406. else
  1407. busy = true;
  1408. }
  1409. else {
  1410. busy = false;
  1411. processes.kill();
  1412. }
  1413. }
  1414. };
  1415. #ifndef HZ
  1416. #define HZ 100
  1417. #endif
  1418. #define IDE0_MAJOR 3
  1419. #define SCSI_DISK0_MAJOR 8
  1420. #define SCSI_DISK1_MAJOR 65
  1421. #define SCSI_DISK7_MAJOR 71
  1422. #define SCSI_DISK10_MAJOR 128
  1423. #define SCSI_DISK17_MAJOR 135
  1424. #define IDE1_MAJOR 22
  1425. #define IDE2_MAJOR 33
  1426. #define IDE3_MAJOR 34
  1427. #define IDE4_MAJOR 56
  1428. #define IDE5_MAJOR 57
  1429. #define IDE6_MAJOR 88
  1430. #define IDE7_MAJOR 89
  1431. #define IDE8_MAJOR 90
  1432. #define IDE9_MAJOR 91
  1433. #define COMPAQ_SMART2_MAJOR 72
  1434. #define IDE_DISK_MAJOR(M) ((M) == IDE0_MAJOR || (M) == IDE1_MAJOR || \
  1435. (M) == IDE2_MAJOR || (M) == IDE3_MAJOR || \
  1436. (M) == IDE4_MAJOR || (M) == IDE5_MAJOR || \
  1437. (M) == IDE6_MAJOR || (M) == IDE7_MAJOR || \
  1438. (M) == IDE8_MAJOR || (M) == IDE9_MAJOR)
  1439. #define SCSI_DISK_MAJOR(M) ((M) == SCSI_DISK0_MAJOR || \
  1440. ((M) >= SCSI_DISK1_MAJOR && (M) <= SCSI_DISK7_MAJOR) || \
  1441. ((M) >= SCSI_DISK10_MAJOR && (M) <= SCSI_DISK17_MAJOR))
  1442. #define OTHER_DISK_MAJOR(M) ((M) == COMPAQ_SMART2_MAJOR) // by investigation!
  1443. class CExtendedStats // Disk network and cpu stats
  1444. {
  1445. struct blkio_info
  1446. {
  1447. unsigned rd_ios; // Read I/O operations
  1448. unsigned rd_merges; // Reads merged
  1449. __uint64 rd_sectors; // Sectors read
  1450. unsigned rd_ticks; // Time in queue + service for read
  1451. unsigned wr_ios; // Write I/O operations
  1452. unsigned wr_merges; // Writes merged
  1453. __uint64 wr_sectors; // Sectors written
  1454. unsigned wr_ticks; // Time in queue + service for write
  1455. unsigned ticks; // Time of requests in queue
  1456. unsigned aveq; // Average queue length
  1457. };
  1458. struct cpu_info
  1459. {
  1460. __uint64 user;
  1461. __uint64 system;
  1462. __uint64 idle;
  1463. __uint64 iowait;
  1464. };
  1465. struct net_info
  1466. {
  1467. __uint64 rxbytes;
  1468. __uint64 rxpackets;
  1469. __uint64 rxerrors;
  1470. __uint64 rxdrops;
  1471. __uint64 txbytes;
  1472. __uint64 txpackets;
  1473. __uint64 txerrors;
  1474. __uint64 txdrops;
  1475. };
  1476. struct part_info
  1477. {
  1478. unsigned int major;
  1479. unsigned int minor;
  1480. char name[32];
  1481. };
  1482. part_info *partition;
  1483. unsigned nparts;
  1484. blkio_info *newblkio;
  1485. blkio_info *oldblkio;
  1486. cpu_info newcpu;
  1487. unsigned numcpu;
  1488. cpu_info oldcpu;
  1489. cpu_info cpu;
  1490. net_info oldnet;
  1491. net_info newnet;
  1492. unsigned ncpu;
  1493. bool first;
  1494. char *kbuf;
  1495. size32_t kbufsz;
  1496. size32_t kbufmax;
  1497. unsigned short kbufcrc;
  1498. __uint64 totalcpu;
  1499. unsigned ndisks;
  1500. int isdisk(unsigned int major, unsigned int minor)
  1501. {
  1502. if (IDE_DISK_MAJOR(major))
  1503. return ((minor&0x3F)==0);
  1504. if (SCSI_DISK_MAJOR(major))
  1505. return ((minor&0x0F)==0);
  1506. if (OTHER_DISK_MAJOR(major))
  1507. return ((minor&0x0F)==0);
  1508. return 0;
  1509. }
  1510. bool getNextCPU()
  1511. {
  1512. oldcpu = newcpu;
  1513. if (!ncpu) {
  1514. unsigned speed;
  1515. getCpuInfo(ncpu, speed);
  1516. if (!ncpu)
  1517. ncpu = 1;
  1518. }
  1519. FILE* cpufp = fopen("/proc/stat", "r");
  1520. if (!cpufp) {
  1521. memset(&cpu,0,sizeof(cpu));
  1522. totalcpu = 0;
  1523. return false;
  1524. }
  1525. char ln[256];
  1526. while (fgets(ln, sizeof(ln), cpufp)) {
  1527. if (strncmp(ln, "cpu ", 4)==0) {
  1528. int items;
  1529. __uint64 nice, irq, softirq;
  1530. items = sscanf(ln,
  1531. "cpu %llu %llu %llu %llu %llu %llu %llu",
  1532. &newcpu.user, &nice,
  1533. &newcpu.system,
  1534. &newcpu.idle,
  1535. &newcpu.iowait,
  1536. &irq, &softirq);
  1537. newcpu.user += nice;
  1538. if (items == 4)
  1539. newcpu.iowait = 0;
  1540. if (items == 7)
  1541. newcpu.system += irq + softirq;
  1542. break;
  1543. }
  1544. }
  1545. fclose(cpufp);
  1546. cpu.user = newcpu.user - oldcpu.user;
  1547. cpu.system = newcpu.system - oldcpu.system;
  1548. cpu.idle = newcpu.idle - oldcpu.idle;
  1549. cpu.iowait = newcpu.iowait - oldcpu.iowait;
  1550. totalcpu = (cpu.user + cpu.system + cpu.idle + cpu.iowait);
  1551. return true;
  1552. }
  1553. bool getDiskInfo()
  1554. {
  1555. char ln[256];
  1556. part_info pi;
  1557. FILE* diskfp = fopen("/proc/diskstats", "r");
  1558. if (!diskfp)
  1559. return false;
  1560. if (!newblkio) {
  1561. nparts = 0;
  1562. while (fgets(ln, sizeof(ln), diskfp)) {
  1563. unsigned reads = 0;
  1564. if (sscanf(ln, "%4d %4d %31s %u", &pi.major, &pi.minor, pi.name, &reads) == 4) {
  1565. unsigned p = 0;
  1566. while ((p<nparts) && (partition[p].major != pi.major || partition[p].minor != pi.minor))
  1567. p++;
  1568. if ((p==nparts) && reads && isdisk(pi.major,pi.minor)) {
  1569. nparts++;
  1570. partition = (part_info *)realloc(partition,nparts*sizeof(part_info));
  1571. partition[p] = pi;
  1572. }
  1573. }
  1574. }
  1575. free(newblkio);
  1576. free(oldblkio);
  1577. newblkio = (blkio_info *)calloc(sizeof(blkio_info),nparts);
  1578. oldblkio = (blkio_info* )calloc(sizeof(blkio_info),nparts);
  1579. }
  1580. rewind(diskfp);
  1581. // could skip lines we know aren't significant here
  1582. while (fgets(ln, sizeof(ln), diskfp)) {
  1583. blkio_info blkio;
  1584. unsigned items = sscanf(ln, "%4d %4d %*s %u %u %llu %u %u %u %llu %u %*u %u %u",
  1585. &pi.major, &pi.minor,
  1586. &blkio.rd_ios, &blkio.rd_merges,
  1587. &blkio.rd_sectors, &blkio.rd_ticks,
  1588. &blkio.wr_ios, &blkio.wr_merges,
  1589. &blkio.wr_sectors, &blkio.wr_ticks,
  1590. &blkio.ticks, &blkio.aveq);
  1591. if (items == 6) {
  1592. // hopefully not this branch!
  1593. blkio.rd_sectors = blkio.rd_merges;
  1594. blkio.wr_sectors = blkio.rd_ticks;
  1595. blkio.rd_ios = 0;
  1596. blkio.rd_merges = 0;
  1597. blkio.rd_ticks = 0;
  1598. blkio.wr_ios = 0;
  1599. blkio.wr_merges = 0;
  1600. blkio.wr_ticks = 0;
  1601. blkio.ticks = 0;
  1602. blkio.aveq = 0;
  1603. items = 12;
  1604. }
  1605. if (items == 12) {
  1606. for (unsigned p = 0; p < nparts; p++) {
  1607. if (partition[p].major == pi.major && partition[p].minor == pi.minor) {
  1608. newblkio[p] = blkio;
  1609. break;
  1610. }
  1611. }
  1612. }
  1613. }
  1614. fclose(diskfp);
  1615. return true;
  1616. }
  1617. bool getNetInfo()
  1618. {
  1619. FILE *netfp = fopen("/proc/net/dev", "r");
  1620. if (!netfp)
  1621. return false;
  1622. char ln[512];
  1623. // Read two lines
  1624. if (!fgets(ln, sizeof(ln), netfp) || !fgets(ln, sizeof(ln), netfp)) {
  1625. fclose(netfp);
  1626. return false;
  1627. }
  1628. unsigned txskip = 2;
  1629. bool hasbyt = false;
  1630. if (strstr(ln,"compressed")) {
  1631. txskip = 4;
  1632. hasbyt = true;
  1633. }
  1634. else if (strstr(ln,"bytes"))
  1635. hasbyt = true;
  1636. while (fgets(ln, sizeof(ln), netfp)) {
  1637. const char *s = ln;
  1638. skipSp(s);
  1639. if (strncmp(s, "eth0:", 5)==0) { // may want eth1 at some point!
  1640. s+=5;
  1641. if (hasbyt) {
  1642. newnet.rxbytes = readDecNum(s);
  1643. skipSp(s);
  1644. }
  1645. else
  1646. newnet.rxbytes = 0;
  1647. newnet.rxpackets = readDecNum(s);
  1648. skipSp(s);
  1649. newnet.rxerrors = readDecNum(s);
  1650. skipSp(s);
  1651. newnet.rxdrops = readDecNum(s);
  1652. skipSp(s);
  1653. while (txskip--) {
  1654. readDecNum(s);
  1655. skipSp(s);
  1656. }
  1657. if (hasbyt) {
  1658. newnet.txbytes = readDecNum(s);
  1659. skipSp(s);
  1660. }
  1661. else
  1662. newnet.txbytes = 0;
  1663. newnet.txpackets = readDecNum(s);
  1664. skipSp(s);
  1665. newnet.txerrors = readDecNum(s);
  1666. skipSp(s);
  1667. newnet.txdrops = readDecNum(s);
  1668. break;
  1669. }
  1670. }
  1671. fclose(netfp);
  1672. return true;
  1673. }
  1674. size32_t getKLog(const char *&data)
  1675. {
  1676. #ifdef __linux__
  1677. if (kbufmax) {
  1678. loop {
  1679. char *newkbuf = (char *)malloc(kbufmax);
  1680. if (!newkbuf)
  1681. break; // OOM - abort logging
  1682. size32_t newkbufsz = klogctl(3,newkbuf,kbufmax);
  1683. if ((int)newkbufsz<0) {
  1684. ERRLOG("klogctl error %d",errno);
  1685. free(newkbuf);
  1686. data = NULL;
  1687. return 0;
  1688. }
  1689. if (newkbufsz<kbufmax) {
  1690. unsigned short crc = chksum16(newkbuf,newkbufsz);
  1691. if (kbuf) {
  1692. if (crc!=kbufcrc) {
  1693. unsigned ofs = 0;
  1694. if ((newkbufsz>=kbufsz)) {
  1695. for (unsigned i=0;i+3<kbufsz;i++) { // not very quick!
  1696. if (memcmp(kbuf+i,newkbuf,kbufsz-i)==0) {
  1697. ofs = kbufsz-i;
  1698. break;
  1699. }
  1700. }
  1701. }
  1702. size32_t ret = newkbufsz-ofs;
  1703. if (ret>3) {
  1704. kbufcrc = crc;
  1705. free(kbuf);
  1706. kbuf = newkbuf;
  1707. kbufsz = newkbufsz;
  1708. data = kbuf+ofs;
  1709. return ret;
  1710. }
  1711. }
  1712. }
  1713. else { // first time {
  1714. kbuf = newkbuf;
  1715. newkbuf = NULL;
  1716. kbufsz = newkbufsz;
  1717. }
  1718. free(newkbuf);
  1719. data = NULL;
  1720. return 0;
  1721. }
  1722. if (kbufmax>0x100000) {
  1723. // don't believe!
  1724. ERRLOG("klogctl buffer too big!");
  1725. free(newkbuf);
  1726. break;
  1727. }
  1728. kbufmax += 0x1000;
  1729. free(newkbuf);
  1730. }
  1731. kbufmax = 0;
  1732. kbufsz = 0;
  1733. free(kbuf);
  1734. kbuf = NULL;
  1735. }
  1736. #endif
  1737. data = NULL;
  1738. return 0;
  1739. }
  1740. inline double perSec(double v,double deltams)
  1741. {
  1742. return 1000.0*v/deltams;
  1743. }
  1744. public:
  1745. unsigned getCPU()
  1746. {
  1747. if (!getNextCPU())
  1748. return (unsigned)-1;
  1749. if (totalcpu==0)
  1750. return 0;
  1751. unsigned ret = (unsigned)((totalcpu-cpu.idle)*100/totalcpu);
  1752. if (ret>100)
  1753. ret = 100;
  1754. return ret;
  1755. }
  1756. CExtendedStats(bool printklog)
  1757. {
  1758. partition = (part_info *)malloc(sizeof(part_info));
  1759. nparts = 0;
  1760. newblkio = NULL;
  1761. oldblkio = NULL;
  1762. first = true;
  1763. ncpu = 0;
  1764. kbuf = NULL;
  1765. kbufsz = 0;
  1766. kbufcrc = 0;
  1767. memset(&oldcpu, 0, sizeof(oldcpu));
  1768. memset(&newcpu, 0, sizeof(newcpu));
  1769. memset(&cpu, 0, sizeof(cpu));
  1770. totalcpu = 0;
  1771. numcpu = 0;
  1772. memset(&oldnet, 0, sizeof(oldnet));
  1773. memset(&newnet, 0, sizeof(newnet));
  1774. ndisks = 0;
  1775. if (printklog)
  1776. kbufmax = 0x1000;
  1777. else
  1778. kbufmax = 0;
  1779. }
  1780. ~CExtendedStats()
  1781. {
  1782. free(partition);
  1783. free(kbuf);
  1784. free(newblkio);
  1785. free(oldblkio);
  1786. }
  1787. bool getLine(StringBuffer &out)
  1788. {
  1789. blkio_info *t = oldblkio;
  1790. oldblkio = newblkio;
  1791. newblkio = t;
  1792. oldnet = newnet;
  1793. #ifdef USE_OLD_PU
  1794. if (!getNextCPU())
  1795. return false; // required
  1796. #endif
  1797. bool gotdisk = getDiskInfo()&&nparts;
  1798. bool gotnet = getNetInfo();
  1799. if (first) {
  1800. first = false;
  1801. return false;
  1802. }
  1803. double deltams = ((double)totalcpu*1000) / ncpu / HZ;
  1804. if (deltams<10)
  1805. return false;
  1806. if (gotdisk) {
  1807. if (out.length()&&(out.charAt(out.length()-1)!=' '))
  1808. out.append(' ');
  1809. out.append("DSK: ");
  1810. for (unsigned p = 0; p < nparts; p++) {
  1811. unsigned rd_ios = newblkio[p].rd_ios - oldblkio[p].rd_ios;
  1812. __uint64 rd_sectors = newblkio[p].rd_sectors - oldblkio[p].rd_sectors;
  1813. unsigned wr_ios = newblkio[p].wr_ios - oldblkio[p].wr_ios;
  1814. __uint64 wr_sectors = newblkio[p].wr_sectors - oldblkio[p].wr_sectors;
  1815. unsigned ticks = newblkio[p].ticks - oldblkio[p].ticks;
  1816. unsigned busy = (unsigned)(100*ticks/deltams);
  1817. if (busy>100)
  1818. busy = 100;
  1819. out.appendf("[%s] r/s=%0.1f kr/s=%0.1f w/s=%0.1f kw/s=%0.1f bsy=%d",
  1820. partition[p].name,
  1821. perSec(rd_ios,deltams),
  1822. perSec(rd_sectors,deltams)/2.0,
  1823. perSec(wr_ios,deltams),
  1824. perSec(wr_sectors,deltams)/2.0,
  1825. busy);
  1826. out.append(' ');
  1827. }
  1828. }
  1829. if (gotnet) {
  1830. out.append("NIC: ");
  1831. __uint64 rxbytes = newnet.rxbytes-oldnet.rxbytes;
  1832. __uint64 rxpackets = newnet.rxpackets-oldnet.rxpackets;
  1833. __uint64 txbytes = newnet.txbytes-oldnet.txbytes;
  1834. __uint64 txpackets = newnet.txpackets-oldnet.txpackets;
  1835. out.appendf("rxp/s=%0.1f rxk/s=%0.1f txp/s=%0.1f txk/s=%0.1f",
  1836. perSec(rxpackets,deltams),
  1837. perSec(rxbytes/1024.0,deltams),
  1838. perSec(txpackets,deltams),
  1839. perSec(txbytes/1024.0,deltams));
  1840. out.append(' ');
  1841. }
  1842. if (totalcpu)
  1843. out.appendf("CPU: usr=%d sys=%d iow=%d idle=%d", (unsigned)(cpu.user*100/totalcpu), (unsigned)(cpu.system*100/totalcpu), (unsigned)(cpu.iowait*100/totalcpu), (unsigned)(cpu.idle*100/totalcpu));
  1844. return true;
  1845. }
  1846. #define KERN_EMERG "<0>" // system is unusable
  1847. #define KERN_ALERT "<1>" // action must be taken immediately
  1848. #define KERN_CRIT "<2>" // critical conditions
  1849. #define KERN_ERR "<3>" // error conditions
  1850. #define KERN_WARNING "<4>" // warning conditions
  1851. #define KERN_NOTICE "<5>" // normal but significant condition
  1852. #define KERN_INFO "<6>" // informational
  1853. #define KERN_DEBUG "<7>" // debug-level messages
  1854. #define KMSGTEST(S) if (memcmp(p,S,3)==0) { ln.append(#S); level = p[1]-'0'; }
  1855. void printKLog(IPerfMonHook *hook)
  1856. {
  1857. const char *p;
  1858. size32_t sz = getKLog(p);
  1859. StringBuffer ln;
  1860. const char *e = p+sz;
  1861. while (p!=e) {
  1862. if (*p=='<') {
  1863. ln.clear();
  1864. int level = -1;
  1865. KMSGTEST(KERN_EMERG)
  1866. else KMSGTEST(KERN_ALERT)
  1867. else KMSGTEST(KERN_CRIT)
  1868. else KMSGTEST(KERN_ERR)
  1869. else KMSGTEST(KERN_WARNING)
  1870. else KMSGTEST(KERN_NOTICE)
  1871. else KMSGTEST(KERN_INFO)
  1872. else KMSGTEST(KERN_DEBUG)
  1873. else {
  1874. ln.append("KERN_UNKNOWN");
  1875. p -= 3;
  1876. }
  1877. p += 3;
  1878. ln.append(": ");
  1879. while ((p!=e)&&(*p!='\n'))
  1880. ln.append(*(p++));
  1881. if (hook)
  1882. hook->log(level, ln.str());
  1883. else
  1884. PROGLOG("%s",ln.str());
  1885. }
  1886. while ((p!=e)&&(*p!='\n'))
  1887. p++;
  1888. if (p!=e)
  1889. p++;
  1890. }
  1891. }
  1892. };
  1893. #endif
  1894. #ifdef _WIN32
  1895. static struct CNtKernelInformation
  1896. {
  1897. CNtKernelInformation()
  1898. {
  1899. NtQuerySystemInformation = (PROCNTQSI)GetProcAddress(
  1900. GetModuleHandle("ntdll"),
  1901. "NtQuerySystemInformation"
  1902. );
  1903. NtQueryInformationProcess = (PROCNTQIP)GetProcAddress(
  1904. GetModuleHandle("ntdll"),
  1905. "NtQueryInformationProcess"
  1906. );
  1907. // GetSystemTimes not available on earlier versions of Windows - NtQuerySystemInformation not consistent on later ones. So use GetSystemTimes if available
  1908. pGetSystemTimes = (PROCNTGST)GetProcAddress(
  1909. GetModuleHandle("kernel32"),
  1910. "GetSystemTimes"
  1911. );
  1912. NtQuerySystemInformation(SystemBasicInformation,&SysBaseInfo,sizeof(SysBaseInfo),NULL);
  1913. }
  1914. PROCNTQSI NtQuerySystemInformation;
  1915. PROCNTQIP NtQueryInformationProcess;
  1916. PROCNTGST pGetSystemTimes;
  1917. SYSTEM_BASIC_INFORMATION SysBaseInfo;
  1918. } NtKernelFunctions;
  1919. #endif
  1920. struct PortStats
  1921. {
  1922. unsigned port;
  1923. unsigned drops;
  1924. unsigned rx_queue;
  1925. };
  1926. typedef MapBetween<unsigned, unsigned, PortStats, PortStats> MapPortToPortStats;
  1927. class CUdpStatsReporter
  1928. {
  1929. public:
  1930. CUdpStatsReporter()
  1931. {
  1932. dropsCol = -1;
  1933. portCol = -1;
  1934. uidCol = -1;
  1935. queueCol = -1;
  1936. }
  1937. bool reportUdpInfo(unsigned traceLevel)
  1938. {
  1939. #ifdef _WIN32
  1940. return false;
  1941. #else
  1942. if (uidCol==-1 && columnNames.length())
  1943. return false;
  1944. FILE *netfp = fopen("/proc/net/udp", "r");
  1945. if (!netfp)
  1946. return false;
  1947. char ln[512];
  1948. // Read header
  1949. if (!fgets(ln, sizeof(ln), netfp)) {
  1950. fclose(netfp);
  1951. return false;
  1952. }
  1953. if (!columnNames.length())
  1954. {
  1955. columnNames.appendList(ln, " ");
  1956. ForEachItemInRev(idx, columnNames)
  1957. {
  1958. if (streq(columnNames.item(idx), "rem_address"))
  1959. columnNames.add("rem_port", idx+1);
  1960. else if (streq(columnNames.item(idx), "local_address"))
  1961. columnNames.add("local_port", idx+1);
  1962. }
  1963. ForEachItemIn(idx2, columnNames)
  1964. {
  1965. if (streq(columnNames.item(idx2), "drops"))
  1966. dropsCol = idx2;
  1967. else if (streq(columnNames.item(idx2), "local_port"))
  1968. portCol = idx2;
  1969. else if (streq(columnNames.item(idx2), "rx_queue"))
  1970. queueCol = idx2;
  1971. else if (streq(columnNames.item(idx2), "uid"))
  1972. uidCol = idx2;
  1973. }
  1974. if (portCol == -1 || queueCol == -1 || uidCol == -1)
  1975. {
  1976. uidCol = -1;
  1977. fclose(netfp);
  1978. return false;
  1979. }
  1980. }
  1981. int myUid = geteuid();
  1982. while (fgets(ln, sizeof(ln), netfp))
  1983. {
  1984. StringArray cols;
  1985. cols.appendList(ln, " :");
  1986. if (cols.length() >= columnNames.length() && atoi(cols.item(uidCol))==myUid)
  1987. {
  1988. unsigned queue = strtoul(cols.item(queueCol), NULL, 16);
  1989. unsigned drops = 0;
  1990. if (dropsCol >= 0)
  1991. drops = strtoul(cols.item(dropsCol), NULL, 10);
  1992. if (queue || drops)
  1993. {
  1994. unsigned port = strtoul(cols.item(portCol), NULL, 16);
  1995. if (traceLevel > 0)
  1996. DBGLOG("From /proc/net/udp: port %d rx_queue=%u drops=%u", port, queue, drops);
  1997. PortStats *ret = map.getValue(port);
  1998. if (!ret)
  1999. {
  2000. PortStats e = {port, 0, 0};
  2001. map.setValue(port, e);
  2002. ret = map.getValue(port);
  2003. assertex(ret);
  2004. }
  2005. if (queue > ret->rx_queue)
  2006. {
  2007. DBGLOG("UDP queue: new max rx_queue: port %d rx_queue=%u drops=%u", port, queue, drops);
  2008. ret->rx_queue = queue;
  2009. }
  2010. if (drops > ret->drops)
  2011. {
  2012. LOG(MCoperatorError, unknownJob, "DROPPED UDP PACKETS: port %d rx_queue=%u (peak %u) drops=%u (total %i)", port, queue, ret->rx_queue, drops-ret->drops, drops);
  2013. ret->drops = drops;
  2014. }
  2015. }
  2016. }
  2017. }
  2018. fclose(netfp);
  2019. return true;
  2020. #endif
  2021. }
  2022. private:
  2023. MapPortToPortStats map;
  2024. StringArray columnNames;
  2025. int dropsCol;
  2026. int portCol;
  2027. int uidCol;
  2028. int queueCol;
  2029. };
  2030. class CSnmpStatsReporter
  2031. {
  2032. public:
  2033. CSnmpStatsReporter()
  2034. {
  2035. inErrorsCol = -1;
  2036. prevErrors = 0;
  2037. }
  2038. bool reportSnmpInfo()
  2039. {
  2040. #ifdef _WIN32
  2041. return false;
  2042. #else
  2043. if (inErrorsCol==-1 && columnNames.length())
  2044. return false;
  2045. FILE *netfp = fopen("/proc/net/snmp", "r");
  2046. if (!netfp)
  2047. return false;
  2048. char ln[512];
  2049. bool ok = false;
  2050. while (fgets(ln, sizeof(ln), netfp))
  2051. {
  2052. if (strncmp(ln, "Udp:", 4)==0)
  2053. {
  2054. if (!columnNames.length())
  2055. {
  2056. columnNames.appendList(ln, " ");
  2057. ForEachItemIn(idx, columnNames)
  2058. {
  2059. if (streq(columnNames.item(idx), "InErrors"))
  2060. inErrorsCol = idx;
  2061. }
  2062. if (inErrorsCol == -1)
  2063. break;
  2064. }
  2065. if (fgets(ln, sizeof(ln), netfp))
  2066. {
  2067. StringArray cols;
  2068. cols.appendList(ln, " ");
  2069. if (cols.length() >= columnNames.length())
  2070. {
  2071. ok = true;
  2072. unsigned errors = strtoul(cols.item(inErrorsCol), NULL, 10);
  2073. if (errors > prevErrors)
  2074. LOG(MCoperatorError, unknownJob, "UDP InErrors: %u (total %u)", errors-prevErrors, errors);
  2075. prevErrors = errors;
  2076. }
  2077. }
  2078. break;
  2079. }
  2080. }
  2081. fclose(netfp);
  2082. return ok;
  2083. #endif
  2084. }
  2085. private:
  2086. StringArray columnNames;
  2087. int inErrorsCol;
  2088. unsigned prevErrors;
  2089. };
  2090. static class CMemoryUsageReporter: public Thread
  2091. {
  2092. bool term;
  2093. unsigned interval;
  2094. Semaphore sem;
  2095. PerfMonMode traceMode;
  2096. Linked<IPerfMonHook> hook;
  2097. unsigned latestCPU;
  2098. #if defined(USE_OLD_PU) || defined(_WIN32)
  2099. double dbIdleTime;
  2100. double dbSystemTime;
  2101. #endif
  2102. #ifdef _WIN32
  2103. LONG status;
  2104. LARGE_INTEGER liOldIdleTime;
  2105. LARGE_INTEGER liOldSystemTime;
  2106. #else
  2107. double OldIdleTime;
  2108. double OldSystemTime;
  2109. CProcessMonitor procmon;
  2110. CExtendedStats extstats;
  2111. #endif
  2112. StringBuffer primaryfs;
  2113. StringBuffer secondaryfs;
  2114. CriticalSection sect; // for getSystemTraceInfo
  2115. CSnmpStatsReporter snmpStats;
  2116. CUdpStatsReporter udpStats;
  2117. public:
  2118. CMemoryUsageReporter(unsigned _interval, PerfMonMode _traceMode, IPerfMonHook * _hook, bool printklog)
  2119. : Thread("CMemoryUsageReporter"), traceMode(_traceMode)
  2120. #ifndef _WIN32
  2121. , extstats(printklog)
  2122. #endif
  2123. {
  2124. interval = _interval;
  2125. hook.set(_hook);
  2126. term = false;
  2127. latestCPU = 0;
  2128. // UDP stats reported unless explicitly disabled
  2129. Owned<IProperties> conf = createProperties(CONFIG_DIR PATHSEPSTR "environment.conf", true);
  2130. if (conf->getPropBool("udp_stats", true))
  2131. traceMode |= PerfMonUDP;
  2132. #ifdef _WIN32
  2133. memset(&liOldIdleTime,0,sizeof(liOldIdleTime));
  2134. memset(&liOldSystemTime,0,sizeof(liOldSystemTime));
  2135. dbIdleTime = 0;
  2136. primaryfs.append("C:");
  2137. #else
  2138. FILE* procfp;
  2139. procfp = fopen("/proc/uptime", "r");
  2140. int matched = 0;
  2141. if (procfp) {
  2142. matched = fscanf(procfp, "%lf %lf\n", &OldSystemTime, &OldIdleTime);
  2143. fclose(procfp);
  2144. }
  2145. if (!procfp || matched != 2)
  2146. {
  2147. OldSystemTime = 0;
  2148. OldIdleTime = 0;
  2149. }
  2150. primaryfs.append("/");
  2151. #endif
  2152. }
  2153. void setPrimaryFileSystem(char const * _primaryfs)
  2154. {
  2155. CriticalBlock block(sect);
  2156. primaryfs.clear();
  2157. if(_primaryfs)
  2158. primaryfs.append(_primaryfs);
  2159. }
  2160. void setSecondaryFileSystem(char const * _secondaryfs)
  2161. {
  2162. CriticalBlock block(sect);
  2163. secondaryfs.clear();
  2164. if(_secondaryfs)
  2165. secondaryfs.append(_secondaryfs);
  2166. }
  2167. void getSystemTraceInfo(StringBuffer &str, PerfMonMode mode)
  2168. {
  2169. CriticalBlock block(sect);
  2170. #ifdef _WIN32
  2171. if (NtKernelFunctions.pGetSystemTimes) {
  2172. LARGE_INTEGER idle, kernel, user;
  2173. NtKernelFunctions.pGetSystemTimes(&idle, &kernel, &user);
  2174. // note - kernel time seems to include idle time
  2175. if(liOldIdleTime.QuadPart != 0) {
  2176. // CurrentValue = NewValue - OldValue
  2177. dbIdleTime = Li2Double(idle) - Li2Double(liOldIdleTime);
  2178. dbSystemTime = (Li2Double(kernel) + Li2Double(user)) - Li2Double(liOldSystemTime);
  2179. // CurrentCpuIdle = IdleTime / SystemTime
  2180. dbIdleTime = dbIdleTime / dbSystemTime;
  2181. // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
  2182. latestCPU = (unsigned) (100.0 - dbIdleTime * 100.0 + 0.5);
  2183. }
  2184. liOldIdleTime = idle;
  2185. liOldSystemTime.QuadPart = user.QuadPart + kernel.QuadPart;
  2186. } else {
  2187. SYSTEM_PERFORMANCE_INFORMATION SysPerfInfo;
  2188. SYSTEM_TIME_INFORMATION SysTimeInfo;
  2189. NtKernelFunctions.NtQuerySystemInformation(SystemTimeInformation,&SysTimeInfo,sizeof(SysTimeInfo),0);
  2190. NtKernelFunctions.NtQuerySystemInformation(SystemPerformanceInformation,&SysPerfInfo,sizeof(SysPerfInfo),NULL);
  2191. if(liOldIdleTime.QuadPart != 0) {
  2192. // CurrentValue = NewValue - OldValue
  2193. dbIdleTime = Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
  2194. dbSystemTime = Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);
  2195. // CurrentCpuIdle = IdleTime / SystemTime
  2196. dbIdleTime = dbIdleTime / dbSystemTime;
  2197. // CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
  2198. latestCPU = (unsigned) (100.0 - dbIdleTime * 100.0 / (double)NtKernelFunctions.SysBaseInfo.bKeNumberProcessors + 0.5);
  2199. }
  2200. liOldIdleTime = SysPerfInfo.liIdleTime;
  2201. liOldSystemTime = SysTimeInfo.liKeSystemTime;
  2202. }
  2203. MEMORYSTATUSEX memstatus;
  2204. memstatus.dwLength = sizeof(memstatus);
  2205. GlobalMemoryStatusEx(&memstatus);
  2206. DWORDLONG vmTotal = memstatus.ullTotalVirtual;
  2207. DWORDLONG vmAvail = memstatus.ullAvailVirtual;
  2208. DWORDLONG vmInUse = vmTotal - vmAvail;
  2209. DWORDLONG physTotal = memstatus.ullAvailPhys;
  2210. DWORDLONG physAvail = memstatus.ullTotalPhys;
  2211. DWORDLONG physInUse = physTotal - physAvail;
  2212. ULARGE_INTEGER diskAvailStruct;
  2213. ULARGE_INTEGER diskTotalStruct;
  2214. unsigned __int64 firstDriveTotal = 0;
  2215. unsigned __int64 firstDriveInUse = 0;
  2216. unsigned __int64 secondDriveTotal = 0;
  2217. unsigned __int64 secondDriveInUse = 0;
  2218. if(primaryfs.length())
  2219. {
  2220. diskAvailStruct.QuadPart = 0;
  2221. diskTotalStruct.QuadPart = 0;
  2222. GetDiskFreeSpaceEx(primaryfs.str(), &diskAvailStruct, &diskTotalStruct, 0);
  2223. firstDriveTotal = diskTotalStruct.QuadPart;
  2224. firstDriveInUse = diskTotalStruct.QuadPart - diskAvailStruct.QuadPart;
  2225. }
  2226. if(secondaryfs.length())
  2227. {
  2228. diskAvailStruct.QuadPart = 0;
  2229. diskTotalStruct.QuadPart = 0;
  2230. GetDiskFreeSpaceEx(secondaryfs.str(), &diskAvailStruct, &diskTotalStruct, 0);
  2231. secondDriveTotal = diskTotalStruct.QuadPart;
  2232. secondDriveInUse = diskTotalStruct.QuadPart - diskAvailStruct.QuadPart;
  2233. }
  2234. if(hook)
  2235. hook->processPerfStats(latestCPU, (unsigned)(vmInUse/1024), (unsigned)(vmTotal/1024), firstDriveInUse, firstDriveTotal, secondDriveInUse, secondDriveTotal, getThreadCount());
  2236. if(!mode)
  2237. return;
  2238. if(mode & PerfMonProcMem)
  2239. {
  2240. str.appendf("PU=%3d%%",latestCPU);
  2241. #if 0
  2242. VM_COUNTERS vmc;
  2243. DWORD dwSize = 0;
  2244. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessVmCounters, &vmc, sizeof(vmc), &dwSize);
  2245. str.appendf(" MU=%3u%%",(unsigned)((__int64)vmc.WorkingSetSize*100/(__int64)vmTotal));
  2246. #else
  2247. str.appendf(" MU=%3u%%",(unsigned)((__int64)vmInUse*100/(__int64)vmTotal));
  2248. str.appendf(" PY=%3u%%",(unsigned)((__int64)physInUse*100/(__int64)physTotal));
  2249. if (hook)
  2250. hook->extraLogging(str);
  2251. #ifdef _USE_MALLOC_HOOK
  2252. if (totalMem)
  2253. str.appendf(" TM=%" I64F "d",totalMem);
  2254. #endif
  2255. #endif
  2256. }
  2257. if(mode & PerfMonPackets)
  2258. {
  2259. unsigned tx, rx;
  2260. if(getPacketStats(tx, rx))
  2261. str.appendf(" TX=%3u%% RX=%3u%%", tx, rx);
  2262. else
  2263. str.appendf(" ");
  2264. }
  2265. if(mode & PerfMonDiskUsage)
  2266. {
  2267. if(firstDriveTotal) str.appendf(" D1=%3u%%", (unsigned)(firstDriveInUse*100/firstDriveTotal));
  2268. if(secondDriveTotal) str.appendf(" D2=%3u%%", (unsigned)(secondDriveInUse*100/secondDriveTotal));
  2269. }
  2270. if(mode & PerfMonExtended)
  2271. {
  2272. __IO_COUNTERS ioc;
  2273. KERNEL_USER_TIMES kut;
  2274. POOLED_USAGE_AND_LIMITS put;
  2275. VM_COUNTERS vmc;
  2276. DWORD dwSize;
  2277. DWORD dwHandles;
  2278. dwSize = 0;
  2279. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessVmCounters, &vmc, sizeof(vmc), &dwSize);
  2280. dwHandles = 0;
  2281. dwSize = 0;
  2282. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessHandleCount, &dwHandles, sizeof(dwHandles), &dwSize);
  2283. dwSize = 0;
  2284. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessIoCounters, &ioc, sizeof(ioc), &dwSize);
  2285. dwSize = 0;
  2286. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessTimes, &kut, sizeof(kut), &dwSize);
  2287. dwSize = 0;
  2288. NtKernelFunctions.NtQueryInformationProcess(GetCurrentProcess(), ProcessPooledUsageAndLimits, &put, sizeof(put), &dwSize);
  2289. str.appendf(" WS=%10u ",vmc.WorkingSetSize);
  2290. str.appendf("PP=%10u ",put.PagedPoolUsage);
  2291. str.appendf("NP=%10u ",put.NonPagedPoolUsage);
  2292. str.appendf("HC=%5u ",dwHandles);
  2293. str.appendf("TC=%5u ",getThreadCount());
  2294. str.appendf("IR=%10u ",(unsigned)(ioc.ReadTransferCount/1024));
  2295. str.appendf("IW=%10u ",(unsigned)(ioc.WriteTransferCount/1024));
  2296. str.appendf("IO=%10u ",(unsigned)(ioc.OtherTransferCount/1024));
  2297. str.appendf("KT=%16" I64F "u ",kut.KernelTime);
  2298. str.appendf("UT=%16" I64F "u ",kut.UserTime);
  2299. }
  2300. #else
  2301. bool outofhandles = false;
  2302. #ifdef USE_OLD_PU
  2303. FILE* procfp = fopen("/proc/uptime", "r");
  2304. int matched = 0;
  2305. OldSystemTime = 0;
  2306. if (procfp) {
  2307. matched = fscanf(procfp, "%lf %lf\n", &dbSystemTime, &dbIdleTime);
  2308. fclose(procfp);
  2309. outofhandles = false;
  2310. }
  2311. latestCPU = unsigned(100.0 - (dbIdleTime - OldIdleTime)*100.0/(dbSystemTime - OldSystemTime) + 0.5);
  2312. if (procfp && matched == 2)
  2313. {
  2314. OldSystemTime = dbSystemTime;
  2315. OldIdleTime = dbIdleTime;
  2316. }
  2317. #else
  2318. latestCPU = extstats.getCPU();
  2319. if (latestCPU==(unsigned)-1) {
  2320. outofhandles = true;
  2321. latestCPU = 0;
  2322. }
  2323. #endif
  2324. unsigned __int64 primaryfsTotal = 0;
  2325. unsigned __int64 primaryfsInUse = 0;
  2326. unsigned __int64 secondaryfsTotal = 0;
  2327. unsigned __int64 secondaryfsInUse = 0;
  2328. if(primaryfs.length())
  2329. getDiskUsage(primaryfs.str(), primaryfsTotal, primaryfsInUse);
  2330. if(secondaryfs.length())
  2331. getDiskUsage(secondaryfs.str(), secondaryfsTotal, secondaryfsInUse);
  2332. if(!mode) return;
  2333. unsigned memused=0;
  2334. unsigned memtot=0;
  2335. if(mode & PerfMonProcMem)
  2336. {
  2337. if (!outofhandles)
  2338. str.appendf("PU=%3d%% ", latestCPU);
  2339. else
  2340. str.appendf("PU=OOH ");
  2341. getMemStats(str,memused,memtot);
  2342. if (hook)
  2343. hook->extraLogging(str);
  2344. procmon.printBusy(latestCPU,str);
  2345. }
  2346. if (hook) {
  2347. if (!memtot) {
  2348. unsigned mu;
  2349. unsigned ma;
  2350. unsigned mt;
  2351. unsigned st;
  2352. unsigned su;
  2353. getMemUsage(mu,ma,mt,st,su);
  2354. memused = mu+su;
  2355. memtot = mt+st;
  2356. }
  2357. hook->processPerfStats(latestCPU, memused, memtot, primaryfsInUse, primaryfsTotal, secondaryfsInUse, secondaryfsTotal, getThreadCount());
  2358. }
  2359. if(mode & PerfMonPackets)
  2360. {
  2361. unsigned tx, rx;
  2362. if(getPacketStats(tx, rx))
  2363. str.appendf(" TX=%3u%% RX=%3u%%", tx, rx);
  2364. else
  2365. str.appendf(" ");
  2366. }
  2367. if(mode & PerfMonDiskUsage)
  2368. {
  2369. if(primaryfsTotal) str.appendf(" D1=%3u%%", (unsigned)(primaryfsInUse*100/primaryfsTotal));
  2370. if(secondaryfsTotal) str.appendf(" D2=%3u%%", (unsigned)(secondaryfsInUse*100/secondaryfsTotal));
  2371. }
  2372. if(mode & PerfMonExtended)
  2373. {
  2374. extstats.getLine(str);
  2375. }
  2376. #endif
  2377. }
  2378. #define NAMEDCOUNTPERIOD 60*30
  2379. int run()
  2380. {
  2381. StringBuffer str;
  2382. getSystemTraceInfo(str, traceMode&~PerfMonExtended); // initializes the values so that first one we print is meaningful rather than always saying PU=0%
  2383. if (traceMode&PerfMonUDP)
  2384. {
  2385. snmpStats.reportSnmpInfo();
  2386. udpStats.reportUdpInfo(0);
  2387. }
  2388. CTimeMon tm(NAMEDCOUNTPERIOD*1000);
  2389. while (!term) {
  2390. if (sem.wait(interval))
  2391. break;
  2392. str.clear();
  2393. getSystemTraceInfo(str, traceMode&~PerfMonExtended);
  2394. #ifdef NAMEDCOUNTS
  2395. if (tm.timedout())
  2396. {
  2397. dumpNamedCounts(str.newline());
  2398. tm.reset(NAMEDCOUNTPERIOD*1000);
  2399. }
  2400. #endif
  2401. if (traceMode&PerfMonUDP)
  2402. {
  2403. snmpStats.reportSnmpInfo();
  2404. udpStats.reportUdpInfo(0);
  2405. }
  2406. if(traceMode&&str.length()) {
  2407. LOG(MCdebugInfo, unknownJob, "SYS: %s", str.str());
  2408. #ifndef _WIN32
  2409. if (traceMode&PerfMonExtended) {
  2410. if (extstats.getLine(str.clear()))
  2411. LOG(MCdebugInfo, unknownJob, "%s", str.str());
  2412. {
  2413. CriticalBlock block(sect);
  2414. extstats.printKLog(hook);
  2415. }
  2416. }
  2417. #endif
  2418. }
  2419. }
  2420. return 0;
  2421. }
  2422. void stop()
  2423. {
  2424. term = true;
  2425. sem.signal();
  2426. join();
  2427. }
  2428. unsigned queryLatestCPU() const
  2429. {
  2430. return latestCPU;
  2431. }
  2432. void setHook(IPerfMonHook *_hook)
  2433. {
  2434. CriticalBlock block(sect);
  2435. hook.set(_hook);
  2436. }
  2437. } *MemoryUsageReporter=NULL;
  2438. #ifdef _WIN32
  2439. static inline unsigned scaleFileTimeToMilli(unsigned __int64 nano100)
  2440. {
  2441. return (unsigned)(nano100 / 10000);
  2442. }
  2443. void getProcessTime(UserSystemTime_t & result)
  2444. {
  2445. LARGE_INTEGER startTime, exitTime, kernelTime, userTime;
  2446. if (GetProcessTimes(GetCurrentProcess(), (FILETIME *)&startTime, (FILETIME *)&exitTime, (FILETIME *)&kernelTime, (FILETIME *)&userTime))
  2447. {
  2448. result.user = scaleFileTimeToMilli(userTime.QuadPart);
  2449. result.system = scaleFileTimeToMilli(kernelTime.QuadPart);
  2450. }
  2451. }
  2452. #else
  2453. void getProcessTime(UserSystemTime_t & result)
  2454. {
  2455. UserStatusInfo info(GetCurrentProcessId());
  2456. if (info.update())
  2457. result = info.time;
  2458. }
  2459. #endif
  2460. void getSystemTraceInfo(StringBuffer &str, PerfMonMode mode)
  2461. {
  2462. if (!MemoryUsageReporter)
  2463. MemoryUsageReporter = new CMemoryUsageReporter(1000, mode, 0, false);
  2464. MemoryUsageReporter->getSystemTraceInfo(str, mode);
  2465. }
  2466. void startPerformanceMonitor(unsigned interval, PerfMonMode traceMode, IPerfMonHook * hook)
  2467. {
  2468. stopPerformanceMonitor();
  2469. if (!MemoryUsageReporter) {
  2470. MemoryUsageReporter = new CMemoryUsageReporter(interval, traceMode, hook, (traceMode&PerfMonExtended)!=0);
  2471. MemoryUsageReporter->start();
  2472. }
  2473. }
  2474. void stopPerformanceMonitor()
  2475. {
  2476. if (MemoryUsageReporter) {
  2477. MemoryUsageReporter->stop();
  2478. delete MemoryUsageReporter;
  2479. MemoryUsageReporter = NULL;
  2480. }
  2481. }
  2482. void setPerformanceMonitorHook(IPerfMonHook *hook)
  2483. {
  2484. if (MemoryUsageReporter)
  2485. MemoryUsageReporter->setHook(hook);
  2486. }
  2487. void setPerformanceMonitorPrimaryFileSystem(char const * fs)
  2488. {
  2489. if(MemoryUsageReporter)
  2490. MemoryUsageReporter->setPrimaryFileSystem(fs);
  2491. }
  2492. void setPerformanceMonitorSecondaryFileSystem(char const * fs)
  2493. {
  2494. if(MemoryUsageReporter)
  2495. MemoryUsageReporter->setSecondaryFileSystem(fs);
  2496. }
  2497. unsigned getLatestCPUUsage()
  2498. {
  2499. if (MemoryUsageReporter)
  2500. return MemoryUsageReporter->queryLatestCPU();
  2501. else
  2502. return 0;
  2503. }
  2504. void getHardwareInfo(HardwareInfo &hdwInfo, const char *primDiskPath, const char *secDiskPath)
  2505. {
  2506. memset(&hdwInfo, 0, sizeof(HardwareInfo));
  2507. getCpuInfo(hdwInfo.numCPUs, hdwInfo.CPUSpeed);
  2508. #ifdef _WIN32
  2509. MEMORYSTATUS memstatus;
  2510. GlobalMemoryStatus(&memstatus);
  2511. hdwInfo.totalMemory = memstatus.dwTotalPhys / (1024*1024); // in MB
  2512. ULARGE_INTEGER diskAvailStruct;
  2513. ULARGE_INTEGER diskTotalStruct;
  2514. if (primDiskPath)
  2515. {
  2516. diskTotalStruct.QuadPart = 0;
  2517. GetDiskFreeSpaceEx(primDiskPath, &diskAvailStruct, &diskTotalStruct, 0);
  2518. hdwInfo.primDiskSize = (unsigned)(diskTotalStruct.QuadPart / (1024*1024*1024)); // in GB
  2519. hdwInfo.primFreeSize = (unsigned)(diskAvailStruct.QuadPart / (1024*1024*1024)); // in GB
  2520. }
  2521. if (secDiskPath)
  2522. {
  2523. diskTotalStruct.QuadPart = 0;
  2524. GetDiskFreeSpaceEx(secDiskPath, &diskAvailStruct, &diskTotalStruct, 0);
  2525. hdwInfo.secDiskSize = (unsigned)(diskTotalStruct.QuadPart / (1024*1024*1024)); // in GB
  2526. hdwInfo.secFreeSize = (unsigned)(diskAvailStruct.QuadPart / (1024*1024*1024)); // in GB
  2527. }
  2528. // MORE: Find win32 call for NIC speed
  2529. #else // linux
  2530. unsigned memUsed, memActive, memSwap, memSwapUsed;
  2531. getMemUsage(memUsed, memActive, hdwInfo.totalMemory, memSwap, memSwapUsed);
  2532. hdwInfo.totalMemory /= 1024; // in MB
  2533. unsigned __int64 diskSize;
  2534. unsigned __int64 diskUsed;
  2535. if (primDiskPath)
  2536. {
  2537. getDiskUsage(primDiskPath, diskSize, diskUsed);
  2538. hdwInfo.primDiskSize = diskSize / (1024*1024*1024); // in GB
  2539. hdwInfo.primFreeSize = (diskSize - diskUsed) / (1024*1024*1024); // in GB
  2540. }
  2541. if (secDiskPath)
  2542. {
  2543. getDiskUsage(secDiskPath, diskSize, diskUsed);
  2544. hdwInfo.secDiskSize = diskSize / (1024*1024*1024); // in GB
  2545. hdwInfo.secFreeSize = (diskSize - diskUsed) / (1024*1024*1024); // in GB
  2546. }
  2547. // MORE: Find linux call for NIC speed -- mii-tool does not seem to work on our roxie clusters?
  2548. #endif
  2549. }
  2550. //===========================================================================
  2551. enum SegTypes {
  2552. segtype_free, //
  2553. segtype_heap, // rw-p named [heap]
  2554. segtype_data, // rw-p unnamed
  2555. segtype_guard, // ---p unnamed/named
  2556. segtype_stack, // rwxp
  2557. segtype_qlibcode, // r-xp named */lib200
  2558. segtype_qlibdata, // rw-p named */lib200
  2559. segtype_libcode, // r-xp named *
  2560. segtype_libdata, // rw-p named *
  2561. segtype_pstack, // rwxp named [stack]
  2562. segtype_const, // r--p
  2563. segtype_null // must be last
  2564. };
  2565. struct SegTypeRec
  2566. {
  2567. offset_t total;
  2568. unsigned n;
  2569. offset_t largest;
  2570. };
  2571. const char *PROCMAPHEADER =
  2572. "FREE,NFREE,MAXFREE,HEAP,STACK,NSTACKS,DATA,NDATA,MAXDATA,LIBDATA,QUERYDATA,MAXQUERYDATA,LIBCODE,QUERYCODE,MAXQLIBCODE";
  2573. class CProcReader
  2574. {
  2575. // Cant use JFile for /proc filesystem as seek doesn't work
  2576. public:
  2577. char ln [512];
  2578. FILE *file;
  2579. const char *buf;
  2580. size32_t bufsize;
  2581. CProcReader(const char *filename,const void *_buf,size32_t _buflen)
  2582. {
  2583. buf = (const char *)_buf;
  2584. bufsize = buf?_buflen:0;
  2585. file = buf?NULL:fopen(filename,"r");
  2586. }
  2587. ~CProcReader()
  2588. {
  2589. if (file)
  2590. fclose(file);
  2591. }
  2592. bool nextln()
  2593. {
  2594. if (buf) {
  2595. if (bufsize&&*buf) {
  2596. unsigned i = 0;
  2597. while (bufsize&&(i<sizeof(ln)-1)&&*buf&&(*buf!=10)&&(*buf!=13)) {
  2598. ln[i++] = *(buf++);
  2599. bufsize--;
  2600. }
  2601. ln[i] = 0;
  2602. while (bufsize&&*buf&&((*buf==10)||(*buf==13))) {
  2603. buf++;
  2604. bufsize--;
  2605. }
  2606. return true;
  2607. }
  2608. }
  2609. else if (file&&fgets (ln, sizeof(ln), file)) {
  2610. unsigned i = strlen(ln);
  2611. while (i&&((ln[i-1]==10)||(ln[i-1]==13)))
  2612. i--;
  2613. ln[i] = 0;
  2614. return true;
  2615. }
  2616. if (file) {
  2617. fclose(file);
  2618. file = NULL;
  2619. }
  2620. return false;
  2621. }
  2622. void dump(bool useprintf)
  2623. {
  2624. while (nextln()) {
  2625. if (useprintf)
  2626. printf("%s\n",ln);
  2627. else
  2628. PROGLOG("%s",ln);
  2629. }
  2630. }
  2631. };
  2632. void printProcMap(const char *fn, bool printbody, bool printsummary, StringBuffer *lnout, MemoryBuffer *mb, bool useprintf)
  2633. {
  2634. CProcReader reader(fn,mb?mb->toByteArray():NULL,mb?mb->length():0);
  2635. unsigned i;
  2636. SegTypeRec recs[segtype_null];
  2637. memset(&recs,0,sizeof(recs));
  2638. offset_t last=0;
  2639. if (printbody) {
  2640. if (useprintf)
  2641. printf("START,END,SIZE,OFFSET,PERMS,PATH\n");
  2642. else
  2643. PROGLOG("START,END,SIZE,OFFSET,PERMS,PATH");
  2644. }
  2645. while (reader.nextln()) {
  2646. const char *ln = reader.ln;
  2647. unsigned n=0;
  2648. if (*ln) {
  2649. offset_t start = readHexNum(ln);
  2650. if (last&&(last!=start)) {
  2651. recs[segtype_free].n++;
  2652. offset_t ssz = start-last;
  2653. recs[segtype_free].total += ssz;
  2654. if (ssz>recs[segtype_free].largest)
  2655. recs[segtype_free].largest = ssz;
  2656. }
  2657. if (*ln=='-') {
  2658. ln++;
  2659. offset_t end = readHexNum(ln);
  2660. char perms[5];
  2661. skipSp(ln);
  2662. for (i=0;i<4;)
  2663. if (*ln)
  2664. perms[i++] = *(ln++);
  2665. perms[i] = 0;
  2666. skipSp(ln);
  2667. offset_t offset = readHexNum(ln);
  2668. skipSp(ln);
  2669. char dev[6];
  2670. for (i=0;i<5;)
  2671. if (*ln)
  2672. dev[i++] = *(ln++);
  2673. dev[i] = 0;
  2674. skipSp(ln);
  2675. unsigned inode __attribute__((unused)) = (unsigned) readDecNum(ln);
  2676. skipSp(ln);
  2677. const char *path = ln;
  2678. if (printbody) {
  2679. if (useprintf)
  2680. printf("%08" I64F "x,%08" I64F "x,%" I64F "d,%08" I64F "x,%s,%s,%s\n",start,end,(offset_t)(end-start),offset,perms,dev,path);
  2681. else
  2682. PROGLOG("%08" I64F "x,%08" I64F "x,%" I64F "d,%08" I64F "x,%s,%s,%s",start,end,(offset_t)(end-start),offset,perms,dev,path);
  2683. }
  2684. SegTypes t = segtype_data;
  2685. if (strcmp(perms,"---p")==0)
  2686. t = segtype_guard;
  2687. else if (strcmp(perms,"rwxp")==0) {
  2688. if (memicmp(ln,"[stack]",7)==0)
  2689. t = segtype_pstack;
  2690. else
  2691. t = segtype_stack;
  2692. }
  2693. else if (strcmp(perms,"rw-p")==0) {
  2694. if (memicmp(ln,"[heap]",6)==0)
  2695. t = segtype_heap;
  2696. else if (strstr(ln,"/libW200"))
  2697. t = segtype_qlibdata;
  2698. else if (*ln)
  2699. t = segtype_libdata;
  2700. else
  2701. t = segtype_data;
  2702. }
  2703. else if (strcmp(perms,"r-xp")==0) {
  2704. if (strstr(ln,"/libW200"))
  2705. t = segtype_qlibcode;
  2706. else if (*ln)
  2707. t = segtype_libcode;
  2708. }
  2709. else if (strcmp(perms,"r--p")==0)
  2710. t = segtype_const;
  2711. else {
  2712. ERRLOG("%s - unknown perms",perms);
  2713. continue;
  2714. }
  2715. recs[t].n++;
  2716. offset_t ssz = end-start;
  2717. recs[t].total += ssz;
  2718. if (ssz>recs[t].largest)
  2719. recs[t].largest = ssz;
  2720. n++;
  2721. last = end;
  2722. #ifndef __64BIT__
  2723. if ((end<0xffffffff)&&(end>=0xc0000000)) // rest is OS (32-bit only)
  2724. break;
  2725. #endif
  2726. }
  2727. }
  2728. }
  2729. if (printsummary||lnout) {
  2730. StringBuffer tln;
  2731. if (lnout==NULL)
  2732. lnout = &tln;
  2733. lnout->appendf("%" I64F "u," // total
  2734. "%u," // n
  2735. "%" I64F "u," // largest
  2736. "%" I64F "u," // total
  2737. "%" I64F "u," // total
  2738. "%u," // n
  2739. "%" I64F "u," // total
  2740. "%u," // n
  2741. "%" I64F "u," // largest
  2742. "%" I64F "u," // total
  2743. "%" I64F "u," // total
  2744. "%" I64F "u," // largest
  2745. "%" I64F "u," // total
  2746. "%" I64F "u," // total
  2747. "%" I64F "u" // largest
  2748. ,
  2749. recs[segtype_free].total,
  2750. recs[segtype_free].n,
  2751. recs[segtype_free].largest,
  2752. recs[segtype_heap].total,
  2753. recs[segtype_stack].total,
  2754. recs[segtype_stack].n,
  2755. recs[segtype_data].total,
  2756. recs[segtype_data].n,
  2757. recs[segtype_data].largest,
  2758. recs[segtype_libdata].total,
  2759. recs[segtype_qlibdata].total,
  2760. recs[segtype_qlibdata].largest,
  2761. recs[segtype_libcode].total,
  2762. recs[segtype_qlibcode].total,
  2763. recs[segtype_qlibcode].largest
  2764. );
  2765. if (printsummary) {
  2766. if (useprintf)
  2767. printf("%s\n%s\n",PROCMAPHEADER,tln.str());
  2768. else {
  2769. PROGLOG("%s",PROCMAPHEADER);
  2770. PROGLOG("%s",tln.str());
  2771. }
  2772. }
  2773. }
  2774. }
  2775. #ifdef _WIN32
  2776. // stubs
  2777. void PrintMemoryReport(bool full)
  2778. {
  2779. StringBuffer s;
  2780. getSystemTraceInfo(s,PerfMonProcMem);
  2781. PROGLOG("%s",s.str());
  2782. }
  2783. #else
  2784. void PrintMemoryReport(bool full)
  2785. {
  2786. // may be very close to oom so protect against re-entry
  2787. static int recurse=0;
  2788. if (recurse++==0) {
  2789. try {
  2790. printProcMap("/proc/self/maps",full,true,NULL,NULL,false);
  2791. }
  2792. catch (IException *e) {
  2793. e->Release();
  2794. }
  2795. catch (...) {
  2796. }
  2797. try {
  2798. PROGLOG("/proc/meminfo:");
  2799. CProcReader reader("/proc/meminfo",NULL,0);
  2800. reader.dump(false);
  2801. }
  2802. catch (IException *e) {
  2803. e->Release();
  2804. }
  2805. catch (...) {
  2806. }
  2807. try {
  2808. PROGLOG("/proc/self/status:");
  2809. CProcReader reader("/proc/self/status",NULL,0);
  2810. reader.dump(false);
  2811. }
  2812. catch (IException *e) {
  2813. e->Release();
  2814. }
  2815. catch (...) {
  2816. }
  2817. try {
  2818. StringBuffer s;
  2819. getSystemTraceInfo(s,PerfMonProcMem);
  2820. PROGLOG("%s",s.str());
  2821. PROGLOG("===============================================================");
  2822. }
  2823. catch (IException *e) {
  2824. e->Release();
  2825. }
  2826. catch (...) {
  2827. }
  2828. }
  2829. recurse--;
  2830. }
  2831. #endif
  2832. bool areTransparentHugePagesEnabled()
  2833. {
  2834. #ifdef __linux__
  2835. StringBuffer contents;
  2836. try
  2837. {
  2838. contents.loadFile("/sys/kernel/mm/transparent_hugepage/enabled");
  2839. return !strstr(contents.str(), "[never]");
  2840. }
  2841. catch (IException * e)
  2842. {
  2843. e->Release();
  2844. }
  2845. #endif
  2846. return false;
  2847. }
  2848. memsize_t getHugePageSize()
  2849. {
  2850. #ifdef __linux__
  2851. StringBuffer contents;
  2852. try
  2853. {
  2854. //Search for an entry Hugepagesize: xxxx kB
  2855. const char * const tag = "Hugepagesize:";
  2856. contents.loadFile("/proc/meminfo");
  2857. const char * hugepage = strstr(contents.str(), tag);
  2858. if (hugepage)
  2859. {
  2860. const char * next = hugepage + strlen(tag);
  2861. char * end;
  2862. memsize_t size = strtoul(next, &end, 10);
  2863. if (strncmp(end, " kB", 3) == 0)
  2864. return size * 0x400;
  2865. }
  2866. }
  2867. catch (IException * e)
  2868. {
  2869. e->Release();
  2870. }
  2871. #endif
  2872. return 0x200000; // Default for an x86 system
  2873. }
  2874. //===========================================================================
  2875. #ifdef LEAK_CHECK
  2876. #ifdef _WIN32
  2877. LeakChecker::LeakChecker(const char * _title) : title(_title)
  2878. {
  2879. _CrtMemCheckpoint(&oldMemState);
  2880. }
  2881. LeakChecker::~LeakChecker()
  2882. {
  2883. _CrtMemState newMemState, diffMemState;
  2884. _CrtMemCheckpoint(&newMemState);
  2885. if(_CrtMemDifference(&diffMemState, &oldMemState, &newMemState))
  2886. {
  2887. _RPT1(_CRT_WARN, "----- Memory leaks in '%s' -----\n", title);
  2888. _CrtMemDumpStatistics(&diffMemState);
  2889. _CrtMemDumpAllObjectsSince(&oldMemState);
  2890. _RPT0(_CRT_WARN, "----- End of leaks -----\n");
  2891. }
  2892. }
  2893. static char _logFile[255]; // used to hold last file name of log file for memory leak logging
  2894. static FILE *_logHandle = NULL;
  2895. _CRT_REPORT_HOOK oldReport;
  2896. static int MemoryLeakReportHook(int nRptType,char *szMsg,int *retVal)
  2897. {
  2898. if (szMsg && *szMsg)
  2899. {
  2900. if (_logHandle)
  2901. fprintf(_logHandle, szMsg);
  2902. if (*_logFile)
  2903. {
  2904. #if 1
  2905. // this works better in VS 2008 libraries (which fault in fopen)
  2906. int handle = _open(_logFile, O_RDWR | O_CREAT, _S_IREAD | _S_IWRITE);
  2907. _lseek(handle,0,SEEK_END);
  2908. _write(handle,szMsg,strlen(szMsg));
  2909. _close(handle);
  2910. #else
  2911. FILE *handle = fopen(_logFile, "a");
  2912. fprintf(handle, szMsg);
  2913. fclose(handle);
  2914. #endif
  2915. }
  2916. }
  2917. if (oldReport)
  2918. return oldReport(nRptType,szMsg,retVal);
  2919. else
  2920. return false;
  2921. }
  2922. MODULE_INIT(INIT_PRIORITY_JDEBUG1)
  2923. {
  2924. oldReport = _CrtSetReportHook(MemoryLeakReportHook);
  2925. return 1;
  2926. }
  2927. void logLeaks (const char *logFile)
  2928. {
  2929. if (logFile)
  2930. strncpy(_logFile, logFile, sizeof(_logFile));
  2931. else
  2932. _logFile[0] = 0;
  2933. }
  2934. void logLeaks (FILE *logHandle)
  2935. {
  2936. _logHandle = logHandle;
  2937. }
  2938. #else
  2939. #endif
  2940. #endif
  2941. #if !defined(USING_MPATROL) && defined(WIN32) && defined(_DEBUG)
  2942. void jlib_decl enableMemLeakChecking(bool enable)
  2943. {
  2944. int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
  2945. if (enable)
  2946. tmpFlag |= _CRTDBG_LEAK_CHECK_DF;
  2947. else
  2948. tmpFlag &= ~_CRTDBG_LEAK_CHECK_DF;
  2949. _CrtSetDbgFlag( tmpFlag );
  2950. }
  2951. #endif
  2952. #if defined(_WIN32) && defined(_DEBUG)
  2953. //#include <dbgint.h>
  2954. const unsigned maxUnique = 10000;
  2955. typedef struct _CrtMemBlockHeader
  2956. {
  2957. // Pointer to the block allocated just before this one:
  2958. struct _CrtMemBlockHeader *pBlockHeaderNext;
  2959. // Pointer to the block allocated just after this one:
  2960. struct _CrtMemBlockHeader *pBlockHeaderPrev;
  2961. char *szFileName; // File name
  2962. int nLine; // Line number
  2963. size_t nDataSize; // Size of user block
  2964. int nBlockUse; // Type of block
  2965. long lRequest; // Allocation number
  2966. } _CrtMemBlockHeader;
  2967. int compareFile(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2968. {
  2969. int compare;
  2970. if (left->szFileName && right->szFileName)
  2971. compare = strcmp(left->szFileName, right->szFileName);
  2972. else if (left->szFileName)
  2973. compare = -1;
  2974. else if (right->szFileName)
  2975. compare = +1;
  2976. else
  2977. compare = 0;
  2978. return compare;
  2979. }
  2980. int compareLocation(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2981. {
  2982. int compare = compareFile(left, right);
  2983. if (compare != 0)
  2984. return compare;
  2985. return left->nLine - right->nLine;
  2986. }
  2987. int compareBlocks(_CrtMemBlockHeader * left, _CrtMemBlockHeader * right)
  2988. {
  2989. int compare = compareLocation(left, right);
  2990. if (compare != 0)
  2991. return compare;
  2992. return (int)(right->nDataSize - left->nDataSize);
  2993. }
  2994. void addLocation(unsigned & numUnique, _CrtMemBlockHeader * * locations, unsigned * counts, _CrtMemBlockHeader * search)
  2995. {
  2996. int left = 0;
  2997. int right = numUnique;
  2998. while (left < right)
  2999. {
  3000. int mid = (left + right) >> 1;
  3001. int cmp = compareBlocks(search, locations[mid]);
  3002. if (cmp < 0)
  3003. right = mid;
  3004. else if (cmp > 0)
  3005. left = mid+1;
  3006. else
  3007. {
  3008. //Save the lowest allocation number (so quicker to set a subsequent breakpoint)
  3009. if (search->lRequest < locations[mid]->lRequest)
  3010. locations[mid] = search;
  3011. counts[mid]++;
  3012. return;
  3013. }
  3014. }
  3015. if (numUnique != maxUnique)
  3016. {
  3017. assertex(left == right);
  3018. memmove(locations + left+1, locations + left, (numUnique-left)*sizeof(*locations));
  3019. memmove(counts + left+1, counts + left, (numUnique-left)*sizeof(*counts));
  3020. locations[left] = search;
  3021. counts[left] = 1;
  3022. numUnique++;
  3023. }
  3024. else
  3025. counts[maxUnique]++;
  3026. }
  3027. unsigned dumpMemory(unsigned lenTarget, char * target, unsigned lenSrc, const void * ptr)
  3028. {
  3029. if (lenSrc > lenTarget)
  3030. lenSrc = lenTarget;
  3031. const char * src = (const char *)ptr;
  3032. for (unsigned i=0; i < lenSrc; i++)
  3033. {
  3034. byte next = src[i];
  3035. target[i] = (next >= 0x20 && next <= 0x7e) ? next : '.';
  3036. }
  3037. return lenSrc;
  3038. }
  3039. void printAllocationSummary()
  3040. {
  3041. _CrtMemState state;
  3042. _CrtMemCheckpoint(&state);
  3043. unsigned numUnique = 0;
  3044. _CrtMemBlockHeader * locations[maxUnique+1];
  3045. unsigned counts[maxUnique+1];
  3046. _clear(counts);
  3047. unsigned __int64 totalFree = 0;
  3048. unsigned __int64 totalAllocated = 0;
  3049. //Walk the heap, keeping a tally of (filename, line, size)->count
  3050. _CrtMemBlockHeader * cur;
  3051. for (cur = state.pBlockHeader; cur; cur=cur->pBlockHeaderNext)
  3052. {
  3053. switch (cur->nBlockUse)
  3054. {
  3055. case _NORMAL_BLOCK:
  3056. {
  3057. addLocation(numUnique, locations, counts, cur);
  3058. totalAllocated += cur->nDataSize;
  3059. break;
  3060. }
  3061. case _FREE_BLOCK:
  3062. totalFree += cur->nDataSize;
  3063. break;
  3064. }
  3065. }
  3066. PROGLOG("%d Unique allocations by <filename>(line)@size", numUnique);
  3067. for (unsigned i2 = 0; i2 < numUnique; i2++)
  3068. {
  3069. _CrtMemBlockHeader * display = locations[i2];
  3070. //char tempBuffer[16];
  3071. //unsigned len = dumpMemory(sizeof(tempBuffer), tempBuffer, display->nDataSize,
  3072. PROGLOG("%s(%d) %d:%d {%ld} = %d", display->szFileName ? display->szFileName : "<unknown>", display->nLine, display->nDataSize, counts[i2], display->lRequest, display->nDataSize * counts[i2]);
  3073. }
  3074. PROGLOG("Ungrouped: %d Total %" I64F "d", counts[maxUnique], totalAllocated);
  3075. PROGLOG("Summary by location");
  3076. for (unsigned iSummary2 = 0; iSummary2 < numUnique; )
  3077. {
  3078. _CrtMemBlockHeader * display = locations[iSummary2];
  3079. unsigned count = counts[iSummary2];
  3080. unsigned __int64 size = count * display->nDataSize;
  3081. for (iSummary2++; iSummary2 < numUnique; iSummary2++)
  3082. {
  3083. _CrtMemBlockHeader * next = locations[iSummary2];
  3084. if (compareLocation(display, next) != 0)
  3085. break;
  3086. count += counts[iSummary2];
  3087. size += (counts[iSummary2] * next->nDataSize);
  3088. }
  3089. PROGLOG("%s(%d) %d = %d", display->szFileName ? display->szFileName : "<unknown>", display->nLine, count, size);
  3090. }
  3091. PROGLOG("Summary by source");
  3092. for (unsigned iSummary2 = 0; iSummary2 < numUnique; )
  3093. {
  3094. _CrtMemBlockHeader * display = locations[iSummary2];
  3095. unsigned count = counts[iSummary2];
  3096. unsigned __int64 size = count * display->nDataSize;
  3097. for (iSummary2++; iSummary2 < numUnique; iSummary2++)
  3098. {
  3099. _CrtMemBlockHeader * next = locations[iSummary2];
  3100. if (compareFile(display, next) != 0)
  3101. break;
  3102. count += counts[iSummary2];
  3103. size += (counts[iSummary2] * next->nDataSize);
  3104. }
  3105. PROGLOG("%s %d = %d", display->szFileName ? display->szFileName : "<unknown>", count, size);
  3106. }
  3107. }
  3108. #else
  3109. void printAllocationSummary()
  3110. {
  3111. }
  3112. #endif
  3113. #ifdef _USE_MALLOC_HOOK
  3114. // Note memory hooks should not be enabled for release (as not re-entrant in linux)
  3115. static CriticalSection hookSect;
  3116. #ifdef __linux__
  3117. static void *(*old_malloc_hook)(size_t, const void *);
  3118. static void (*old_free_hook)(void *, const void *);
  3119. static void *(*old_realloc_hook)(void *, size_t, const void *);
  3120. static void * jlib_malloc_hook (size_t size, const void *caller) ;
  3121. static void jlib_free_hook (void *ptr, const void *caller);
  3122. static void *jlib_realloc_hook (void *ptr, size_t size, const void *caller);
  3123. static int jlib_hooknest = 0; // this *shouldn't* really be needed
  3124. inline void restore_malloc_hooks()
  3125. {
  3126. if (--jlib_hooknest==0) {
  3127. __malloc_hook = old_malloc_hook;
  3128. __realloc_hook = old_realloc_hook;
  3129. __free_hook = old_free_hook;
  3130. }
  3131. }
  3132. inline void set_malloc_hooks()
  3133. {
  3134. assertex(jlib_hooknest==0);
  3135. old_malloc_hook = __malloc_hook;
  3136. old_free_hook = __free_hook;
  3137. old_realloc_hook = __realloc_hook;
  3138. __malloc_hook = jlib_malloc_hook;
  3139. __free_hook = jlib_free_hook;
  3140. __realloc_hook = jlib_realloc_hook;
  3141. jlib_hooknest = 1;
  3142. }
  3143. inline void reset_malloc_hooks()
  3144. {
  3145. if (jlib_hooknest++==0) {
  3146. __malloc_hook = jlib_malloc_hook;
  3147. __free_hook = jlib_free_hook;
  3148. __realloc_hook = jlib_realloc_hook;
  3149. }
  3150. }
  3151. inline void incCount(unsigned sz,bool inc)
  3152. {
  3153. int i=0;
  3154. size32_t s=sz;
  3155. while (s) {
  3156. s /= 2;
  3157. i++;
  3158. }
  3159. if (inc)
  3160. memArea[i] += sz;
  3161. else
  3162. memArea[i] -= sz;
  3163. }
  3164. void * jlib_malloc_hook (size_t size, const void *caller)
  3165. {
  3166. CriticalBlock block(hookSect);
  3167. void *res;
  3168. restore_malloc_hooks();
  3169. res = malloc (size);
  3170. if (res) {
  3171. size = malloc_usable_size(res);
  3172. totalMem+=size;
  3173. if (totalMem>hwmTotalMem) {
  3174. if (hwmTotalMem/(100*0x100000)!=totalMem/(100*0x100000)) {
  3175. PrintStackReport();
  3176. PROGLOG("TOTALMEM(%" I64F "d): malloc %u",totalMem,(unsigned)size);
  3177. }
  3178. hwmTotalMem = totalMem;
  3179. }
  3180. }
  3181. else
  3182. size = 0;
  3183. incCount(size,true);
  3184. if (size>REPORT_LARGER_BLOCK_THAN) {
  3185. PrintStackReport();
  3186. PROGLOG("LARGEALLOC(%u): %p",(unsigned)size,res);
  3187. }
  3188. reset_malloc_hooks();
  3189. return res;
  3190. }
  3191. void jlib_free_hook (void *ptr, const void *caller)
  3192. {
  3193. if (!ptr)
  3194. return;
  3195. CriticalBlock block(hookSect);
  3196. restore_malloc_hooks();
  3197. size32_t sz = malloc_usable_size(ptr);
  3198. free (ptr);
  3199. totalMem -= sz;
  3200. incCount(sz,false);
  3201. if (sz>REPORT_LARGER_BLOCK_THAN) {
  3202. PROGLOG("LARGEFREE(%u): %p",(unsigned)sz,ptr);
  3203. }
  3204. reset_malloc_hooks();
  3205. }
  3206. void *jlib_realloc_hook (void *ptr, size_t size, const void *caller)
  3207. {
  3208. CriticalBlock block(hookSect);
  3209. restore_malloc_hooks();
  3210. size32_t oldsz = ptr?malloc_usable_size(ptr):0;
  3211. void *res = realloc (ptr,size);
  3212. if (res) {
  3213. size = malloc_usable_size(res);
  3214. totalMem += size;
  3215. }
  3216. else
  3217. size = 0;
  3218. totalMem -= oldsz;
  3219. if (totalMem>hwmTotalMem) {
  3220. if (hwmTotalMem/(100*0x100000)!=totalMem/(100*0x100000)) {
  3221. PrintStackReport();
  3222. PROGLOG("TOTALMEM(%" I64F "d): realloc %u %u",totalMem,(unsigned)oldsz,(unsigned)size);
  3223. }
  3224. hwmTotalMem = totalMem;
  3225. }
  3226. incCount(size,true);
  3227. incCount(oldsz,false);
  3228. if ((size>REPORT_LARGER_BLOCK_THAN)||(oldsz>REPORT_LARGER_BLOCK_THAN)) {
  3229. if (size>oldsz) {
  3230. PrintStackReport();
  3231. PROGLOG("LARGEREALLOC_UP(%u,%u): %p %p",(unsigned)oldsz,(unsigned)size,ptr,res);
  3232. }
  3233. else {
  3234. PROGLOG("LARGEREALLOC_DN(%u,%u): %p %p",(unsigned)oldsz,(unsigned)size,ptr,res);
  3235. }
  3236. }
  3237. reset_malloc_hooks();
  3238. return res;
  3239. }
  3240. void jlib_decl jlib_init_hook()
  3241. {
  3242. set_malloc_hooks();
  3243. }
  3244. __int64 jlib_decl setAllocHook(bool on,bool clear)
  3245. {
  3246. CriticalBlock block(hookSect);
  3247. __int64 ret = totalMem;
  3248. if (clear) {
  3249. totalMem = 0;
  3250. hwmTotalMem = 0;
  3251. }
  3252. if (on) {
  3253. if (jlib_hooknest==0)
  3254. set_malloc_hooks();
  3255. }
  3256. else {
  3257. while (jlib_hooknest) {
  3258. restore_malloc_hooks();
  3259. //printf("Total = %d bytes\n",totalMem);
  3260. }
  3261. }
  3262. return ret;
  3263. }
  3264. unsigned jlib_decl setAllocHook(bool on)
  3265. {
  3266. // bwd compatible - should use above version in preference
  3267. CriticalBlock block(hookSect);
  3268. if (on) {
  3269. if (jlib_hooknest==0) {
  3270. set_malloc_hooks();
  3271. totalMem = 0;
  3272. hwmTotalMem = 0;
  3273. }
  3274. }
  3275. else {
  3276. while (jlib_hooknest) {
  3277. restore_malloc_hooks();
  3278. //printf("Total = %d bytes\n",totalMem);
  3279. }
  3280. }
  3281. return (unsigned)totalMem;
  3282. }
  3283. #else // windows
  3284. static _CRT_ALLOC_HOOK oldHook = NULL;
  3285. static int allocHook( int allocType, void *userData, size_t size, int nBlockUse,
  3286. long requestNumber, const unsigned char *filename, int lineNumber)
  3287. {
  3288. CriticalBlock block(hookSect);
  3289. if ( nBlockUse == _CRT_BLOCK ) // Ignore internal C runtime library allocations
  3290. return TRUE;
  3291. static bool recurse = false;
  3292. if (recurse)
  3293. return TRUE;
  3294. recurse = true;
  3295. char *operation[] = { "", "allocating", "re-allocating", "freeing" };
  3296. char *blockType[] = { "Free", "Normal", "CRT", "Ignore", "Client" };
  3297. switch (allocType) {
  3298. case _HOOK_REALLOC:
  3299. if (userData==NULL)
  3300. printf("no data on realloc\n");
  3301. else
  3302. totalMem-=_msize(userData);
  3303. // fall through
  3304. case _HOOK_ALLOC:
  3305. totalMem+=size;
  3306. break;
  3307. case _HOOK_FREE:
  3308. if (userData)
  3309. totalMem-=_msize(userData);
  3310. break;
  3311. }
  3312. // printf( "Memory operation in %s, line %d: %s a %d-byte '%s' block (#%ld)\n",
  3313. // filename, lineNumber, operation[allocType], size,
  3314. // blockType[nBlockUse], requestNumber );
  3315. recurse = false;
  3316. return TRUE; // Allow the memory operation to proceed
  3317. }
  3318. unsigned jlib_decl setAllocHook(bool on)
  3319. {
  3320. CriticalBlock block(hookSect);
  3321. if (on) {
  3322. if (oldHook==NULL) {
  3323. oldHook = _CrtSetAllocHook( allocHook );
  3324. totalMem = 0;
  3325. }
  3326. }
  3327. else {
  3328. if (oldHook!=NULL)
  3329. _CrtSetAllocHook( oldHook );
  3330. oldHook = NULL;
  3331. //printf("Total = %d bytes\n",totalMem);
  3332. }
  3333. return (unsigned)totalMem; // return unsigned for bwd compat
  3334. }
  3335. #endif
  3336. __int64 getTotalMem()
  3337. {
  3338. return totalMem;
  3339. }
  3340. #else // release
  3341. unsigned jlib_decl setAllocHook(bool on __attribute__((unused)))
  3342. {
  3343. return 0;
  3344. }
  3345. __int64 jlib_decl setAllocHook(bool on __attribute__((unused)), bool clear __attribute__((unused)))
  3346. {
  3347. return 0;
  3348. }
  3349. __int64 jlib_decl getTotalMem()
  3350. {
  3351. return 0;
  3352. }
  3353. void jlib_decl jlib_init_hook()
  3354. {
  3355. }
  3356. #endif
  3357. class UserMetricMsgHandler : public CInterface, implements ILogMsgHandler, implements IUserMetric
  3358. {
  3359. mutable unsigned __int64 counter;
  3360. StringAttr metricName;
  3361. StringAttr regex;
  3362. Owned<ILogMsgFilter> regexFilter;
  3363. public:
  3364. virtual void Link(void) const { CInterface::Link(); }
  3365. virtual bool Release(void) const
  3366. {
  3367. if (CInterface::Release())
  3368. return true;
  3369. if (!IsShared())
  3370. {
  3371. queryLogMsgManager()->removeMonitor(const_cast<UserMetricMsgHandler *>(this)); // removeMonitor should take a const param really
  3372. }
  3373. return false;
  3374. }
  3375. UserMetricMsgHandler(const char *_name, const char *_regex) : metricName(_name), regex(_regex)
  3376. {
  3377. counter = 0;
  3378. regexFilter.setown(getRegexLogMsgFilter(regex, true));
  3379. queryLogMsgManager()->addMonitor(this, regexFilter);
  3380. }
  3381. // interface ILogMsgHandler
  3382. virtual void handleMessage(const LogMsg & msg __attribute__((unused))) const { counter++; }
  3383. virtual bool needsPrep() const { return false; }
  3384. virtual void prep() {}
  3385. virtual unsigned queryMessageFields() const { return MSGFIELD_detail; }
  3386. virtual void setMessageFields(unsigned _fields __attribute__((unused)) = MSGFIELD_all) {}
  3387. virtual void addToPTree(IPropertyTree * parent __attribute__((unused))) const {}
  3388. virtual int flush() { return 0; }
  3389. virtual char const *disable() { return 0; }
  3390. virtual void enable() {}
  3391. virtual bool getLogName(StringBuffer &name __attribute__((unused))) const { return false; }
  3392. // interface IUserMetric
  3393. virtual unsigned __int64 queryCount() const { return counter; }
  3394. virtual const char *queryName() const { return metricName; }
  3395. virtual const char *queryMatchString() const { return regex; }
  3396. virtual void inc() { counter++; }
  3397. virtual void reset() { counter = 0; }
  3398. };
  3399. jlib_decl IUserMetric *createUserMetric(const char *name, const char *matchString)
  3400. {
  3401. return new UserMetricMsgHandler(name, matchString);
  3402. }