jdebug.cpp 95 KB

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