jdebug.cpp 94 KB

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