jdebug.cpp 95 KB

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