jdebug.cpp 95 KB

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