jdebug.cpp 108 KB

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