SystemInformation.cxx 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480
  1. /*============================================================================
  2. KWSys - Kitware System Library
  3. Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
  4. Distributed under the OSI-approved BSD License (the "License");
  5. see accompanying file Copyright.txt for details.
  6. This software is distributed WITHOUT ANY WARRANTY; without even the
  7. implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  8. See the License for more information.
  9. ============================================================================*/
  10. #if defined(_WIN32)
  11. # define NOMINMAX // use our min,max
  12. # if !defined(_WIN32_WINNT) && !(defined(_MSC_VER) && _MSC_VER < 1300)
  13. # define _WIN32_WINNT 0x0501
  14. # endif
  15. # include <winsock.h> // WSADATA, include before sys/types.h
  16. #endif
  17. #if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
  18. # define _GNU_SOURCE
  19. #endif
  20. // TODO:
  21. // We need an alternative implementation for many functions in this file
  22. // when USE_ASM_INSTRUCTIONS gets defined as 0.
  23. //
  24. // Consider using these on Win32/Win64 for some of them:
  25. //
  26. // IsProcessorFeaturePresent
  27. // http://msdn.microsoft.com/en-us/library/ms724482(VS.85).aspx
  28. //
  29. // GetProcessMemoryInfo
  30. // http://msdn.microsoft.com/en-us/library/ms683219(VS.85).aspx
  31. #include "kwsysPrivate.h"
  32. #include KWSYS_HEADER(SystemInformation.hxx)
  33. #include KWSYS_HEADER(Process.h)
  34. // Work-around CMake dependency scanning limitation. This must
  35. // duplicate the above list of headers.
  36. #if 0
  37. # include "SystemInformation.hxx.in"
  38. # include "Process.h.in"
  39. #endif
  40. #include <iostream>
  41. #include <sstream>
  42. #include <fstream>
  43. #include <string>
  44. #include <vector>
  45. #if defined(_WIN32)
  46. # include <windows.h>
  47. # if defined(_MSC_VER) && _MSC_VER >= 1800
  48. # define KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  49. # endif
  50. # include <errno.h>
  51. # if defined(KWSYS_SYS_HAS_PSAPI)
  52. # include <psapi.h>
  53. # endif
  54. # if !defined(siginfo_t)
  55. typedef int siginfo_t;
  56. # endif
  57. #else
  58. # include <sys/types.h>
  59. # include <sys/time.h>
  60. # include <sys/utsname.h> // int uname(struct utsname *buf);
  61. # include <sys/resource.h> // getrlimit
  62. # include <unistd.h>
  63. # include <signal.h>
  64. # include <fcntl.h>
  65. # include <errno.h> // extern int errno;
  66. #endif
  67. #if defined (__CYGWIN__) && !defined(_WIN32)
  68. # include <windows.h>
  69. # undef _WIN32
  70. #endif
  71. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  72. # include <sys/param.h>
  73. # include <sys/sysctl.h>
  74. # include <sys/socket.h>
  75. # include <netdb.h>
  76. # include <netinet/in.h>
  77. # if defined(KWSYS_SYS_HAS_IFADDRS_H)
  78. # include <ifaddrs.h>
  79. # define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
  80. # endif
  81. #endif
  82. #if defined(KWSYS_SYS_HAS_MACHINE_CPU_H)
  83. # include <machine/cpu.h>
  84. #endif
  85. #ifdef __APPLE__
  86. # include <sys/sysctl.h>
  87. # include <mach/vm_statistics.h>
  88. # include <mach/host_info.h>
  89. # include <mach/mach.h>
  90. # include <mach/mach_types.h>
  91. # include <fenv.h>
  92. # include <sys/socket.h>
  93. # include <netdb.h>
  94. # include <netinet/in.h>
  95. # if defined(KWSYS_SYS_HAS_IFADDRS_H)
  96. # include <ifaddrs.h>
  97. # define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
  98. # endif
  99. # if !(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0 >= 1050)
  100. # undef KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE
  101. # endif
  102. #endif
  103. #if defined(__linux) || defined (__sun) || defined(_SCO_DS)
  104. # include <fenv.h>
  105. # include <sys/socket.h>
  106. # include <netdb.h>
  107. # include <netinet/in.h>
  108. # if defined(KWSYS_SYS_HAS_IFADDRS_H)
  109. # include <ifaddrs.h>
  110. # if !defined(__LSB_VERSION__) /* LSB has no getifaddrs */
  111. # define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
  112. # endif
  113. # endif
  114. # if defined(KWSYS_CXX_HAS_RLIMIT64)
  115. typedef struct rlimit64 ResourceLimitType;
  116. # define GetResourceLimit getrlimit64
  117. # else
  118. typedef struct rlimit ResourceLimitType;
  119. # define GetResourceLimit getrlimit
  120. # endif
  121. #elif defined( __hpux )
  122. # include <sys/param.h>
  123. # include <sys/pstat.h>
  124. # if defined(KWSYS_SYS_HAS_MPCTL_H)
  125. # include <sys/mpctl.h>
  126. # endif
  127. #endif
  128. #ifdef __HAIKU__
  129. # include <OS.h>
  130. #endif
  131. #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  132. # include <execinfo.h>
  133. # if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
  134. # include <cxxabi.h>
  135. # endif
  136. # if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
  137. # include <dlfcn.h>
  138. # endif
  139. #else
  140. # undef KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE
  141. # undef KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP
  142. #endif
  143. #include <memory.h>
  144. #include <stdlib.h>
  145. #include <stdio.h>
  146. #include <string.h>
  147. #include <ctype.h> // int isdigit(int c);
  148. #if defined(KWSYS_USE_LONG_LONG)
  149. # if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
  150. # define iostreamLongLong(x) (x)
  151. # else
  152. # define iostreamLongLong(x) ((long)(x))
  153. # endif
  154. #elif defined(KWSYS_USE___INT64)
  155. # if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
  156. # define iostreamLongLong(x) (x)
  157. # else
  158. # define iostreamLongLong(x) ((long)(x))
  159. # endif
  160. #else
  161. # error "No Long Long"
  162. #endif
  163. #if defined(KWSYS_CXX_HAS_ATOLL)
  164. # define atoLongLong atoll
  165. #else
  166. # if defined(KWSYS_CXX_HAS__ATOI64)
  167. # define atoLongLong _atoi64
  168. # elif defined(KWSYS_CXX_HAS_ATOL)
  169. # define atoLongLong atol
  170. # else
  171. # define atoLongLong atoi
  172. # endif
  173. #endif
  174. #if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(_WIN64) && !defined(__clang__)
  175. #define USE_ASM_INSTRUCTIONS 1
  176. #else
  177. #define USE_ASM_INSTRUCTIONS 0
  178. #endif
  179. #if defined(_MSC_VER) && (_MSC_VER >= 1400) && !defined(__clang__)
  180. #include <intrin.h>
  181. #define USE_CPUID_INTRINSICS 1
  182. #else
  183. #define USE_CPUID_INTRINSICS 0
  184. #endif
  185. #if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS || defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
  186. # define USE_CPUID 1
  187. #else
  188. # define USE_CPUID 0
  189. #endif
  190. #if USE_CPUID
  191. #define CPUID_AWARE_COMPILER
  192. /**
  193. * call CPUID instruction
  194. *
  195. * Will return false if the instruction failed.
  196. */
  197. static bool call_cpuid(int select, int result[4])
  198. {
  199. #if USE_CPUID_INTRINSICS
  200. __cpuid(result, select);
  201. return true;
  202. #else
  203. int tmp[4];
  204. #if defined(_MSC_VER)
  205. // Use SEH to determine CPUID presence
  206. __try {
  207. _asm {
  208. #ifdef CPUID_AWARE_COMPILER
  209. ; we must push/pop the registers <<CPUID>> writes to, as the
  210. ; optimiser does not know about <<CPUID>>, and so does not expect
  211. ; these registers to change.
  212. push eax
  213. push ebx
  214. push ecx
  215. push edx
  216. #endif
  217. ; <<CPUID>>
  218. mov eax, select
  219. #ifdef CPUID_AWARE_COMPILER
  220. cpuid
  221. #else
  222. _asm _emit 0x0f
  223. _asm _emit 0xa2
  224. #endif
  225. mov tmp[0 * TYPE int], eax
  226. mov tmp[1 * TYPE int], ebx
  227. mov tmp[2 * TYPE int], ecx
  228. mov tmp[3 * TYPE int], edx
  229. #ifdef CPUID_AWARE_COMPILER
  230. pop edx
  231. pop ecx
  232. pop ebx
  233. pop eax
  234. #endif
  235. }
  236. }
  237. __except(1)
  238. {
  239. return false;
  240. }
  241. memcpy(result, tmp, sizeof(tmp));
  242. #elif defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
  243. unsigned int a, b, c, d;
  244. __asm {
  245. mov EAX, select;
  246. cpuid
  247. mov a, EAX;
  248. mov b, EBX;
  249. mov c, ECX;
  250. mov d, EDX;
  251. }
  252. result[0] = a;
  253. result[1] = b;
  254. result[2] = c;
  255. result[3] = d;
  256. #endif
  257. // The cpuid instruction succeeded.
  258. return true;
  259. #endif
  260. }
  261. #endif
  262. namespace KWSYS_NAMESPACE
  263. {
  264. template<typename T>
  265. T min(T a, T b){ return a<b ? a : b; }
  266. extern "C" { typedef void (*SigAction)(int,siginfo_t*,void*); }
  267. // Define SystemInformationImplementation class
  268. typedef void (*DELAY_FUNC)(unsigned int uiMS);
  269. class SystemInformationImplementation
  270. {
  271. public:
  272. typedef SystemInformation::LongLong LongLong;
  273. SystemInformationImplementation ();
  274. ~SystemInformationImplementation ();
  275. const char * GetVendorString();
  276. const char * GetVendorID();
  277. std::string GetTypeID();
  278. std::string GetFamilyID();
  279. std::string GetModelID();
  280. std::string GetModelName();
  281. std::string GetSteppingCode();
  282. const char * GetExtendedProcessorName();
  283. const char * GetProcessorSerialNumber();
  284. int GetProcessorCacheSize();
  285. unsigned int GetLogicalProcessorsPerPhysical();
  286. float GetProcessorClockFrequency();
  287. int GetProcessorAPICID();
  288. int GetProcessorCacheXSize(long int);
  289. bool DoesCPUSupportFeature(long int);
  290. const char * GetOSName();
  291. const char * GetHostname();
  292. int GetFullyQualifiedDomainName(std::string &fqdn);
  293. const char * GetOSRelease();
  294. const char * GetOSVersion();
  295. const char * GetOSPlatform();
  296. bool Is64Bits();
  297. unsigned int GetNumberOfLogicalCPU(); // per physical cpu
  298. unsigned int GetNumberOfPhysicalCPU();
  299. bool DoesCPUSupportCPUID();
  300. // Retrieve memory information in megabyte.
  301. size_t GetTotalVirtualMemory();
  302. size_t GetAvailableVirtualMemory();
  303. size_t GetTotalPhysicalMemory();
  304. size_t GetAvailablePhysicalMemory();
  305. LongLong GetProcessId();
  306. // Retrieve memory information in kib
  307. LongLong GetHostMemoryTotal();
  308. LongLong GetHostMemoryAvailable(const char *envVarName);
  309. LongLong GetHostMemoryUsed();
  310. LongLong GetProcMemoryAvailable(
  311. const char *hostLimitEnvVarName,
  312. const char *procLimitEnvVarName);
  313. LongLong GetProcMemoryUsed();
  314. double GetLoadAverage();
  315. // enable/disable stack trace signal handler.
  316. static
  317. void SetStackTraceOnError(int enable);
  318. // get current stack
  319. static
  320. std::string GetProgramStack(int firstFrame, int wholePath);
  321. /** Run the different checks */
  322. void RunCPUCheck();
  323. void RunOSCheck();
  324. void RunMemoryCheck();
  325. public:
  326. typedef struct tagID
  327. {
  328. int Type;
  329. int Family;
  330. int Model;
  331. int Revision;
  332. int ExtendedFamily;
  333. int ExtendedModel;
  334. std::string ProcessorName;
  335. std::string Vendor;
  336. std::string SerialNumber;
  337. std::string ModelName;
  338. } ID;
  339. typedef struct tagCPUPowerManagement
  340. {
  341. bool HasVoltageID;
  342. bool HasFrequencyID;
  343. bool HasTempSenseDiode;
  344. } CPUPowerManagement;
  345. typedef struct tagCPUExtendedFeatures
  346. {
  347. bool Has3DNow;
  348. bool Has3DNowPlus;
  349. bool SupportsMP;
  350. bool HasMMXPlus;
  351. bool HasSSEMMX;
  352. bool SupportsHyperthreading;
  353. unsigned int LogicalProcessorsPerPhysical;
  354. int APIC_ID;
  355. CPUPowerManagement PowerManagement;
  356. } CPUExtendedFeatures;
  357. typedef struct CPUtagFeatures
  358. {
  359. bool HasFPU;
  360. bool HasTSC;
  361. bool HasMMX;
  362. bool HasSSE;
  363. bool HasSSEFP;
  364. bool HasSSE2;
  365. bool HasIA64;
  366. bool HasAPIC;
  367. bool HasCMOV;
  368. bool HasMTRR;
  369. bool HasACPI;
  370. bool HasSerial;
  371. bool HasThermal;
  372. int CPUSpeed;
  373. int L1CacheSize;
  374. int L2CacheSize;
  375. int L3CacheSize;
  376. CPUExtendedFeatures ExtendedFeatures;
  377. } CPUFeatures;
  378. enum Manufacturer
  379. {
  380. AMD, Intel, NSC, UMC, Cyrix, NexGen, IDT, Rise, Transmeta, Sun, IBM,
  381. Motorola, HP, UnknownManufacturer
  382. };
  383. protected:
  384. // For windows
  385. bool RetrieveCPUFeatures();
  386. bool RetrieveCPUIdentity();
  387. bool RetrieveCPUCacheDetails();
  388. bool RetrieveClassicalCPUCacheDetails();
  389. bool RetrieveCPUClockSpeed();
  390. bool RetrieveClassicalCPUClockSpeed();
  391. bool RetrieveCPUExtendedLevelSupport(int);
  392. bool RetrieveExtendedCPUFeatures();
  393. bool RetrieveProcessorSerialNumber();
  394. bool RetrieveCPUPowerManagement();
  395. bool RetrieveClassicalCPUIdentity();
  396. bool RetrieveExtendedCPUIdentity();
  397. // Processor information
  398. Manufacturer ChipManufacturer;
  399. CPUFeatures Features;
  400. ID ChipID;
  401. float CPUSpeedInMHz;
  402. unsigned int NumberOfLogicalCPU;
  403. unsigned int NumberOfPhysicalCPU;
  404. int CPUCount(); // For windows
  405. unsigned char LogicalCPUPerPhysicalCPU();
  406. unsigned char GetAPICId(); // For windows
  407. bool IsHyperThreadingSupported();
  408. static LongLong GetCyclesDifference(DELAY_FUNC, unsigned int); // For windows
  409. // For Linux and Cygwin, /proc/cpuinfo formats are slightly different
  410. bool RetreiveInformationFromCpuInfoFile();
  411. std::string ExtractValueFromCpuInfoFile(std::string buffer,
  412. const char* word, size_t init=0);
  413. bool QueryLinuxMemory();
  414. bool QueryCygwinMemory();
  415. static void Delay (unsigned int);
  416. static void DelayOverhead (unsigned int);
  417. void FindManufacturer(const std::string &family = "");
  418. // For Mac
  419. bool ParseSysCtl();
  420. int CallSwVers(const char *arg, std::string &ver);
  421. void TrimNewline(std::string&);
  422. std::string ExtractValueFromSysCtl(const char* word);
  423. std::string SysCtlBuffer;
  424. // For Solaris
  425. bool QuerySolarisMemory();
  426. bool QuerySolarisProcessor();
  427. std::string ParseValueFromKStat(const char* arguments);
  428. std::string RunProcess(std::vector<const char*> args);
  429. //For Haiku OS
  430. bool QueryHaikuInfo();
  431. //For QNX
  432. bool QueryQNXMemory();
  433. bool QueryQNXProcessor();
  434. //For OpenBSD, FreeBSD, NetBSD, DragonFly
  435. bool QueryBSDMemory();
  436. bool QueryBSDProcessor();
  437. //For HP-UX
  438. bool QueryHPUXMemory();
  439. bool QueryHPUXProcessor();
  440. //For Microsoft Windows
  441. bool QueryWindowsMemory();
  442. //For AIX
  443. bool QueryAIXMemory();
  444. bool QueryProcessorBySysconf();
  445. bool QueryProcessor();
  446. // Evaluate the memory information.
  447. bool QueryMemoryBySysconf();
  448. bool QueryMemory();
  449. size_t TotalVirtualMemory;
  450. size_t AvailableVirtualMemory;
  451. size_t TotalPhysicalMemory;
  452. size_t AvailablePhysicalMemory;
  453. size_t CurrentPositionInFile;
  454. // Operating System information
  455. bool QueryOSInformation();
  456. std::string OSName;
  457. std::string Hostname;
  458. std::string OSRelease;
  459. std::string OSVersion;
  460. std::string OSPlatform;
  461. };
  462. SystemInformation::SystemInformation()
  463. {
  464. this->Implementation = new SystemInformationImplementation;
  465. }
  466. SystemInformation::~SystemInformation()
  467. {
  468. delete this->Implementation;
  469. }
  470. const char * SystemInformation::GetVendorString()
  471. {
  472. return this->Implementation->GetVendorString();
  473. }
  474. const char * SystemInformation::GetVendorID()
  475. {
  476. return this->Implementation->GetVendorID();
  477. }
  478. std::string SystemInformation::GetTypeID()
  479. {
  480. return this->Implementation->GetTypeID();
  481. }
  482. std::string SystemInformation::GetFamilyID()
  483. {
  484. return this->Implementation->GetFamilyID();
  485. }
  486. std::string SystemInformation::GetModelID()
  487. {
  488. return this->Implementation->GetModelID();
  489. }
  490. std::string SystemInformation::GetModelName()
  491. {
  492. return this->Implementation->GetModelName();
  493. }
  494. std::string SystemInformation::GetSteppingCode()
  495. {
  496. return this->Implementation->GetSteppingCode();
  497. }
  498. const char * SystemInformation::GetExtendedProcessorName()
  499. {
  500. return this->Implementation->GetExtendedProcessorName();
  501. }
  502. const char * SystemInformation::GetProcessorSerialNumber()
  503. {
  504. return this->Implementation->GetProcessorSerialNumber();
  505. }
  506. int SystemInformation::GetProcessorCacheSize()
  507. {
  508. return this->Implementation->GetProcessorCacheSize();
  509. }
  510. unsigned int SystemInformation::GetLogicalProcessorsPerPhysical()
  511. {
  512. return this->Implementation->GetLogicalProcessorsPerPhysical();
  513. }
  514. float SystemInformation::GetProcessorClockFrequency()
  515. {
  516. return this->Implementation->GetProcessorClockFrequency();
  517. }
  518. int SystemInformation::GetProcessorAPICID()
  519. {
  520. return this->Implementation->GetProcessorAPICID();
  521. }
  522. int SystemInformation::GetProcessorCacheXSize(long int l)
  523. {
  524. return this->Implementation->GetProcessorCacheXSize(l);
  525. }
  526. bool SystemInformation::DoesCPUSupportFeature(long int i)
  527. {
  528. return this->Implementation->DoesCPUSupportFeature(i);
  529. }
  530. std::string SystemInformation::GetCPUDescription()
  531. {
  532. std::ostringstream oss;
  533. oss
  534. << this->GetNumberOfPhysicalCPU()
  535. << " core ";
  536. if (this->GetModelName().empty())
  537. {
  538. oss
  539. << this->GetProcessorClockFrequency()
  540. << " MHz "
  541. << this->GetVendorString()
  542. << " "
  543. << this->GetExtendedProcessorName();
  544. }
  545. else
  546. {
  547. oss << this->GetModelName();
  548. }
  549. // remove extra spaces
  550. std::string tmp=oss.str();
  551. size_t pos;
  552. while( (pos=tmp.find(" "))!=std::string::npos)
  553. {
  554. tmp.replace(pos,2," ");
  555. }
  556. return tmp;
  557. }
  558. const char * SystemInformation::GetOSName()
  559. {
  560. return this->Implementation->GetOSName();
  561. }
  562. const char * SystemInformation::GetHostname()
  563. {
  564. return this->Implementation->GetHostname();
  565. }
  566. std::string SystemInformation::GetFullyQualifiedDomainName()
  567. {
  568. std::string fqdn;
  569. this->Implementation->GetFullyQualifiedDomainName(fqdn);
  570. return fqdn;
  571. }
  572. const char * SystemInformation::GetOSRelease()
  573. {
  574. return this->Implementation->GetOSRelease();
  575. }
  576. const char * SystemInformation::GetOSVersion()
  577. {
  578. return this->Implementation->GetOSVersion();
  579. }
  580. const char * SystemInformation::GetOSPlatform()
  581. {
  582. return this->Implementation->GetOSPlatform();
  583. }
  584. int SystemInformation::GetOSIsWindows()
  585. {
  586. #if defined(_WIN32)
  587. return 1;
  588. #else
  589. return 0;
  590. #endif
  591. }
  592. int SystemInformation::GetOSIsLinux()
  593. {
  594. #if defined(__linux)
  595. return 1;
  596. #else
  597. return 0;
  598. #endif
  599. }
  600. int SystemInformation::GetOSIsApple()
  601. {
  602. #if defined(__APPLE__)
  603. return 1;
  604. #else
  605. return 0;
  606. #endif
  607. }
  608. std::string SystemInformation::GetOSDescription()
  609. {
  610. std::ostringstream oss;
  611. oss
  612. << this->GetOSName()
  613. << " "
  614. << this->GetOSRelease()
  615. << " "
  616. << this->GetOSVersion();
  617. return oss.str();
  618. }
  619. bool SystemInformation::Is64Bits()
  620. {
  621. return this->Implementation->Is64Bits();
  622. }
  623. unsigned int SystemInformation::GetNumberOfLogicalCPU() // per physical cpu
  624. {
  625. return this->Implementation->GetNumberOfLogicalCPU();
  626. }
  627. unsigned int SystemInformation::GetNumberOfPhysicalCPU()
  628. {
  629. return this->Implementation->GetNumberOfPhysicalCPU();
  630. }
  631. bool SystemInformation::DoesCPUSupportCPUID()
  632. {
  633. return this->Implementation->DoesCPUSupportCPUID();
  634. }
  635. // Retrieve memory information in megabyte.
  636. size_t SystemInformation::GetTotalVirtualMemory()
  637. {
  638. return this->Implementation->GetTotalVirtualMemory();
  639. }
  640. size_t SystemInformation::GetAvailableVirtualMemory()
  641. {
  642. return this->Implementation->GetAvailableVirtualMemory();
  643. }
  644. size_t SystemInformation::GetTotalPhysicalMemory()
  645. {
  646. return this->Implementation->GetTotalPhysicalMemory();
  647. }
  648. size_t SystemInformation::GetAvailablePhysicalMemory()
  649. {
  650. return this->Implementation->GetAvailablePhysicalMemory();
  651. }
  652. std::string SystemInformation::GetMemoryDescription(
  653. const char *hostLimitEnvVarName,
  654. const char *procLimitEnvVarName)
  655. {
  656. std::ostringstream oss;
  657. oss
  658. << "Host Total: "
  659. << iostreamLongLong(this->GetHostMemoryTotal())
  660. << " KiB, Host Available: "
  661. << iostreamLongLong(this->GetHostMemoryAvailable(hostLimitEnvVarName))
  662. << " KiB, Process Available: "
  663. << iostreamLongLong(
  664. this->GetProcMemoryAvailable(hostLimitEnvVarName,procLimitEnvVarName))
  665. << " KiB";
  666. return oss.str();
  667. }
  668. // host memory info in units of KiB.
  669. SystemInformation::LongLong SystemInformation::GetHostMemoryTotal()
  670. {
  671. return this->Implementation->GetHostMemoryTotal();
  672. }
  673. SystemInformation::LongLong
  674. SystemInformation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
  675. {
  676. return this->Implementation->GetHostMemoryAvailable(hostLimitEnvVarName);
  677. }
  678. SystemInformation::LongLong SystemInformation::GetHostMemoryUsed()
  679. {
  680. return this->Implementation->GetHostMemoryUsed();
  681. }
  682. // process memory info in units of KiB.
  683. SystemInformation::LongLong
  684. SystemInformation::GetProcMemoryAvailable(
  685. const char *hostLimitEnvVarName,
  686. const char *procLimitEnvVarName)
  687. {
  688. return this->Implementation->GetProcMemoryAvailable(
  689. hostLimitEnvVarName,
  690. procLimitEnvVarName);
  691. }
  692. SystemInformation::LongLong SystemInformation::GetProcMemoryUsed()
  693. {
  694. return this->Implementation->GetProcMemoryUsed();
  695. }
  696. double SystemInformation::GetLoadAverage()
  697. {
  698. return this->Implementation->GetLoadAverage();
  699. }
  700. SystemInformation::LongLong SystemInformation::GetProcessId()
  701. {
  702. return this->Implementation->GetProcessId();
  703. }
  704. void SystemInformation::SetStackTraceOnError(int enable)
  705. {
  706. SystemInformationImplementation::SetStackTraceOnError(enable);
  707. }
  708. std::string SystemInformation::GetProgramStack(int firstFrame, int wholePath)
  709. {
  710. return SystemInformationImplementation::GetProgramStack(firstFrame, wholePath);
  711. }
  712. /** Run the different checks */
  713. void SystemInformation::RunCPUCheck()
  714. {
  715. this->Implementation->RunCPUCheck();
  716. }
  717. void SystemInformation::RunOSCheck()
  718. {
  719. this->Implementation->RunOSCheck();
  720. }
  721. void SystemInformation::RunMemoryCheck()
  722. {
  723. this->Implementation->RunMemoryCheck();
  724. }
  725. // --------------------------------------------------------------
  726. // SystemInformationImplementation starts here
  727. #define STORE_TLBCACHE_INFO(x,y) x = (x < (y)) ? (y) : x
  728. #define TLBCACHE_INFO_UNITS (15)
  729. #define CLASSICAL_CPU_FREQ_LOOP 10000000
  730. #define RDTSC_INSTRUCTION _asm _emit 0x0f _asm _emit 0x31
  731. #define MMX_FEATURE 0x00000001
  732. #define MMX_PLUS_FEATURE 0x00000002
  733. #define SSE_FEATURE 0x00000004
  734. #define SSE2_FEATURE 0x00000008
  735. #define AMD_3DNOW_FEATURE 0x00000010
  736. #define AMD_3DNOW_PLUS_FEATURE 0x00000020
  737. #define IA64_FEATURE 0x00000040
  738. #define MP_CAPABLE 0x00000080
  739. #define HYPERTHREAD_FEATURE 0x00000100
  740. #define SERIALNUMBER_FEATURE 0x00000200
  741. #define APIC_FEATURE 0x00000400
  742. #define SSE_FP_FEATURE 0x00000800
  743. #define SSE_MMX_FEATURE 0x00001000
  744. #define CMOV_FEATURE 0x00002000
  745. #define MTRR_FEATURE 0x00004000
  746. #define L1CACHE_FEATURE 0x00008000
  747. #define L2CACHE_FEATURE 0x00010000
  748. #define L3CACHE_FEATURE 0x00020000
  749. #define ACPI_FEATURE 0x00040000
  750. #define THERMALMONITOR_FEATURE 0x00080000
  751. #define TEMPSENSEDIODE_FEATURE 0x00100000
  752. #define FREQUENCYID_FEATURE 0x00200000
  753. #define VOLTAGEID_FREQUENCY 0x00400000
  754. // Status Flag
  755. #define HT_NOT_CAPABLE 0
  756. #define HT_ENABLED 1
  757. #define HT_DISABLED 2
  758. #define HT_SUPPORTED_NOT_ENABLED 3
  759. #define HT_CANNOT_DETECT 4
  760. // EDX[28] Bit 28 is set if HT is supported
  761. #define HT_BIT 0x10000000
  762. // EAX[11:8] Bit 8-11 contains family processor ID.
  763. #define FAMILY_ID 0x0F00
  764. #define PENTIUM4_ID 0x0F00
  765. // EAX[23:20] Bit 20-23 contains extended family processor ID
  766. #define EXT_FAMILY_ID 0x0F00000
  767. // EBX[23:16] Bit 16-23 in ebx contains the number of logical
  768. #define NUM_LOGICAL_BITS 0x00FF0000
  769. // processors per physical processor when execute cpuid with
  770. // eax set to 1
  771. // EBX[31:24] Bits 24-31 (8 bits) return the 8-bit unique
  772. #define INITIAL_APIC_ID_BITS 0xFF000000
  773. // initial APIC ID for the processor this code is running on.
  774. // Default value = 0xff if HT is not supported
  775. // Hide implementation details in an anonymous namespace.
  776. namespace {
  777. // *****************************************************************************
  778. #if defined(__linux) || defined(__APPLE__)
  779. int LoadLines(
  780. FILE *file,
  781. std::vector<std::string> &lines)
  782. {
  783. // Load each line in the given file into a the vector.
  784. int nRead=0;
  785. const int bufSize=1024;
  786. char buf[bufSize]={'\0'};
  787. while (!feof(file) && !ferror(file))
  788. {
  789. errno=0;
  790. if (fgets(buf,bufSize,file) == 0)
  791. {
  792. if (ferror(file) && (errno==EINTR))
  793. {
  794. clearerr(file);
  795. }
  796. continue;
  797. }
  798. char *pBuf=buf;
  799. while(*pBuf)
  800. {
  801. if (*pBuf=='\n') *pBuf='\0';
  802. pBuf+=1;
  803. }
  804. lines.push_back(buf);
  805. ++nRead;
  806. }
  807. if (ferror(file))
  808. {
  809. return 0;
  810. }
  811. return nRead;
  812. }
  813. # if defined(__linux)
  814. // *****************************************************************************
  815. int LoadLines(
  816. const char *fileName,
  817. std::vector<std::string> &lines)
  818. {
  819. FILE *file=fopen(fileName,"r");
  820. if (file==0)
  821. {
  822. return 0;
  823. }
  824. int nRead=LoadLines(file,lines);
  825. fclose(file);
  826. return nRead;
  827. }
  828. # endif
  829. // ****************************************************************************
  830. template<typename T>
  831. int NameValue(
  832. std::vector<std::string> &lines,
  833. std::string name, T &value)
  834. {
  835. size_t nLines=lines.size();
  836. for (size_t i=0; i<nLines; ++i)
  837. {
  838. size_t at=lines[i].find(name);
  839. if (at==std::string::npos)
  840. {
  841. continue;
  842. }
  843. std::istringstream is(lines[i].substr(at+name.size()));
  844. is >> value;
  845. return 0;
  846. }
  847. return -1;
  848. }
  849. #endif
  850. #if defined(__linux)
  851. // ****************************************************************************
  852. template<typename T>
  853. int GetFieldsFromFile(
  854. const char *fileName,
  855. const char **fieldNames,
  856. T *values)
  857. {
  858. std::vector<std::string> fields;
  859. if (!LoadLines(fileName,fields))
  860. {
  861. return -1;
  862. }
  863. int i=0;
  864. while (fieldNames[i]!=NULL)
  865. {
  866. int ierr=NameValue(fields,fieldNames[i],values[i]);
  867. if (ierr)
  868. {
  869. return -(i+2);
  870. }
  871. i+=1;
  872. }
  873. return 0;
  874. }
  875. // ****************************************************************************
  876. template<typename T>
  877. int GetFieldFromFile(
  878. const char *fileName,
  879. const char *fieldName,
  880. T &value)
  881. {
  882. const char *fieldNames[2]={fieldName,NULL};
  883. T values[1]={T(0)};
  884. int ierr=GetFieldsFromFile(fileName,fieldNames,values);
  885. if (ierr)
  886. {
  887. return ierr;
  888. }
  889. value=values[0];
  890. return 0;
  891. }
  892. #endif
  893. // ****************************************************************************
  894. #if defined(__APPLE__)
  895. template<typename T>
  896. int GetFieldsFromCommand(
  897. const char *command,
  898. const char **fieldNames,
  899. T *values)
  900. {
  901. FILE *file=popen(command,"r");
  902. if (file==0)
  903. {
  904. return -1;
  905. }
  906. std::vector<std::string> fields;
  907. int nl=LoadLines(file,fields);
  908. pclose(file);
  909. if (nl==0)
  910. {
  911. return -1;
  912. }
  913. int i=0;
  914. while (fieldNames[i]!=NULL)
  915. {
  916. int ierr=NameValue(fields,fieldNames[i],values[i]);
  917. if (ierr)
  918. {
  919. return -(i+2);
  920. }
  921. i+=1;
  922. }
  923. return 0;
  924. }
  925. #endif
  926. // ****************************************************************************
  927. #if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
  928. void StacktraceSignalHandler(
  929. int sigNo,
  930. siginfo_t *sigInfo,
  931. void * /*sigContext*/)
  932. {
  933. #if defined(__linux) || defined(__APPLE__)
  934. std::ostringstream oss;
  935. oss
  936. << std::endl
  937. << "=========================================================" << std::endl
  938. << "Process id " << getpid() << " ";
  939. switch (sigNo)
  940. {
  941. case SIGINT:
  942. oss << "Caught SIGINT";
  943. break;
  944. case SIGTERM:
  945. oss << "Caught SIGTERM";
  946. break;
  947. case SIGABRT:
  948. oss << "Caught SIGABRT";
  949. break;
  950. case SIGFPE:
  951. oss
  952. << "Caught SIGFPE at "
  953. << (sigInfo->si_addr==0?"0x":"")
  954. << sigInfo->si_addr
  955. << " ";
  956. switch (sigInfo->si_code)
  957. {
  958. # if defined(FPE_INTDIV)
  959. case FPE_INTDIV:
  960. oss << "integer division by zero";
  961. break;
  962. # endif
  963. # if defined(FPE_INTOVF)
  964. case FPE_INTOVF:
  965. oss << "integer overflow";
  966. break;
  967. # endif
  968. case FPE_FLTDIV:
  969. oss << "floating point divide by zero";
  970. break;
  971. case FPE_FLTOVF:
  972. oss << "floating point overflow";
  973. break;
  974. case FPE_FLTUND:
  975. oss << "floating point underflow";
  976. break;
  977. case FPE_FLTRES:
  978. oss << "floating point inexact result";
  979. break;
  980. case FPE_FLTINV:
  981. oss << "floating point invalid operation";
  982. break;
  983. #if defined(FPE_FLTSUB)
  984. case FPE_FLTSUB:
  985. oss << "floating point subscript out of range";
  986. break;
  987. #endif
  988. default:
  989. oss << "code " << sigInfo->si_code;
  990. break;
  991. }
  992. break;
  993. case SIGSEGV:
  994. oss
  995. << "Caught SIGSEGV at "
  996. << (sigInfo->si_addr==0?"0x":"")
  997. << sigInfo->si_addr
  998. << " ";
  999. switch (sigInfo->si_code)
  1000. {
  1001. case SEGV_MAPERR:
  1002. oss << "address not mapped to object";
  1003. break;
  1004. case SEGV_ACCERR:
  1005. oss << "invalid permission for mapped object";
  1006. break;
  1007. default:
  1008. oss << "code " << sigInfo->si_code;
  1009. break;
  1010. }
  1011. break;
  1012. case SIGBUS:
  1013. oss
  1014. << "Caught SIGBUS at "
  1015. << (sigInfo->si_addr==0?"0x":"")
  1016. << sigInfo->si_addr
  1017. << " ";
  1018. switch (sigInfo->si_code)
  1019. {
  1020. case BUS_ADRALN:
  1021. oss << "invalid address alignment";
  1022. break;
  1023. # if defined(BUS_ADRERR)
  1024. case BUS_ADRERR:
  1025. oss << "nonexistent physical address";
  1026. break;
  1027. # endif
  1028. # if defined(BUS_OBJERR)
  1029. case BUS_OBJERR:
  1030. oss << "object-specific hardware error";
  1031. break;
  1032. # endif
  1033. # if defined(BUS_MCEERR_AR)
  1034. case BUS_MCEERR_AR:
  1035. oss << "Hardware memory error consumed on a machine check; action required.";
  1036. break;
  1037. # endif
  1038. # if defined(BUS_MCEERR_AO)
  1039. case BUS_MCEERR_AO:
  1040. oss << "Hardware memory error detected in process but not consumed; action optional.";
  1041. break;
  1042. # endif
  1043. default:
  1044. oss << "code " << sigInfo->si_code;
  1045. break;
  1046. }
  1047. break;
  1048. case SIGILL:
  1049. oss
  1050. << "Caught SIGILL at "
  1051. << (sigInfo->si_addr==0?"0x":"")
  1052. << sigInfo->si_addr
  1053. << " ";
  1054. switch (sigInfo->si_code)
  1055. {
  1056. case ILL_ILLOPC:
  1057. oss << "illegal opcode";
  1058. break;
  1059. # if defined(ILL_ILLOPN)
  1060. case ILL_ILLOPN:
  1061. oss << "illegal operand";
  1062. break;
  1063. # endif
  1064. # if defined(ILL_ILLADR)
  1065. case ILL_ILLADR:
  1066. oss << "illegal addressing mode.";
  1067. break;
  1068. # endif
  1069. case ILL_ILLTRP:
  1070. oss << "illegal trap";
  1071. break;
  1072. case ILL_PRVOPC:
  1073. oss << "privileged opcode";
  1074. break;
  1075. # if defined(ILL_PRVREG)
  1076. case ILL_PRVREG:
  1077. oss << "privileged register";
  1078. break;
  1079. # endif
  1080. # if defined(ILL_COPROC)
  1081. case ILL_COPROC:
  1082. oss << "co-processor error";
  1083. break;
  1084. # endif
  1085. # if defined(ILL_BADSTK)
  1086. case ILL_BADSTK:
  1087. oss << "internal stack error";
  1088. break;
  1089. # endif
  1090. default:
  1091. oss << "code " << sigInfo->si_code;
  1092. break;
  1093. }
  1094. break;
  1095. default:
  1096. oss << "Caught " << sigNo << " code " << sigInfo->si_code;
  1097. break;
  1098. }
  1099. oss
  1100. << std::endl
  1101. << "Program Stack:" << std::endl
  1102. << SystemInformationImplementation::GetProgramStack(2,0)
  1103. << "=========================================================" << std::endl;
  1104. std::cerr << oss.str() << std::endl;
  1105. // restore the previously registered handlers
  1106. // and abort
  1107. SystemInformationImplementation::SetStackTraceOnError(0);
  1108. abort();
  1109. #else
  1110. // avoid warning C4100
  1111. (void)sigNo;
  1112. (void)sigInfo;
  1113. #endif
  1114. }
  1115. #endif
  1116. #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  1117. #define safes(_arg)((_arg)?(_arg):"???")
  1118. // Description:
  1119. // A container for symbol properties. Each instance
  1120. // must be Initialized.
  1121. class SymbolProperties
  1122. {
  1123. public:
  1124. SymbolProperties();
  1125. // Description:
  1126. // The SymbolProperties instance must be initialized by
  1127. // passing a stack address.
  1128. void Initialize(void *address);
  1129. // Description:
  1130. // Get the symbol's stack address.
  1131. void *GetAddress() const { return this->Address; }
  1132. // Description:
  1133. // If not set paths will be removed. eg, from a binary
  1134. // or source file.
  1135. void SetReportPath(int rp){ this->ReportPath=rp; }
  1136. // Description:
  1137. // Set/Get the name of the binary file that the symbol
  1138. // is found in.
  1139. void SetBinary(const char *binary)
  1140. { this->Binary=safes(binary); }
  1141. std::string GetBinary() const;
  1142. // Description:
  1143. // Set the name of the function that the symbol is found in.
  1144. // If c++ demangling is supported it will be demangled.
  1145. void SetFunction(const char *function)
  1146. { this->Function=this->Demangle(function); }
  1147. std::string GetFunction() const
  1148. { return this->Function; }
  1149. // Description:
  1150. // Set/Get the name of the source file where the symbol
  1151. // is defined.
  1152. void SetSourceFile(const char *sourcefile)
  1153. { this->SourceFile=safes(sourcefile); }
  1154. std::string GetSourceFile() const
  1155. { return this->GetFileName(this->SourceFile); }
  1156. // Description:
  1157. // Set/Get the line number where the symbol is defined
  1158. void SetLineNumber(long linenumber){ this->LineNumber=linenumber; }
  1159. long GetLineNumber() const { return this->LineNumber; }
  1160. // Description:
  1161. // Set the address where the biinary image is mapped
  1162. // into memory.
  1163. void SetBinaryBaseAddress(void *address)
  1164. { this->BinaryBaseAddress=address; }
  1165. private:
  1166. void *GetRealAddress() const
  1167. { return (void*)((char*)this->Address-(char*)this->BinaryBaseAddress); }
  1168. std::string GetFileName(const std::string &path) const;
  1169. std::string Demangle(const char *symbol) const;
  1170. private:
  1171. std::string Binary;
  1172. void *BinaryBaseAddress;
  1173. void *Address;
  1174. std::string SourceFile;
  1175. std::string Function;
  1176. long LineNumber;
  1177. int ReportPath;
  1178. };
  1179. // --------------------------------------------------------------------------
  1180. std::ostream &operator<<(
  1181. std::ostream &os,
  1182. const SymbolProperties &sp)
  1183. {
  1184. #if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
  1185. os
  1186. << std::hex << sp.GetAddress() << " : "
  1187. << sp.GetFunction()
  1188. << " [(" << sp.GetBinary() << ") "
  1189. << sp.GetSourceFile() << ":"
  1190. << std::dec << sp.GetLineNumber() << "]";
  1191. #elif defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  1192. void *addr = sp.GetAddress();
  1193. char **syminfo = backtrace_symbols(&addr,1);
  1194. os << safes(syminfo[0]);
  1195. free(syminfo);
  1196. #else
  1197. (void)os;
  1198. (void)sp;
  1199. #endif
  1200. return os;
  1201. }
  1202. // --------------------------------------------------------------------------
  1203. SymbolProperties::SymbolProperties()
  1204. {
  1205. // not using an initializer list
  1206. // to avoid some PGI compiler warnings
  1207. this->SetBinary("???");
  1208. this->SetBinaryBaseAddress(NULL);
  1209. this->Address = NULL;
  1210. this->SetSourceFile("???");
  1211. this->SetFunction("???");
  1212. this->SetLineNumber(-1);
  1213. this->SetReportPath(0);
  1214. // avoid PGI compiler warnings
  1215. this->GetRealAddress();
  1216. this->GetFunction();
  1217. this->GetSourceFile();
  1218. this->GetLineNumber();
  1219. }
  1220. // --------------------------------------------------------------------------
  1221. std::string SymbolProperties::GetFileName(const std::string &path) const
  1222. {
  1223. std::string file(path);
  1224. if (!this->ReportPath)
  1225. {
  1226. size_t at = file.rfind("/");
  1227. if (at!=std::string::npos)
  1228. {
  1229. file = file.substr(at+1,std::string::npos);
  1230. }
  1231. }
  1232. return file;
  1233. }
  1234. // --------------------------------------------------------------------------
  1235. std::string SymbolProperties::GetBinary() const
  1236. {
  1237. // only linux has proc fs
  1238. #if defined(__linux__)
  1239. if (this->Binary=="/proc/self/exe")
  1240. {
  1241. std::string binary;
  1242. char buf[1024]={'\0'};
  1243. ssize_t ll=0;
  1244. if ((ll=readlink("/proc/self/exe",buf,1024))>0)
  1245. {
  1246. buf[ll]='\0';
  1247. binary=buf;
  1248. }
  1249. else
  1250. {
  1251. binary="/proc/self/exe";
  1252. }
  1253. return this->GetFileName(binary);
  1254. }
  1255. #endif
  1256. return this->GetFileName(this->Binary);
  1257. }
  1258. // --------------------------------------------------------------------------
  1259. std::string SymbolProperties::Demangle(const char *symbol) const
  1260. {
  1261. std::string result = safes(symbol);
  1262. #if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
  1263. int status = 0;
  1264. size_t bufferLen = 1024;
  1265. char *buffer = (char*)malloc(1024);
  1266. char *demangledSymbol =
  1267. abi::__cxa_demangle(symbol, buffer, &bufferLen, &status);
  1268. if (!status)
  1269. {
  1270. result = demangledSymbol;
  1271. }
  1272. free(buffer);
  1273. #else
  1274. (void)symbol;
  1275. #endif
  1276. return result;
  1277. }
  1278. // --------------------------------------------------------------------------
  1279. void SymbolProperties::Initialize(void *address)
  1280. {
  1281. this->Address = address;
  1282. #if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
  1283. // first fallback option can demangle c++ functions
  1284. Dl_info info;
  1285. int ierr=dladdr(this->Address,&info);
  1286. if (ierr && info.dli_sname && info.dli_saddr)
  1287. {
  1288. this->SetBinary(info.dli_fname);
  1289. this->SetFunction(info.dli_sname);
  1290. }
  1291. #else
  1292. // second fallback use builtin backtrace_symbols
  1293. // to decode the bactrace.
  1294. #endif
  1295. }
  1296. #endif // don't define this class if we're not using it
  1297. // --------------------------------------------------------------------------
  1298. #if defined(_WIN32) || defined(__CYGWIN__)
  1299. # define KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
  1300. #endif
  1301. #if defined(_MSC_VER) && _MSC_VER < 1310
  1302. # undef KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes
  1303. #endif
  1304. #if defined(KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes)
  1305. double calculateCPULoad(unsigned __int64 idleTicks,
  1306. unsigned __int64 totalTicks)
  1307. {
  1308. static double previousLoad = -0.0;
  1309. static unsigned __int64 previousIdleTicks = 0;
  1310. static unsigned __int64 previousTotalTicks = 0;
  1311. unsigned __int64 const idleTicksSinceLastTime =
  1312. idleTicks - previousIdleTicks;
  1313. unsigned __int64 const totalTicksSinceLastTime =
  1314. totalTicks - previousTotalTicks;
  1315. double load;
  1316. if (previousTotalTicks == 0 || totalTicksSinceLastTime == 0)
  1317. {
  1318. // No new information. Use previous result.
  1319. load = previousLoad;
  1320. }
  1321. else
  1322. {
  1323. // Calculate load since last time.
  1324. load = 1.0 - double(idleTicksSinceLastTime) / totalTicksSinceLastTime;
  1325. // Smooth if possible.
  1326. if (previousLoad > 0)
  1327. {
  1328. load = 0.25 * load + 0.75 * previousLoad;
  1329. }
  1330. }
  1331. previousLoad = load;
  1332. previousIdleTicks = idleTicks;
  1333. previousTotalTicks = totalTicks;
  1334. return load;
  1335. }
  1336. unsigned __int64 fileTimeToUInt64(FILETIME const& ft)
  1337. {
  1338. LARGE_INTEGER out;
  1339. out.HighPart = ft.dwHighDateTime;
  1340. out.LowPart = ft.dwLowDateTime;
  1341. return out.QuadPart;
  1342. }
  1343. #endif
  1344. } // anonymous namespace
  1345. SystemInformationImplementation::SystemInformationImplementation()
  1346. {
  1347. this->TotalVirtualMemory = 0;
  1348. this->AvailableVirtualMemory = 0;
  1349. this->TotalPhysicalMemory = 0;
  1350. this->AvailablePhysicalMemory = 0;
  1351. this->CurrentPositionInFile = 0;
  1352. this->ChipManufacturer = UnknownManufacturer;
  1353. memset(&this->Features, 0, sizeof(CPUFeatures));
  1354. this->ChipID.Type = 0;
  1355. this->ChipID.Family = 0;
  1356. this->ChipID.Model = 0;
  1357. this->ChipID.Revision = 0;
  1358. this->ChipID.ExtendedFamily = 0;
  1359. this->ChipID.ExtendedModel = 0;
  1360. this->CPUSpeedInMHz = 0;
  1361. this->NumberOfLogicalCPU = 0;
  1362. this->NumberOfPhysicalCPU = 0;
  1363. this->OSName = "";
  1364. this->Hostname = "";
  1365. this->OSRelease = "";
  1366. this->OSVersion = "";
  1367. this->OSPlatform = "";
  1368. }
  1369. SystemInformationImplementation::~SystemInformationImplementation()
  1370. {
  1371. }
  1372. void SystemInformationImplementation::RunCPUCheck()
  1373. {
  1374. #ifdef _WIN32
  1375. // Check to see if this processor supports CPUID.
  1376. bool supportsCPUID = DoesCPUSupportCPUID();
  1377. if (supportsCPUID)
  1378. {
  1379. // Retrieve the CPU details.
  1380. RetrieveCPUIdentity();
  1381. this->FindManufacturer();
  1382. RetrieveCPUFeatures();
  1383. }
  1384. // These two may be called without support for the CPUID instruction.
  1385. // (But if the instruction is there, they should be called *after*
  1386. // the above call to RetrieveCPUIdentity... that's why the two if
  1387. // blocks exist with the same "if (supportsCPUID)" logic...
  1388. //
  1389. if (!RetrieveCPUClockSpeed())
  1390. {
  1391. RetrieveClassicalCPUClockSpeed();
  1392. }
  1393. if (supportsCPUID)
  1394. {
  1395. // Retrieve cache information.
  1396. if (!RetrieveCPUCacheDetails())
  1397. {
  1398. RetrieveClassicalCPUCacheDetails();
  1399. }
  1400. // Retrieve the extended CPU details.
  1401. if (!RetrieveExtendedCPUIdentity())
  1402. {
  1403. RetrieveClassicalCPUIdentity();
  1404. }
  1405. RetrieveExtendedCPUFeatures();
  1406. RetrieveCPUPowerManagement();
  1407. // Now attempt to retrieve the serial number (if possible).
  1408. RetrieveProcessorSerialNumber();
  1409. }
  1410. this->CPUCount();
  1411. #elif defined(__APPLE__)
  1412. this->ParseSysCtl();
  1413. #elif defined (__SVR4) && defined (__sun)
  1414. this->QuerySolarisProcessor();
  1415. #elif defined(__HAIKU__)
  1416. this->QueryHaikuInfo();
  1417. #elif defined(__QNX__)
  1418. this->QueryQNXProcessor();
  1419. #elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  1420. this->QueryBSDProcessor();
  1421. #elif defined(__hpux)
  1422. this->QueryHPUXProcessor();
  1423. #elif defined(__linux) || defined(__CYGWIN__)
  1424. this->RetreiveInformationFromCpuInfoFile();
  1425. #else
  1426. this->QueryProcessor();
  1427. #endif
  1428. }
  1429. void SystemInformationImplementation::RunOSCheck()
  1430. {
  1431. this->QueryOSInformation();
  1432. }
  1433. void SystemInformationImplementation::RunMemoryCheck()
  1434. {
  1435. #if defined(__APPLE__)
  1436. this->ParseSysCtl();
  1437. #elif defined (__SVR4) && defined (__sun)
  1438. this->QuerySolarisMemory();
  1439. #elif defined(__HAIKU__)
  1440. this->QueryHaikuInfo();
  1441. #elif defined(__QNX__)
  1442. this->QueryQNXMemory();
  1443. #elif defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  1444. this->QueryBSDMemory();
  1445. #elif defined(__CYGWIN__)
  1446. this->QueryCygwinMemory();
  1447. #elif defined(_WIN32)
  1448. this->QueryWindowsMemory();
  1449. #elif defined(__hpux)
  1450. this->QueryHPUXMemory();
  1451. #elif defined(__linux)
  1452. this->QueryLinuxMemory();
  1453. #elif defined(_AIX)
  1454. this->QueryAIXMemory();
  1455. #else
  1456. this->QueryMemory();
  1457. #endif
  1458. }
  1459. /** Get the vendor string */
  1460. const char * SystemInformationImplementation::GetVendorString()
  1461. {
  1462. return this->ChipID.Vendor.c_str();
  1463. }
  1464. /** Get the OS Name */
  1465. const char * SystemInformationImplementation::GetOSName()
  1466. {
  1467. return this->OSName.c_str();
  1468. }
  1469. /** Get the hostname */
  1470. const char* SystemInformationImplementation::GetHostname()
  1471. {
  1472. if (this->Hostname.empty())
  1473. {
  1474. this->Hostname="localhost";
  1475. #if defined(_WIN32)
  1476. WORD wVersionRequested;
  1477. WSADATA wsaData;
  1478. char name[255];
  1479. wVersionRequested = MAKEWORD(2,0);
  1480. if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
  1481. {
  1482. gethostname(name,sizeof(name));
  1483. WSACleanup( );
  1484. }
  1485. this->Hostname = name;
  1486. #else
  1487. struct utsname unameInfo;
  1488. int errorFlag = uname(&unameInfo);
  1489. if(errorFlag == 0)
  1490. {
  1491. this->Hostname = unameInfo.nodename;
  1492. }
  1493. #endif
  1494. }
  1495. return this->Hostname.c_str();
  1496. }
  1497. /** Get the FQDN */
  1498. int SystemInformationImplementation::GetFullyQualifiedDomainName(
  1499. std::string &fqdn)
  1500. {
  1501. // in the event of absolute failure return localhost.
  1502. fqdn="localhost";
  1503. #if defined(_WIN32)
  1504. int ierr;
  1505. // TODO - a more robust implementation for windows, see comments
  1506. // in unix implementation.
  1507. WSADATA wsaData;
  1508. WORD ver=MAKEWORD(2,0);
  1509. ierr=WSAStartup(ver,&wsaData);
  1510. if (ierr)
  1511. {
  1512. return -1;
  1513. }
  1514. char base[256]={'\0'};
  1515. ierr=gethostname(base,256);
  1516. if (ierr)
  1517. {
  1518. WSACleanup();
  1519. return -2;
  1520. }
  1521. fqdn=base;
  1522. HOSTENT *hent=gethostbyname(base);
  1523. if (hent)
  1524. {
  1525. fqdn=hent->h_name;
  1526. }
  1527. WSACleanup();
  1528. return 0;
  1529. #elif defined(KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN)
  1530. // gethostname typical returns an alias for loopback interface
  1531. // we want the fully qualified domain name. Because there are
  1532. // any number of interfaces on this system we look for the
  1533. // first of these that contains the name returned by gethostname
  1534. // and is longer. failing that we return gethostname and indicate
  1535. // with a failure code. Return of a failure code is not necessarilly
  1536. // an indication of an error. for instance gethostname may return
  1537. // the fully qualified domain name, or there may not be one if the
  1538. // system lives on a private network such as in the case of a cluster
  1539. // node.
  1540. int ierr=0;
  1541. char base[NI_MAXHOST];
  1542. ierr=gethostname(base,NI_MAXHOST);
  1543. if (ierr)
  1544. {
  1545. return -1;
  1546. }
  1547. size_t baseSize=strlen(base);
  1548. fqdn=base;
  1549. struct ifaddrs *ifas;
  1550. struct ifaddrs *ifa;
  1551. ierr=getifaddrs(&ifas);
  1552. if (ierr)
  1553. {
  1554. return -2;
  1555. }
  1556. for (ifa=ifas; ifa!=NULL; ifa=ifa->ifa_next)
  1557. {
  1558. int fam = ifa->ifa_addr? ifa->ifa_addr->sa_family : -1;
  1559. if ((fam==AF_INET) || (fam==AF_INET6))
  1560. {
  1561. char host[NI_MAXHOST]={'\0'};
  1562. const size_t addrlen
  1563. = (fam==AF_INET?sizeof(struct sockaddr_in):sizeof(struct sockaddr_in6));
  1564. ierr=getnameinfo(
  1565. ifa->ifa_addr,
  1566. static_cast<socklen_t>(addrlen),
  1567. host,
  1568. NI_MAXHOST,
  1569. NULL,
  1570. 0,
  1571. NI_NAMEREQD);
  1572. if (ierr)
  1573. {
  1574. // don't report the failure now since we may succeed on another
  1575. // interface. If all attempts fail then return the failure code.
  1576. ierr=-3;
  1577. continue;
  1578. }
  1579. std::string candidate=host;
  1580. if ((candidate.find(base)!=std::string::npos) && baseSize<candidate.size())
  1581. {
  1582. // success, stop now.
  1583. ierr=0;
  1584. fqdn=candidate;
  1585. break;
  1586. }
  1587. }
  1588. }
  1589. freeifaddrs(ifas);
  1590. return ierr;
  1591. #else
  1592. /* TODO: Implement on more platforms. */
  1593. fqdn=this->GetHostname();
  1594. return -1;
  1595. #endif
  1596. }
  1597. /** Get the OS release */
  1598. const char* SystemInformationImplementation::GetOSRelease()
  1599. {
  1600. return this->OSRelease.c_str();
  1601. }
  1602. /** Get the OS version */
  1603. const char* SystemInformationImplementation::GetOSVersion()
  1604. {
  1605. return this->OSVersion.c_str();
  1606. }
  1607. /** Get the OS platform */
  1608. const char* SystemInformationImplementation::GetOSPlatform()
  1609. {
  1610. return this->OSPlatform.c_str();
  1611. }
  1612. /** Get the vendor ID */
  1613. const char * SystemInformationImplementation::GetVendorID()
  1614. {
  1615. // Return the vendor ID.
  1616. switch (this->ChipManufacturer)
  1617. {
  1618. case Intel:
  1619. return "Intel Corporation";
  1620. case AMD:
  1621. return "Advanced Micro Devices";
  1622. case NSC:
  1623. return "National Semiconductor";
  1624. case Cyrix:
  1625. return "Cyrix Corp., VIA Inc.";
  1626. case NexGen:
  1627. return "NexGen Inc., Advanced Micro Devices";
  1628. case IDT:
  1629. return "IDT\\Centaur, Via Inc.";
  1630. case UMC:
  1631. return "United Microelectronics Corp.";
  1632. case Rise:
  1633. return "Rise";
  1634. case Transmeta:
  1635. return "Transmeta";
  1636. case Sun:
  1637. return "Sun Microelectronics";
  1638. case IBM:
  1639. return "IBM";
  1640. case Motorola:
  1641. return "Motorola";
  1642. case HP:
  1643. return "Hewlett-Packard";
  1644. case UnknownManufacturer:
  1645. default:
  1646. return "Unknown Manufacturer";
  1647. }
  1648. }
  1649. /** Return the type ID of the CPU */
  1650. std::string SystemInformationImplementation::GetTypeID()
  1651. {
  1652. std::ostringstream str;
  1653. str << this->ChipID.Type;
  1654. return str.str();
  1655. }
  1656. /** Return the family of the CPU present */
  1657. std::string SystemInformationImplementation::GetFamilyID()
  1658. {
  1659. std::ostringstream str;
  1660. str << this->ChipID.Family;
  1661. return str.str();
  1662. }
  1663. // Return the model of CPU present */
  1664. std::string SystemInformationImplementation::GetModelID()
  1665. {
  1666. std::ostringstream str;
  1667. str << this->ChipID.Model;
  1668. return str.str();
  1669. }
  1670. // Return the model name of CPU present */
  1671. std::string SystemInformationImplementation::GetModelName()
  1672. {
  1673. return this->ChipID.ModelName;
  1674. }
  1675. /** Return the stepping code of the CPU present. */
  1676. std::string SystemInformationImplementation::GetSteppingCode()
  1677. {
  1678. std::ostringstream str;
  1679. str << this->ChipID.Revision;
  1680. return str.str();
  1681. }
  1682. /** Return the stepping code of the CPU present. */
  1683. const char * SystemInformationImplementation::GetExtendedProcessorName()
  1684. {
  1685. return this->ChipID.ProcessorName.c_str();
  1686. }
  1687. /** Return the serial number of the processor
  1688. * in hexadecimal: xxxx-xxxx-xxxx-xxxx-xxxx-xxxx. */
  1689. const char * SystemInformationImplementation::GetProcessorSerialNumber()
  1690. {
  1691. return this->ChipID.SerialNumber.c_str();
  1692. }
  1693. /** Return the logical processors per physical */
  1694. unsigned int SystemInformationImplementation::GetLogicalProcessorsPerPhysical()
  1695. {
  1696. return this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical;
  1697. }
  1698. /** Return the processor clock frequency. */
  1699. float SystemInformationImplementation::GetProcessorClockFrequency()
  1700. {
  1701. return this->CPUSpeedInMHz;
  1702. }
  1703. /** Return the APIC ID. */
  1704. int SystemInformationImplementation::GetProcessorAPICID()
  1705. {
  1706. return this->Features.ExtendedFeatures.APIC_ID;
  1707. }
  1708. /** Return the L1 cache size. */
  1709. int SystemInformationImplementation::GetProcessorCacheSize()
  1710. {
  1711. return this->Features.L1CacheSize;
  1712. }
  1713. /** Return the chosen cache size. */
  1714. int SystemInformationImplementation::GetProcessorCacheXSize(long int dwCacheID)
  1715. {
  1716. switch (dwCacheID)
  1717. {
  1718. case L1CACHE_FEATURE:
  1719. return this->Features.L1CacheSize;
  1720. case L2CACHE_FEATURE:
  1721. return this->Features.L2CacheSize;
  1722. case L3CACHE_FEATURE:
  1723. return this->Features.L3CacheSize;
  1724. }
  1725. return -1;
  1726. }
  1727. bool SystemInformationImplementation::DoesCPUSupportFeature(long int dwFeature)
  1728. {
  1729. bool bHasFeature = false;
  1730. // Check for MMX instructions.
  1731. if (((dwFeature & MMX_FEATURE) != 0) && this->Features.HasMMX) bHasFeature = true;
  1732. // Check for MMX+ instructions.
  1733. if (((dwFeature & MMX_PLUS_FEATURE) != 0) && this->Features.ExtendedFeatures.HasMMXPlus) bHasFeature = true;
  1734. // Check for SSE FP instructions.
  1735. if (((dwFeature & SSE_FEATURE) != 0) && this->Features.HasSSE) bHasFeature = true;
  1736. // Check for SSE FP instructions.
  1737. if (((dwFeature & SSE_FP_FEATURE) != 0) && this->Features.HasSSEFP) bHasFeature = true;
  1738. // Check for SSE MMX instructions.
  1739. if (((dwFeature & SSE_MMX_FEATURE) != 0) && this->Features.ExtendedFeatures.HasSSEMMX) bHasFeature = true;
  1740. // Check for SSE2 instructions.
  1741. if (((dwFeature & SSE2_FEATURE) != 0) && this->Features.HasSSE2) bHasFeature = true;
  1742. // Check for 3DNow! instructions.
  1743. if (((dwFeature & AMD_3DNOW_FEATURE) != 0) && this->Features.ExtendedFeatures.Has3DNow) bHasFeature = true;
  1744. // Check for 3DNow+ instructions.
  1745. if (((dwFeature & AMD_3DNOW_PLUS_FEATURE) != 0) && this->Features.ExtendedFeatures.Has3DNowPlus) bHasFeature = true;
  1746. // Check for IA64 instructions.
  1747. if (((dwFeature & IA64_FEATURE) != 0) && this->Features.HasIA64) bHasFeature = true;
  1748. // Check for MP capable.
  1749. if (((dwFeature & MP_CAPABLE) != 0) && this->Features.ExtendedFeatures.SupportsMP) bHasFeature = true;
  1750. // Check for a serial number for the processor.
  1751. if (((dwFeature & SERIALNUMBER_FEATURE) != 0) && this->Features.HasSerial) bHasFeature = true;
  1752. // Check for a local APIC in the processor.
  1753. if (((dwFeature & APIC_FEATURE) != 0) && this->Features.HasAPIC) bHasFeature = true;
  1754. // Check for CMOV instructions.
  1755. if (((dwFeature & CMOV_FEATURE) != 0) && this->Features.HasCMOV) bHasFeature = true;
  1756. // Check for MTRR instructions.
  1757. if (((dwFeature & MTRR_FEATURE) != 0) && this->Features.HasMTRR) bHasFeature = true;
  1758. // Check for L1 cache size.
  1759. if (((dwFeature & L1CACHE_FEATURE) != 0) && (this->Features.L1CacheSize != -1)) bHasFeature = true;
  1760. // Check for L2 cache size.
  1761. if (((dwFeature & L2CACHE_FEATURE) != 0) && (this->Features.L2CacheSize != -1)) bHasFeature = true;
  1762. // Check for L3 cache size.
  1763. if (((dwFeature & L3CACHE_FEATURE) != 0) && (this->Features.L3CacheSize != -1)) bHasFeature = true;
  1764. // Check for ACPI capability.
  1765. if (((dwFeature & ACPI_FEATURE) != 0) && this->Features.HasACPI) bHasFeature = true;
  1766. // Check for thermal monitor support.
  1767. if (((dwFeature & THERMALMONITOR_FEATURE) != 0) && this->Features.HasThermal) bHasFeature = true;
  1768. // Check for temperature sensing diode support.
  1769. if (((dwFeature & TEMPSENSEDIODE_FEATURE) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode) bHasFeature = true;
  1770. // Check for frequency ID support.
  1771. if (((dwFeature & FREQUENCYID_FEATURE) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID) bHasFeature = true;
  1772. // Check for voltage ID support.
  1773. if (((dwFeature & VOLTAGEID_FREQUENCY) != 0) && this->Features.ExtendedFeatures.PowerManagement.HasVoltageID) bHasFeature = true;
  1774. return bHasFeature;
  1775. }
  1776. void SystemInformationImplementation::Delay(unsigned int uiMS)
  1777. {
  1778. #ifdef _WIN32
  1779. LARGE_INTEGER Frequency, StartCounter, EndCounter;
  1780. __int64 x;
  1781. // Get the frequency of the high performance counter.
  1782. if (!QueryPerformanceFrequency (&Frequency)) return;
  1783. x = Frequency.QuadPart / 1000 * uiMS;
  1784. // Get the starting position of the counter.
  1785. QueryPerformanceCounter (&StartCounter);
  1786. do {
  1787. // Get the ending position of the counter.
  1788. QueryPerformanceCounter (&EndCounter);
  1789. } while (EndCounter.QuadPart - StartCounter.QuadPart < x);
  1790. #endif
  1791. (void)uiMS;
  1792. }
  1793. bool SystemInformationImplementation::DoesCPUSupportCPUID()
  1794. {
  1795. #if USE_CPUID
  1796. int dummy[4] = { 0, 0, 0, 0 };
  1797. #if USE_ASM_INSTRUCTIONS
  1798. return call_cpuid(0, dummy);
  1799. #else
  1800. call_cpuid(0, dummy);
  1801. return dummy[0] || dummy[1] || dummy[2] || dummy[3];
  1802. #endif
  1803. #else
  1804. // Assume no cpuid instruction.
  1805. return false;
  1806. #endif
  1807. }
  1808. bool SystemInformationImplementation::RetrieveCPUFeatures()
  1809. {
  1810. #if USE_CPUID
  1811. int cpuinfo[4] = { 0, 0, 0, 0 };
  1812. if (!call_cpuid(1, cpuinfo))
  1813. {
  1814. return false;
  1815. }
  1816. // Retrieve the features of CPU present.
  1817. this->Features.HasFPU = ((cpuinfo[3] & 0x00000001) != 0); // FPU Present --> Bit 0
  1818. this->Features.HasTSC = ((cpuinfo[3] & 0x00000010) != 0); // TSC Present --> Bit 4
  1819. this->Features.HasAPIC = ((cpuinfo[3] & 0x00000200) != 0); // APIC Present --> Bit 9
  1820. this->Features.HasMTRR = ((cpuinfo[3] & 0x00001000) != 0); // MTRR Present --> Bit 12
  1821. this->Features.HasCMOV = ((cpuinfo[3] & 0x00008000) != 0); // CMOV Present --> Bit 15
  1822. this->Features.HasSerial = ((cpuinfo[3] & 0x00040000) != 0); // Serial Present --> Bit 18
  1823. this->Features.HasACPI = ((cpuinfo[3] & 0x00400000) != 0); // ACPI Capable --> Bit 22
  1824. this->Features.HasMMX = ((cpuinfo[3] & 0x00800000) != 0); // MMX Present --> Bit 23
  1825. this->Features.HasSSE = ((cpuinfo[3] & 0x02000000) != 0); // SSE Present --> Bit 25
  1826. this->Features.HasSSE2 = ((cpuinfo[3] & 0x04000000) != 0); // SSE2 Present --> Bit 26
  1827. this->Features.HasThermal = ((cpuinfo[3] & 0x20000000) != 0); // Thermal Monitor Present --> Bit 29
  1828. this->Features.HasIA64 = ((cpuinfo[3] & 0x40000000) != 0); // IA64 Present --> Bit 30
  1829. #if USE_ASM_INSTRUCTIONS
  1830. // Retrieve extended SSE capabilities if SSE is available.
  1831. if (this->Features.HasSSE) {
  1832. // Attempt to __try some SSE FP instructions.
  1833. __try
  1834. {
  1835. // Perform: orps xmm0, xmm0
  1836. _asm
  1837. {
  1838. _emit 0x0f
  1839. _emit 0x56
  1840. _emit 0xc0
  1841. }
  1842. // SSE FP capable processor.
  1843. this->Features.HasSSEFP = true;
  1844. }
  1845. __except(1)
  1846. {
  1847. // bad instruction - processor or OS cannot handle SSE FP.
  1848. this->Features.HasSSEFP = false;
  1849. }
  1850. }
  1851. else
  1852. {
  1853. // Set the advanced SSE capabilities to not available.
  1854. this->Features.HasSSEFP = false;
  1855. }
  1856. #else
  1857. this->Features.HasSSEFP = false;
  1858. #endif
  1859. // Retrieve Intel specific extended features.
  1860. if (this->ChipManufacturer == Intel)
  1861. {
  1862. this->Features.ExtendedFeatures.SupportsHyperthreading = ((cpuinfo[3] & 0x10000000) != 0); // Intel specific: Hyperthreading --> Bit 28
  1863. this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical = (this->Features.ExtendedFeatures.SupportsHyperthreading) ? ((cpuinfo[1] & 0x00FF0000) >> 16) : 1;
  1864. if ((this->Features.ExtendedFeatures.SupportsHyperthreading) && (this->Features.HasAPIC))
  1865. {
  1866. // Retrieve APIC information if there is one present.
  1867. this->Features.ExtendedFeatures.APIC_ID = ((cpuinfo[1] & 0xFF000000) >> 24);
  1868. }
  1869. }
  1870. return true;
  1871. #else
  1872. return false;
  1873. #endif
  1874. }
  1875. /** Find the manufacturer given the vendor id */
  1876. void SystemInformationImplementation::FindManufacturer(const std::string& family)
  1877. {
  1878. if (this->ChipID.Vendor == "GenuineIntel") this->ChipManufacturer = Intel; // Intel Corp.
  1879. else if (this->ChipID.Vendor == "UMC UMC UMC ") this->ChipManufacturer = UMC; // United Microelectronics Corp.
  1880. else if (this->ChipID.Vendor == "AuthenticAMD") this->ChipManufacturer = AMD; // Advanced Micro Devices
  1881. else if (this->ChipID.Vendor == "AMD ISBETTER") this->ChipManufacturer = AMD; // Advanced Micro Devices (1994)
  1882. else if (this->ChipID.Vendor == "CyrixInstead") this->ChipManufacturer = Cyrix; // Cyrix Corp., VIA Inc.
  1883. else if (this->ChipID.Vendor == "NexGenDriven") this->ChipManufacturer = NexGen; // NexGen Inc. (now AMD)
  1884. else if (this->ChipID.Vendor == "CentaurHauls") this->ChipManufacturer = IDT; // IDT/Centaur (now VIA)
  1885. else if (this->ChipID.Vendor == "RiseRiseRise") this->ChipManufacturer = Rise; // Rise
  1886. else if (this->ChipID.Vendor == "GenuineTMx86") this->ChipManufacturer = Transmeta; // Transmeta
  1887. else if (this->ChipID.Vendor == "TransmetaCPU") this->ChipManufacturer = Transmeta; // Transmeta
  1888. else if (this->ChipID.Vendor == "Geode By NSC") this->ChipManufacturer = NSC; // National Semiconductor
  1889. else if (this->ChipID.Vendor == "Sun") this->ChipManufacturer = Sun; // Sun Microelectronics
  1890. else if (this->ChipID.Vendor == "IBM") this->ChipManufacturer = IBM; // IBM Microelectronics
  1891. else if (this->ChipID.Vendor == "Hewlett-Packard") this->ChipManufacturer = HP; // Hewlett-Packard
  1892. else if (this->ChipID.Vendor == "Motorola") this->ChipManufacturer = Motorola; // Motorola Microelectronics
  1893. else if (family.substr(0, 7) == "PA-RISC") this->ChipManufacturer = HP; // Hewlett-Packard
  1894. else this->ChipManufacturer = UnknownManufacturer; // Unknown manufacturer
  1895. }
  1896. /** */
  1897. bool SystemInformationImplementation::RetrieveCPUIdentity()
  1898. {
  1899. #if USE_CPUID
  1900. int localCPUVendor[4];
  1901. int localCPUSignature[4];
  1902. if (!call_cpuid(0, localCPUVendor))
  1903. {
  1904. return false;
  1905. }
  1906. if (!call_cpuid(1, localCPUSignature))
  1907. {
  1908. return false;
  1909. }
  1910. // Process the returned information.
  1911. // ; eax = 0 --> eax: maximum value of CPUID instruction.
  1912. // ; ebx: part 1 of 3; CPU signature.
  1913. // ; edx: part 2 of 3; CPU signature.
  1914. // ; ecx: part 3 of 3; CPU signature.
  1915. char vbuf[13];
  1916. memcpy (&(vbuf[0]), &(localCPUVendor[1]), sizeof (int));
  1917. memcpy (&(vbuf[4]), &(localCPUVendor[3]), sizeof (int));
  1918. memcpy (&(vbuf[8]), &(localCPUVendor[2]), sizeof (int));
  1919. vbuf[12] = '\0';
  1920. this->ChipID.Vendor = vbuf;
  1921. // Retrieve the family of CPU present.
  1922. // ; eax = 1 --> eax: CPU ID - bits 31..16 - unused, bits 15..12 - type, bits 11..8 - family, bits 7..4 - model, bits 3..0 - mask revision
  1923. // ; ebx: 31..24 - default APIC ID, 23..16 - logical processor ID, 15..8 - CFLUSH chunk size , 7..0 - brand ID
  1924. // ; edx: CPU feature flags
  1925. this->ChipID.ExtendedFamily = ((localCPUSignature[0] & 0x0FF00000) >> 20); // Bits 27..20 Used
  1926. this->ChipID.ExtendedModel = ((localCPUSignature[0] & 0x000F0000) >> 16); // Bits 19..16 Used
  1927. this->ChipID.Type = ((localCPUSignature[0] & 0x0000F000) >> 12); // Bits 15..12 Used
  1928. this->ChipID.Family = ((localCPUSignature[0] & 0x00000F00) >> 8); // Bits 11..8 Used
  1929. this->ChipID.Model = ((localCPUSignature[0] & 0x000000F0) >> 4); // Bits 7..4 Used
  1930. this->ChipID.Revision = ((localCPUSignature[0] & 0x0000000F) >> 0); // Bits 3..0 Used
  1931. return true;
  1932. #else
  1933. return false;
  1934. #endif
  1935. }
  1936. /** */
  1937. bool SystemInformationImplementation::RetrieveCPUCacheDetails()
  1938. {
  1939. #if USE_CPUID
  1940. int L1Cache[4] = { 0, 0, 0, 0 };
  1941. int L2Cache[4] = { 0, 0, 0, 0 };
  1942. // Check to see if what we are about to do is supported...
  1943. if (RetrieveCPUExtendedLevelSupport (0x80000005))
  1944. {
  1945. if (!call_cpuid(0x80000005, L1Cache))
  1946. {
  1947. return false;
  1948. }
  1949. // Save the L1 data cache size (in KB) from ecx: bits 31..24 as well as data cache size from edx: bits 31..24.
  1950. this->Features.L1CacheSize = ((L1Cache[2] & 0xFF000000) >> 24);
  1951. this->Features.L1CacheSize += ((L1Cache[3] & 0xFF000000) >> 24);
  1952. }
  1953. else
  1954. {
  1955. // Store -1 to indicate the cache could not be queried.
  1956. this->Features.L1CacheSize = -1;
  1957. }
  1958. // Check to see if what we are about to do is supported...
  1959. if (RetrieveCPUExtendedLevelSupport (0x80000006))
  1960. {
  1961. if (!call_cpuid(0x80000006, L2Cache))
  1962. {
  1963. return false;
  1964. }
  1965. // Save the L2 unified cache size (in KB) from ecx: bits 31..16.
  1966. this->Features.L2CacheSize = ((L2Cache[2] & 0xFFFF0000) >> 16);
  1967. }
  1968. else
  1969. {
  1970. // Store -1 to indicate the cache could not be queried.
  1971. this->Features.L2CacheSize = -1;
  1972. }
  1973. // Define L3 as being not present as we cannot test for it.
  1974. this->Features.L3CacheSize = -1;
  1975. #endif
  1976. // Return failure if we cannot detect either cache with this method.
  1977. return ((this->Features.L1CacheSize == -1) && (this->Features.L2CacheSize == -1)) ? false : true;
  1978. }
  1979. /** */
  1980. bool SystemInformationImplementation::RetrieveClassicalCPUCacheDetails()
  1981. {
  1982. #if USE_CPUID
  1983. int TLBCode = -1, TLBData = -1, L1Code = -1, L1Data = -1, L1Trace = -1, L2Unified = -1, L3Unified = -1;
  1984. int TLBCacheData[4] = { 0, 0, 0, 0 };
  1985. int TLBPassCounter = 0;
  1986. int TLBCacheUnit = 0;
  1987. do {
  1988. if (!call_cpuid(2, TLBCacheData))
  1989. {
  1990. return false;
  1991. }
  1992. int bob = ((TLBCacheData[0] & 0x00FF0000) >> 16);
  1993. (void)bob;
  1994. // Process the returned TLB and cache information.
  1995. for (int nCounter = 0; nCounter < TLBCACHE_INFO_UNITS; nCounter ++)
  1996. {
  1997. // First of all - decide which unit we are dealing with.
  1998. switch (nCounter)
  1999. {
  2000. // eax: bits 8..15 : bits 16..23 : bits 24..31
  2001. case 0: TLBCacheUnit = ((TLBCacheData[0] & 0x0000FF00) >> 8); break;
  2002. case 1: TLBCacheUnit = ((TLBCacheData[0] & 0x00FF0000) >> 16); break;
  2003. case 2: TLBCacheUnit = ((TLBCacheData[0] & 0xFF000000) >> 24); break;
  2004. // ebx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
  2005. case 3: TLBCacheUnit = ((TLBCacheData[1] & 0x000000FF) >> 0); break;
  2006. case 4: TLBCacheUnit = ((TLBCacheData[1] & 0x0000FF00) >> 8); break;
  2007. case 5: TLBCacheUnit = ((TLBCacheData[1] & 0x00FF0000) >> 16); break;
  2008. case 6: TLBCacheUnit = ((TLBCacheData[1] & 0xFF000000) >> 24); break;
  2009. // ecx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
  2010. case 7: TLBCacheUnit = ((TLBCacheData[2] & 0x000000FF) >> 0); break;
  2011. case 8: TLBCacheUnit = ((TLBCacheData[2] & 0x0000FF00) >> 8); break;
  2012. case 9: TLBCacheUnit = ((TLBCacheData[2] & 0x00FF0000) >> 16); break;
  2013. case 10: TLBCacheUnit = ((TLBCacheData[2] & 0xFF000000) >> 24); break;
  2014. // edx: bits 0..7 : bits 8..15 : bits 16..23 : bits 24..31
  2015. case 11: TLBCacheUnit = ((TLBCacheData[3] & 0x000000FF) >> 0); break;
  2016. case 12: TLBCacheUnit = ((TLBCacheData[3] & 0x0000FF00) >> 8); break;
  2017. case 13: TLBCacheUnit = ((TLBCacheData[3] & 0x00FF0000) >> 16); break;
  2018. case 14: TLBCacheUnit = ((TLBCacheData[3] & 0xFF000000) >> 24); break;
  2019. // Default case - an error has occurred.
  2020. default: return false;
  2021. }
  2022. // Now process the resulting unit to see what it means....
  2023. switch (TLBCacheUnit)
  2024. {
  2025. case 0x00: break;
  2026. case 0x01: STORE_TLBCACHE_INFO (TLBCode, 4); break;
  2027. case 0x02: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
  2028. case 0x03: STORE_TLBCACHE_INFO (TLBData, 4); break;
  2029. case 0x04: STORE_TLBCACHE_INFO (TLBData, 4096); break;
  2030. case 0x06: STORE_TLBCACHE_INFO (L1Code, 8); break;
  2031. case 0x08: STORE_TLBCACHE_INFO (L1Code, 16); break;
  2032. case 0x0a: STORE_TLBCACHE_INFO (L1Data, 8); break;
  2033. case 0x0c: STORE_TLBCACHE_INFO (L1Data, 16); break;
  2034. case 0x10: STORE_TLBCACHE_INFO (L1Data, 16); break; // <-- FIXME: IA-64 Only
  2035. case 0x15: STORE_TLBCACHE_INFO (L1Code, 16); break; // <-- FIXME: IA-64 Only
  2036. case 0x1a: STORE_TLBCACHE_INFO (L2Unified, 96); break; // <-- FIXME: IA-64 Only
  2037. case 0x22: STORE_TLBCACHE_INFO (L3Unified, 512); break;
  2038. case 0x23: STORE_TLBCACHE_INFO (L3Unified, 1024); break;
  2039. case 0x25: STORE_TLBCACHE_INFO (L3Unified, 2048); break;
  2040. case 0x29: STORE_TLBCACHE_INFO (L3Unified, 4096); break;
  2041. case 0x39: STORE_TLBCACHE_INFO (L2Unified, 128); break;
  2042. case 0x3c: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2043. case 0x40: STORE_TLBCACHE_INFO (L2Unified, 0); break; // <-- FIXME: No integrated L2 cache (P6 core) or L3 cache (P4 core).
  2044. case 0x41: STORE_TLBCACHE_INFO (L2Unified, 128); break;
  2045. case 0x42: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2046. case 0x43: STORE_TLBCACHE_INFO (L2Unified, 512); break;
  2047. case 0x44: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
  2048. case 0x45: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
  2049. case 0x50: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
  2050. case 0x51: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
  2051. case 0x52: STORE_TLBCACHE_INFO (TLBCode, 4096); break;
  2052. case 0x5b: STORE_TLBCACHE_INFO (TLBData, 4096); break;
  2053. case 0x5c: STORE_TLBCACHE_INFO (TLBData, 4096); break;
  2054. case 0x5d: STORE_TLBCACHE_INFO (TLBData, 4096); break;
  2055. case 0x66: STORE_TLBCACHE_INFO (L1Data, 8); break;
  2056. case 0x67: STORE_TLBCACHE_INFO (L1Data, 16); break;
  2057. case 0x68: STORE_TLBCACHE_INFO (L1Data, 32); break;
  2058. case 0x70: STORE_TLBCACHE_INFO (L1Trace, 12); break;
  2059. case 0x71: STORE_TLBCACHE_INFO (L1Trace, 16); break;
  2060. case 0x72: STORE_TLBCACHE_INFO (L1Trace, 32); break;
  2061. case 0x77: STORE_TLBCACHE_INFO (L1Code, 16); break; // <-- FIXME: IA-64 Only
  2062. case 0x79: STORE_TLBCACHE_INFO (L2Unified, 128); break;
  2063. case 0x7a: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2064. case 0x7b: STORE_TLBCACHE_INFO (L2Unified, 512); break;
  2065. case 0x7c: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
  2066. case 0x7e: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2067. case 0x81: STORE_TLBCACHE_INFO (L2Unified, 128); break;
  2068. case 0x82: STORE_TLBCACHE_INFO (L2Unified, 256); break;
  2069. case 0x83: STORE_TLBCACHE_INFO (L2Unified, 512); break;
  2070. case 0x84: STORE_TLBCACHE_INFO (L2Unified, 1024); break;
  2071. case 0x85: STORE_TLBCACHE_INFO (L2Unified, 2048); break;
  2072. case 0x88: STORE_TLBCACHE_INFO (L3Unified, 2048); break; // <-- FIXME: IA-64 Only
  2073. case 0x89: STORE_TLBCACHE_INFO (L3Unified, 4096); break; // <-- FIXME: IA-64 Only
  2074. case 0x8a: STORE_TLBCACHE_INFO (L3Unified, 8192); break; // <-- FIXME: IA-64 Only
  2075. case 0x8d: STORE_TLBCACHE_INFO (L3Unified, 3096); break; // <-- FIXME: IA-64 Only
  2076. case 0x90: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
  2077. case 0x96: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
  2078. case 0x9b: STORE_TLBCACHE_INFO (TLBCode, 262144); break; // <-- FIXME: IA-64 Only
  2079. // Default case - an error has occurred.
  2080. default: return false;
  2081. }
  2082. }
  2083. // Increment the TLB pass counter.
  2084. TLBPassCounter ++;
  2085. } while ((TLBCacheData[0] & 0x000000FF) > TLBPassCounter);
  2086. // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
  2087. if ((L1Code == -1) && (L1Data == -1) && (L1Trace == -1))
  2088. {
  2089. this->Features.L1CacheSize = -1;
  2090. }
  2091. else if ((L1Code == -1) && (L1Data == -1) && (L1Trace != -1))
  2092. {
  2093. this->Features.L1CacheSize = L1Trace;
  2094. }
  2095. else if ((L1Code != -1) && (L1Data == -1))
  2096. {
  2097. this->Features.L1CacheSize = L1Code;
  2098. }
  2099. else if ((L1Code == -1) && (L1Data != -1))
  2100. {
  2101. this->Features.L1CacheSize = L1Data;
  2102. }
  2103. else if ((L1Code != -1) && (L1Data != -1))
  2104. {
  2105. this->Features.L1CacheSize = L1Code + L1Data;
  2106. }
  2107. else
  2108. {
  2109. this->Features.L1CacheSize = -1;
  2110. }
  2111. // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
  2112. if (L2Unified == -1)
  2113. {
  2114. this->Features.L2CacheSize = -1;
  2115. }
  2116. else
  2117. {
  2118. this->Features.L2CacheSize = L2Unified;
  2119. }
  2120. // Ok - we now have the maximum TLB, L1, L2, and L3 sizes...
  2121. if (L3Unified == -1)
  2122. {
  2123. this->Features.L3CacheSize = -1;
  2124. }
  2125. else
  2126. {
  2127. this->Features.L3CacheSize = L3Unified;
  2128. }
  2129. return true;
  2130. #else
  2131. return false;
  2132. #endif
  2133. }
  2134. /** */
  2135. bool SystemInformationImplementation::RetrieveCPUClockSpeed()
  2136. {
  2137. bool retrieved = false;
  2138. #if defined(_WIN32)
  2139. unsigned int uiRepetitions = 1;
  2140. unsigned int uiMSecPerRepetition = 50;
  2141. __int64 i64Total = 0;
  2142. __int64 i64Overhead = 0;
  2143. // Check if the TSC implementation works at all
  2144. if (this->Features.HasTSC &&
  2145. GetCyclesDifference(SystemInformationImplementation::Delay,
  2146. uiMSecPerRepetition) > 0)
  2147. {
  2148. for (unsigned int nCounter = 0; nCounter < uiRepetitions; nCounter ++)
  2149. {
  2150. i64Total += GetCyclesDifference (SystemInformationImplementation::Delay,
  2151. uiMSecPerRepetition);
  2152. i64Overhead +=
  2153. GetCyclesDifference (SystemInformationImplementation::DelayOverhead,
  2154. uiMSecPerRepetition);
  2155. }
  2156. // Calculate the MHz speed.
  2157. i64Total -= i64Overhead;
  2158. i64Total /= uiRepetitions;
  2159. i64Total /= uiMSecPerRepetition;
  2160. i64Total /= 1000;
  2161. // Save the CPU speed.
  2162. this->CPUSpeedInMHz = (float) i64Total;
  2163. retrieved = true;
  2164. }
  2165. // If RDTSC is not supported, we fallback to trying to read this value
  2166. // from the registry:
  2167. if (!retrieved)
  2168. {
  2169. HKEY hKey = NULL;
  2170. LONG err = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
  2171. L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
  2172. KEY_READ, &hKey);
  2173. if (ERROR_SUCCESS == err)
  2174. {
  2175. DWORD dwType = 0;
  2176. DWORD data = 0;
  2177. DWORD dwSize = sizeof(DWORD);
  2178. err = RegQueryValueExW(hKey, L"~MHz", 0,
  2179. &dwType, (LPBYTE) &data, &dwSize);
  2180. if (ERROR_SUCCESS == err)
  2181. {
  2182. this->CPUSpeedInMHz = (float) data;
  2183. retrieved = true;
  2184. }
  2185. RegCloseKey(hKey);
  2186. hKey = NULL;
  2187. }
  2188. }
  2189. #endif
  2190. return retrieved;
  2191. }
  2192. /** */
  2193. bool SystemInformationImplementation::RetrieveClassicalCPUClockSpeed()
  2194. {
  2195. #if USE_ASM_INSTRUCTIONS
  2196. LARGE_INTEGER liStart, liEnd, liCountsPerSecond;
  2197. double dFrequency, dDifference;
  2198. // Attempt to get a starting tick count.
  2199. QueryPerformanceCounter (&liStart);
  2200. __try
  2201. {
  2202. _asm
  2203. {
  2204. mov eax, 0x80000000
  2205. mov ebx, CLASSICAL_CPU_FREQ_LOOP
  2206. Timer_Loop:
  2207. bsf ecx,eax
  2208. dec ebx
  2209. jnz Timer_Loop
  2210. }
  2211. }
  2212. __except(1)
  2213. {
  2214. return false;
  2215. }
  2216. // Attempt to get a starting tick count.
  2217. QueryPerformanceCounter (&liEnd);
  2218. // Get the difference... NB: This is in seconds....
  2219. QueryPerformanceFrequency (&liCountsPerSecond);
  2220. dDifference = (((double) liEnd.QuadPart - (double) liStart.QuadPart) / (double) liCountsPerSecond.QuadPart);
  2221. // Calculate the clock speed.
  2222. if (this->ChipID.Family == 3)
  2223. {
  2224. // 80386 processors.... Loop time is 115 cycles!
  2225. dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 115) / dDifference) / 1000000);
  2226. }
  2227. else if (this->ChipID.Family == 4)
  2228. {
  2229. // 80486 processors.... Loop time is 47 cycles!
  2230. dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 47) / dDifference) / 1000000);
  2231. }
  2232. else if (this->ChipID.Family == 5)
  2233. {
  2234. // Pentium processors.... Loop time is 43 cycles!
  2235. dFrequency = (((CLASSICAL_CPU_FREQ_LOOP * 43) / dDifference) / 1000000);
  2236. }
  2237. // Save the clock speed.
  2238. this->Features.CPUSpeed = (int) dFrequency;
  2239. return true;
  2240. #else
  2241. return false;
  2242. #endif
  2243. }
  2244. /** */
  2245. bool SystemInformationImplementation::RetrieveCPUExtendedLevelSupport(int CPULevelToCheck)
  2246. {
  2247. int cpuinfo[4] = { 0, 0, 0, 0 };
  2248. // The extended CPUID is supported by various vendors starting with the following CPU models:
  2249. //
  2250. // Manufacturer & Chip Name | Family Model Revision
  2251. //
  2252. // AMD K6, K6-2 | 5 6 x
  2253. // Cyrix GXm, Cyrix III "Joshua" | 5 4 x
  2254. // IDT C6-2 | 5 8 x
  2255. // VIA Cyrix III | 6 5 x
  2256. // Transmeta Crusoe | 5 x x
  2257. // Intel Pentium 4 | f x x
  2258. //
  2259. // We check to see if a supported processor is present...
  2260. if (this->ChipManufacturer == AMD)
  2261. {
  2262. if (this->ChipID.Family < 5) return false;
  2263. if ((this->ChipID.Family == 5) && (this->ChipID.Model < 6)) return false;
  2264. }
  2265. else if (this->ChipManufacturer == Cyrix)
  2266. {
  2267. if (this->ChipID.Family < 5) return false;
  2268. if ((this->ChipID.Family == 5) && (this->ChipID.Model < 4)) return false;
  2269. if ((this->ChipID.Family == 6) && (this->ChipID.Model < 5)) return false;
  2270. }
  2271. else if (this->ChipManufacturer == IDT)
  2272. {
  2273. if (this->ChipID.Family < 5) return false;
  2274. if ((this->ChipID.Family == 5) && (this->ChipID.Model < 8)) return false;
  2275. }
  2276. else if (this->ChipManufacturer == Transmeta)
  2277. {
  2278. if (this->ChipID.Family < 5) return false;
  2279. }
  2280. else if (this->ChipManufacturer == Intel)
  2281. {
  2282. if (this->ChipID.Family < 0xf)
  2283. {
  2284. return false;
  2285. }
  2286. }
  2287. #if USE_CPUID
  2288. if (!call_cpuid(0x80000000, cpuinfo))
  2289. {
  2290. return false;
  2291. }
  2292. #endif
  2293. // Now we have to check the level wanted vs level returned...
  2294. int nLevelWanted = (CPULevelToCheck & 0x7FFFFFFF);
  2295. int nLevelReturn = (cpuinfo[0] & 0x7FFFFFFF);
  2296. // Check to see if the level provided is supported...
  2297. if (nLevelWanted > nLevelReturn)
  2298. {
  2299. return false;
  2300. }
  2301. return true;
  2302. }
  2303. /** */
  2304. bool SystemInformationImplementation::RetrieveExtendedCPUFeatures()
  2305. {
  2306. // Check that we are not using an Intel processor as it does not support this.
  2307. if (this->ChipManufacturer == Intel)
  2308. {
  2309. return false;
  2310. }
  2311. // Check to see if what we are about to do is supported...
  2312. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000001)))
  2313. {
  2314. return false;
  2315. }
  2316. #if USE_CPUID
  2317. int localCPUExtendedFeatures[4] = { 0, 0, 0, 0 };
  2318. if (!call_cpuid(0x80000001, localCPUExtendedFeatures))
  2319. {
  2320. return false;
  2321. }
  2322. // Retrieve the extended features of CPU present.
  2323. this->Features.ExtendedFeatures.Has3DNow = ((localCPUExtendedFeatures[3] & 0x80000000) != 0); // 3DNow Present --> Bit 31.
  2324. this->Features.ExtendedFeatures.Has3DNowPlus = ((localCPUExtendedFeatures[3] & 0x40000000) != 0); // 3DNow+ Present -- > Bit 30.
  2325. this->Features.ExtendedFeatures.HasSSEMMX = ((localCPUExtendedFeatures[3] & 0x00400000) != 0); // SSE MMX Present --> Bit 22.
  2326. this->Features.ExtendedFeatures.SupportsMP = ((localCPUExtendedFeatures[3] & 0x00080000) != 0); // MP Capable -- > Bit 19.
  2327. // Retrieve AMD specific extended features.
  2328. if (this->ChipManufacturer == AMD)
  2329. {
  2330. this->Features.ExtendedFeatures.HasMMXPlus = ((localCPUExtendedFeatures[3] & 0x00400000) != 0); // AMD specific: MMX-SSE --> Bit 22
  2331. }
  2332. // Retrieve Cyrix specific extended features.
  2333. if (this->ChipManufacturer == Cyrix)
  2334. {
  2335. this->Features.ExtendedFeatures.HasMMXPlus = ((localCPUExtendedFeatures[3] & 0x01000000) != 0); // Cyrix specific: Extended MMX --> Bit 24
  2336. }
  2337. return true;
  2338. #else
  2339. return false;
  2340. #endif
  2341. }
  2342. /** */
  2343. bool SystemInformationImplementation::RetrieveProcessorSerialNumber()
  2344. {
  2345. // Check to see if the processor supports the processor serial number.
  2346. if (!this->Features.HasSerial)
  2347. {
  2348. return false;
  2349. }
  2350. #if USE_CPUID
  2351. int SerialNumber[4];
  2352. if (!call_cpuid(3, SerialNumber))
  2353. {
  2354. return false;
  2355. }
  2356. // Process the returned information.
  2357. // ; eax = 3 --> ebx: top 32 bits are the processor signature bits --> NB: Transmeta only ?!?
  2358. // ; ecx: middle 32 bits are the processor signature bits
  2359. // ; edx: bottom 32 bits are the processor signature bits
  2360. char sn[128];
  2361. sprintf (sn, "%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x",
  2362. ((SerialNumber[1] & 0xff000000) >> 24),
  2363. ((SerialNumber[1] & 0x00ff0000) >> 16),
  2364. ((SerialNumber[1] & 0x0000ff00) >> 8),
  2365. ((SerialNumber[1] & 0x000000ff) >> 0),
  2366. ((SerialNumber[2] & 0xff000000) >> 24),
  2367. ((SerialNumber[2] & 0x00ff0000) >> 16),
  2368. ((SerialNumber[2] & 0x0000ff00) >> 8),
  2369. ((SerialNumber[2] & 0x000000ff) >> 0),
  2370. ((SerialNumber[3] & 0xff000000) >> 24),
  2371. ((SerialNumber[3] & 0x00ff0000) >> 16),
  2372. ((SerialNumber[3] & 0x0000ff00) >> 8),
  2373. ((SerialNumber[3] & 0x000000ff) >> 0));
  2374. this->ChipID.SerialNumber = sn;
  2375. return true;
  2376. #else
  2377. return false;
  2378. #endif
  2379. }
  2380. /** */
  2381. bool SystemInformationImplementation::RetrieveCPUPowerManagement()
  2382. {
  2383. // Check to see if what we are about to do is supported...
  2384. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000007)))
  2385. {
  2386. this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID = false;
  2387. this->Features.ExtendedFeatures.PowerManagement.HasVoltageID = false;
  2388. this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = false;
  2389. return false;
  2390. }
  2391. #if USE_CPUID
  2392. int localCPUPowerManagement[4] = { 0, 0, 0, 0 };
  2393. if (!call_cpuid(0x80000007, localCPUPowerManagement))
  2394. {
  2395. return false;
  2396. }
  2397. // Check for the power management capabilities of the CPU.
  2398. this->Features.ExtendedFeatures.PowerManagement.HasTempSenseDiode = ((localCPUPowerManagement[3] & 0x00000001) != 0);
  2399. this->Features.ExtendedFeatures.PowerManagement.HasFrequencyID = ((localCPUPowerManagement[3] & 0x00000002) != 0);
  2400. this->Features.ExtendedFeatures.PowerManagement.HasVoltageID = ((localCPUPowerManagement[3] & 0x00000004) != 0);
  2401. return true;
  2402. #else
  2403. return false;
  2404. #endif
  2405. }
  2406. #if USE_CPUID
  2407. // Used only in USE_CPUID implementation below.
  2408. static void SystemInformationStripLeadingSpace(std::string& str)
  2409. {
  2410. // Because some manufacturers have leading white space - we have to post-process the name.
  2411. std::string::size_type pos = str.find_first_not_of(" ");
  2412. if(pos != std::string::npos)
  2413. {
  2414. str = str.substr(pos);
  2415. }
  2416. }
  2417. #endif
  2418. /** */
  2419. bool SystemInformationImplementation::RetrieveExtendedCPUIdentity()
  2420. {
  2421. // Check to see if what we are about to do is supported...
  2422. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000002)))
  2423. return false;
  2424. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000003)))
  2425. return false;
  2426. if (!RetrieveCPUExtendedLevelSupport(static_cast<int>(0x80000004)))
  2427. return false;
  2428. #if USE_CPUID
  2429. int CPUExtendedIdentity[12];
  2430. if (!call_cpuid(0x80000002, CPUExtendedIdentity))
  2431. {
  2432. return false;
  2433. }
  2434. if (!call_cpuid(0x80000003, CPUExtendedIdentity + 4))
  2435. {
  2436. return false;
  2437. }
  2438. if (!call_cpuid(0x80000004, CPUExtendedIdentity + 8))
  2439. {
  2440. return false;
  2441. }
  2442. // Process the returned information.
  2443. char nbuf[49];
  2444. memcpy (&(nbuf[0]), &(CPUExtendedIdentity[0]), sizeof (int));
  2445. memcpy (&(nbuf[4]), &(CPUExtendedIdentity[1]), sizeof (int));
  2446. memcpy (&(nbuf[8]), &(CPUExtendedIdentity[2]), sizeof (int));
  2447. memcpy (&(nbuf[12]), &(CPUExtendedIdentity[3]), sizeof (int));
  2448. memcpy (&(nbuf[16]), &(CPUExtendedIdentity[4]), sizeof (int));
  2449. memcpy (&(nbuf[20]), &(CPUExtendedIdentity[5]), sizeof (int));
  2450. memcpy (&(nbuf[24]), &(CPUExtendedIdentity[6]), sizeof (int));
  2451. memcpy (&(nbuf[28]), &(CPUExtendedIdentity[7]), sizeof (int));
  2452. memcpy (&(nbuf[32]), &(CPUExtendedIdentity[8]), sizeof (int));
  2453. memcpy (&(nbuf[36]), &(CPUExtendedIdentity[9]), sizeof (int));
  2454. memcpy (&(nbuf[40]), &(CPUExtendedIdentity[10]), sizeof (int));
  2455. memcpy (&(nbuf[44]), &(CPUExtendedIdentity[11]), sizeof (int));
  2456. nbuf[48] = '\0';
  2457. this->ChipID.ProcessorName = nbuf;
  2458. this->ChipID.ModelName = nbuf;
  2459. // Because some manufacturers have leading white space - we have to post-process the name.
  2460. SystemInformationStripLeadingSpace(this->ChipID.ProcessorName);
  2461. return true;
  2462. #else
  2463. return false;
  2464. #endif
  2465. }
  2466. /** */
  2467. bool SystemInformationImplementation::RetrieveClassicalCPUIdentity()
  2468. {
  2469. // Start by decided which manufacturer we are using....
  2470. switch (this->ChipManufacturer)
  2471. {
  2472. case Intel:
  2473. // Check the family / model / revision to determine the CPU ID.
  2474. switch (this->ChipID.Family) {
  2475. case 3:
  2476. this->ChipID.ProcessorName = "Newer i80386 family";
  2477. break;
  2478. case 4:
  2479. switch (this->ChipID.Model) {
  2480. case 0: this->ChipID.ProcessorName = "i80486DX-25/33"; break;
  2481. case 1: this->ChipID.ProcessorName = "i80486DX-50"; break;
  2482. case 2: this->ChipID.ProcessorName = "i80486SX"; break;
  2483. case 3: this->ChipID.ProcessorName = "i80486DX2"; break;
  2484. case 4: this->ChipID.ProcessorName = "i80486SL"; break;
  2485. case 5: this->ChipID.ProcessorName = "i80486SX2"; break;
  2486. case 7: this->ChipID.ProcessorName = "i80486DX2 WriteBack"; break;
  2487. case 8: this->ChipID.ProcessorName = "i80486DX4"; break;
  2488. case 9: this->ChipID.ProcessorName = "i80486DX4 WriteBack"; break;
  2489. default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false;
  2490. }
  2491. break;
  2492. case 5:
  2493. switch (this->ChipID.Model)
  2494. {
  2495. case 0: this->ChipID.ProcessorName = "P5 A-Step"; break;
  2496. case 1: this->ChipID.ProcessorName = "P5"; break;
  2497. case 2: this->ChipID.ProcessorName = "P54C"; break;
  2498. case 3: this->ChipID.ProcessorName = "P24T OverDrive"; break;
  2499. case 4: this->ChipID.ProcessorName = "P55C"; break;
  2500. case 7: this->ChipID.ProcessorName = "P54C"; break;
  2501. case 8: this->ChipID.ProcessorName = "P55C (0.25micron)"; break;
  2502. default: this->ChipID.ProcessorName = "Unknown Pentium family"; return false;
  2503. }
  2504. break;
  2505. case 6:
  2506. switch (this->ChipID.Model)
  2507. {
  2508. case 0: this->ChipID.ProcessorName = "P6 A-Step"; break;
  2509. case 1: this->ChipID.ProcessorName = "P6"; break;
  2510. case 3: this->ChipID.ProcessorName = "Pentium II (0.28 micron)"; break;
  2511. case 5: this->ChipID.ProcessorName = "Pentium II (0.25 micron)"; break;
  2512. case 6: this->ChipID.ProcessorName = "Pentium II With On-Die L2 Cache"; break;
  2513. case 7: this->ChipID.ProcessorName = "Pentium III (0.25 micron)"; break;
  2514. case 8: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 256 KB On-Die L2 Cache "; break;
  2515. case 0xa: this->ChipID.ProcessorName = "Pentium III (0.18 micron) With 1 Or 2 MB On-Die L2 Cache "; break;
  2516. case 0xb: this->ChipID.ProcessorName = "Pentium III (0.13 micron) With 256 Or 512 KB On-Die L2 Cache "; break;
  2517. case 23: this->ChipID.ProcessorName = "Intel(R) Core(TM)2 Duo CPU T9500 @ 2.60GHz"; break;
  2518. default: this->ChipID.ProcessorName = "Unknown P6 family"; return false;
  2519. }
  2520. break;
  2521. case 7:
  2522. this->ChipID.ProcessorName = "Intel Merced (IA-64)";
  2523. break;
  2524. case 0xf:
  2525. // Check the extended family bits...
  2526. switch (this->ChipID.ExtendedFamily)
  2527. {
  2528. case 0:
  2529. switch (this->ChipID.Model)
  2530. {
  2531. case 0: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break;
  2532. case 1: this->ChipID.ProcessorName = "Pentium IV (0.18 micron)"; break;
  2533. case 2: this->ChipID.ProcessorName = "Pentium IV (0.13 micron)"; break;
  2534. default: this->ChipID.ProcessorName = "Unknown Pentium 4 family"; return false;
  2535. }
  2536. break;
  2537. case 1:
  2538. this->ChipID.ProcessorName = "Intel McKinley (IA-64)";
  2539. break;
  2540. default:
  2541. this->ChipID.ProcessorName = "Pentium";
  2542. }
  2543. break;
  2544. default:
  2545. this->ChipID.ProcessorName = "Unknown Intel family";
  2546. return false;
  2547. }
  2548. break;
  2549. case AMD:
  2550. // Check the family / model / revision to determine the CPU ID.
  2551. switch (this->ChipID.Family)
  2552. {
  2553. case 4:
  2554. switch (this->ChipID.Model)
  2555. {
  2556. case 3: this->ChipID.ProcessorName = "80486DX2"; break;
  2557. case 7: this->ChipID.ProcessorName = "80486DX2 WriteBack"; break;
  2558. case 8: this->ChipID.ProcessorName = "80486DX4"; break;
  2559. case 9: this->ChipID.ProcessorName = "80486DX4 WriteBack"; break;
  2560. case 0xe: this->ChipID.ProcessorName = "5x86"; break;
  2561. case 0xf: this->ChipID.ProcessorName = "5x86WB"; break;
  2562. default: this->ChipID.ProcessorName = "Unknown 80486 family"; return false;
  2563. }
  2564. break;
  2565. case 5:
  2566. switch (this->ChipID.Model)
  2567. {
  2568. case 0: this->ChipID.ProcessorName = "SSA5 (PR75, PR90 = PR100)"; break;
  2569. case 1: this->ChipID.ProcessorName = "5k86 (PR120 = PR133)"; break;
  2570. case 2: this->ChipID.ProcessorName = "5k86 (PR166)"; break;
  2571. case 3: this->ChipID.ProcessorName = "5k86 (PR200)"; break;
  2572. case 6: this->ChipID.ProcessorName = "K6 (0.30 micron)"; break;
  2573. case 7: this->ChipID.ProcessorName = "K6 (0.25 micron)"; break;
  2574. case 8: this->ChipID.ProcessorName = "K6-2"; break;
  2575. case 9: this->ChipID.ProcessorName = "K6-III"; break;
  2576. case 0xd: this->ChipID.ProcessorName = "K6-2+ or K6-III+ (0.18 micron)"; break;
  2577. default: this->ChipID.ProcessorName = "Unknown 80586 family"; return false;
  2578. }
  2579. break;
  2580. case 6:
  2581. switch (this->ChipID.Model)
  2582. {
  2583. case 1: this->ChipID.ProcessorName = "Athlon- (0.25 micron)"; break;
  2584. case 2: this->ChipID.ProcessorName = "Athlon- (0.18 micron)"; break;
  2585. case 3: this->ChipID.ProcessorName = "Duron- (SF core)"; break;
  2586. case 4: this->ChipID.ProcessorName = "Athlon- (Thunderbird core)"; break;
  2587. case 6: this->ChipID.ProcessorName = "Athlon- (Palomino core)"; break;
  2588. case 7: this->ChipID.ProcessorName = "Duron- (Morgan core)"; break;
  2589. case 8:
  2590. if (this->Features.ExtendedFeatures.SupportsMP)
  2591. this->ChipID.ProcessorName = "Athlon - MP (Thoroughbred core)";
  2592. else this->ChipID.ProcessorName = "Athlon - XP (Thoroughbred core)";
  2593. break;
  2594. default: this->ChipID.ProcessorName = "Unknown K7 family"; return false;
  2595. }
  2596. break;
  2597. default:
  2598. this->ChipID.ProcessorName = "Unknown AMD family";
  2599. return false;
  2600. }
  2601. break;
  2602. case Transmeta:
  2603. switch (this->ChipID.Family)
  2604. {
  2605. case 5:
  2606. switch (this->ChipID.Model)
  2607. {
  2608. case 4: this->ChipID.ProcessorName = "Crusoe TM3x00 and TM5x00"; break;
  2609. default: this->ChipID.ProcessorName = "Unknown Crusoe family"; return false;
  2610. }
  2611. break;
  2612. default:
  2613. this->ChipID.ProcessorName = "Unknown Transmeta family";
  2614. return false;
  2615. }
  2616. break;
  2617. case Rise:
  2618. switch (this->ChipID.Family)
  2619. {
  2620. case 5:
  2621. switch (this->ChipID.Model)
  2622. {
  2623. case 0: this->ChipID.ProcessorName = "mP6 (0.25 micron)"; break;
  2624. case 2: this->ChipID.ProcessorName = "mP6 (0.18 micron)"; break;
  2625. default: this->ChipID.ProcessorName = "Unknown Rise family"; return false;
  2626. }
  2627. break;
  2628. default:
  2629. this->ChipID.ProcessorName = "Unknown Rise family";
  2630. return false;
  2631. }
  2632. break;
  2633. case UMC:
  2634. switch (this->ChipID.Family)
  2635. {
  2636. case 4:
  2637. switch (this->ChipID.Model)
  2638. {
  2639. case 1: this->ChipID.ProcessorName = "U5D"; break;
  2640. case 2: this->ChipID.ProcessorName = "U5S"; break;
  2641. default: this->ChipID.ProcessorName = "Unknown UMC family"; return false;
  2642. }
  2643. break;
  2644. default:
  2645. this->ChipID.ProcessorName = "Unknown UMC family";
  2646. return false;
  2647. }
  2648. break;
  2649. case IDT:
  2650. switch (this->ChipID.Family)
  2651. {
  2652. case 5:
  2653. switch (this->ChipID.Model)
  2654. {
  2655. case 4: this->ChipID.ProcessorName = "C6"; break;
  2656. case 8: this->ChipID.ProcessorName = "C2"; break;
  2657. case 9: this->ChipID.ProcessorName = "C3"; break;
  2658. default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false;
  2659. }
  2660. break;
  2661. case 6:
  2662. switch (this->ChipID.Model)
  2663. {
  2664. case 6: this->ChipID.ProcessorName = "VIA Cyrix III - Samuel"; break;
  2665. default: this->ChipID.ProcessorName = "Unknown IDT\\Centaur family"; return false;
  2666. }
  2667. break;
  2668. default:
  2669. this->ChipID.ProcessorName = "Unknown IDT\\Centaur family";
  2670. return false;
  2671. }
  2672. break;
  2673. case Cyrix:
  2674. switch (this->ChipID.Family)
  2675. {
  2676. case 4:
  2677. switch (this->ChipID.Model)
  2678. {
  2679. case 4: this->ChipID.ProcessorName = "MediaGX GX = GXm"; break;
  2680. case 9: this->ChipID.ProcessorName = "5x86"; break;
  2681. default: this->ChipID.ProcessorName = "Unknown Cx5x86 family"; return false;
  2682. }
  2683. break;
  2684. case 5:
  2685. switch (this->ChipID.Model)
  2686. {
  2687. case 2: this->ChipID.ProcessorName = "Cx6x86"; break;
  2688. case 4: this->ChipID.ProcessorName = "MediaGX GXm"; break;
  2689. default: this->ChipID.ProcessorName = "Unknown Cx6x86 family"; return false;
  2690. }
  2691. break;
  2692. case 6:
  2693. switch (this->ChipID.Model)
  2694. {
  2695. case 0: this->ChipID.ProcessorName = "6x86MX"; break;
  2696. case 5: this->ChipID.ProcessorName = "Cyrix M2 Core"; break;
  2697. case 6: this->ChipID.ProcessorName = "WinChip C5A Core"; break;
  2698. case 7: this->ChipID.ProcessorName = "WinChip C5B\\C5C Core"; break;
  2699. case 8: this->ChipID.ProcessorName = "WinChip C5C-T Core"; break;
  2700. default: this->ChipID.ProcessorName = "Unknown 6x86MX\\Cyrix III family"; return false;
  2701. }
  2702. break;
  2703. default:
  2704. this->ChipID.ProcessorName = "Unknown Cyrix family";
  2705. return false;
  2706. }
  2707. break;
  2708. case NexGen:
  2709. switch (this->ChipID.Family)
  2710. {
  2711. case 5:
  2712. switch (this->ChipID.Model)
  2713. {
  2714. case 0: this->ChipID.ProcessorName = "Nx586 or Nx586FPU"; break;
  2715. default: this->ChipID.ProcessorName = "Unknown NexGen family"; return false;
  2716. }
  2717. break;
  2718. default:
  2719. this->ChipID.ProcessorName = "Unknown NexGen family";
  2720. return false;
  2721. }
  2722. break;
  2723. case NSC:
  2724. this->ChipID.ProcessorName = "Cx486SLC \\ DLC \\ Cx486S A-Step";
  2725. break;
  2726. case Sun:
  2727. case IBM:
  2728. case Motorola:
  2729. case HP:
  2730. case UnknownManufacturer:
  2731. default:
  2732. this->ChipID.ProcessorName = "Unknown family"; // We cannot identify the processor.
  2733. return false;
  2734. }
  2735. return true;
  2736. }
  2737. /** Extract a value from the CPUInfo file */
  2738. std::string SystemInformationImplementation::ExtractValueFromCpuInfoFile(std::string buffer,const char* word,size_t init)
  2739. {
  2740. size_t pos = buffer.find(word,init);
  2741. if(pos != buffer.npos)
  2742. {
  2743. this->CurrentPositionInFile = pos;
  2744. pos = buffer.find(":",pos);
  2745. size_t pos2 = buffer.find("\n",pos);
  2746. if(pos!=buffer.npos && pos2!=buffer.npos)
  2747. {
  2748. // It may happen that the beginning matches, but this is still not the requested key.
  2749. // An example is looking for "cpu" when "cpu family" comes first. So we check that
  2750. // we have only spaces from here to pos, otherwise we search again.
  2751. for(size_t i=this->CurrentPositionInFile+strlen(word); i < pos; ++i)
  2752. {
  2753. if(buffer[i] != ' ' && buffer[i] != '\t')
  2754. {
  2755. return this->ExtractValueFromCpuInfoFile(buffer, word, pos2);
  2756. }
  2757. }
  2758. return buffer.substr(pos+2,pos2-pos-2);
  2759. }
  2760. }
  2761. this->CurrentPositionInFile = buffer.npos;
  2762. return "";
  2763. }
  2764. /** Query for the cpu status */
  2765. bool SystemInformationImplementation::RetreiveInformationFromCpuInfoFile()
  2766. {
  2767. this->NumberOfLogicalCPU = 0;
  2768. this->NumberOfPhysicalCPU = 0;
  2769. std::string buffer;
  2770. FILE *fd = fopen("/proc/cpuinfo", "r" );
  2771. if ( !fd )
  2772. {
  2773. std::cout << "Problem opening /proc/cpuinfo" << std::endl;
  2774. return false;
  2775. }
  2776. size_t fileSize = 0;
  2777. while(!feof(fd))
  2778. {
  2779. buffer += static_cast<char>(fgetc(fd));
  2780. fileSize++;
  2781. }
  2782. fclose( fd );
  2783. buffer.resize(fileSize-2);
  2784. // Number of logical CPUs (combination of multiple processors, multi-core
  2785. // and hyperthreading)
  2786. size_t pos = buffer.find("processor\t");
  2787. while(pos != buffer.npos)
  2788. {
  2789. this->NumberOfLogicalCPU++;
  2790. pos = buffer.find("processor\t",pos+1);
  2791. }
  2792. #ifdef __linux
  2793. // Find the largest physical id.
  2794. int maxId = -1;
  2795. std::string idc =
  2796. this->ExtractValueFromCpuInfoFile(buffer,"physical id");
  2797. while(this->CurrentPositionInFile != buffer.npos)
  2798. {
  2799. int id = atoi(idc.c_str());
  2800. if(id > maxId)
  2801. {
  2802. maxId=id;
  2803. }
  2804. idc = this->ExtractValueFromCpuInfoFile(buffer,"physical id",
  2805. this->CurrentPositionInFile+1);
  2806. }
  2807. // Physical ids returned by Linux don't distinguish cores.
  2808. // We want to record the total number of cores in this->NumberOfPhysicalCPU
  2809. // (checking only the first proc)
  2810. std::string cores =
  2811. this->ExtractValueFromCpuInfoFile(buffer,"cpu cores");
  2812. int numberOfCoresPerCPU=atoi(cores.c_str());
  2813. if (maxId > 0)
  2814. {
  2815. this->NumberOfPhysicalCPU=static_cast<unsigned int>(
  2816. numberOfCoresPerCPU*(maxId+1));
  2817. }
  2818. else
  2819. {
  2820. // Linux Sparc: get cpu count
  2821. this->NumberOfPhysicalCPU=
  2822. atoi(this->ExtractValueFromCpuInfoFile(buffer,"ncpus active").c_str());
  2823. }
  2824. #else // __CYGWIN__
  2825. // does not have "physical id" entries, neither "cpu cores"
  2826. // this has to be fixed for hyper-threading.
  2827. std::string cpucount =
  2828. this->ExtractValueFromCpuInfoFile(buffer,"cpu count");
  2829. this->NumberOfPhysicalCPU=
  2830. this->NumberOfLogicalCPU = atoi(cpucount.c_str());
  2831. #endif
  2832. // gotta have one, and if this is 0 then we get a / by 0n
  2833. // better to have a bad answer than a crash
  2834. if(this->NumberOfPhysicalCPU <= 0)
  2835. {
  2836. this->NumberOfPhysicalCPU = 1;
  2837. }
  2838. // LogicalProcessorsPerPhysical>1 => hyperthreading.
  2839. this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical=
  2840. this->NumberOfLogicalCPU/this->NumberOfPhysicalCPU;
  2841. // CPU speed (checking only the first processor)
  2842. std::string CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"cpu MHz");
  2843. if(!CPUSpeed.empty())
  2844. {
  2845. this->CPUSpeedInMHz = static_cast<float>(atof(CPUSpeed.c_str()));
  2846. }
  2847. #ifdef __linux
  2848. else
  2849. {
  2850. // Linux Sparc: CPU speed is in Hz and encoded in hexadecimal
  2851. CPUSpeed = this->ExtractValueFromCpuInfoFile(buffer,"Cpu0ClkTck");
  2852. this->CPUSpeedInMHz = static_cast<float>(
  2853. strtoull(CPUSpeed.c_str(),0,16))/1000000.0f;
  2854. }
  2855. #endif
  2856. // Chip family
  2857. std::string familyStr =
  2858. this->ExtractValueFromCpuInfoFile(buffer,"cpu family");
  2859. if(familyStr.empty())
  2860. {
  2861. familyStr = this->ExtractValueFromCpuInfoFile(buffer,"CPU architecture");
  2862. }
  2863. this->ChipID.Family = atoi(familyStr.c_str());
  2864. // Chip Vendor
  2865. this->ChipID.Vendor = this->ExtractValueFromCpuInfoFile(buffer,"vendor_id");
  2866. this->FindManufacturer(familyStr);
  2867. // second try for setting family
  2868. if (this->ChipID.Family == 0 && this->ChipManufacturer == HP)
  2869. {
  2870. if (familyStr == "PA-RISC 1.1a")
  2871. this->ChipID.Family = 0x11a;
  2872. else if (familyStr == "PA-RISC 2.0")
  2873. this->ChipID.Family = 0x200;
  2874. // If you really get CMake to work on a machine not belonging to
  2875. // any of those families I owe you a dinner if you get it to
  2876. // contribute nightly builds regularly.
  2877. }
  2878. // Chip Model
  2879. this->ChipID.Model = atoi(this->ExtractValueFromCpuInfoFile(buffer,"model").c_str());
  2880. if(!this->RetrieveClassicalCPUIdentity())
  2881. {
  2882. // Some platforms (e.g. PA-RISC) tell us their CPU name here.
  2883. // Note: x86 does not.
  2884. std::string cpuname = this->ExtractValueFromCpuInfoFile(buffer,"cpu");
  2885. if(!cpuname.empty())
  2886. {
  2887. this->ChipID.ProcessorName = cpuname;
  2888. }
  2889. }
  2890. // Chip revision
  2891. std::string cpurev = this->ExtractValueFromCpuInfoFile(buffer,"stepping");
  2892. if(cpurev.empty())
  2893. {
  2894. cpurev = this->ExtractValueFromCpuInfoFile(buffer,"CPU revision");
  2895. }
  2896. this->ChipID.Revision = atoi(cpurev.c_str());
  2897. // Chip Model Name
  2898. this->ChipID.ModelName = this->ExtractValueFromCpuInfoFile(buffer,"model name").c_str();
  2899. // L1 Cache size
  2900. // Different architectures may show different names for the caches.
  2901. // Sum up everything we find.
  2902. std::vector<const char*> cachename;
  2903. cachename.clear();
  2904. cachename.push_back("cache size"); // e.g. x86
  2905. cachename.push_back("I-cache"); // e.g. PA-RISC
  2906. cachename.push_back("D-cache"); // e.g. PA-RISC
  2907. this->Features.L1CacheSize = 0;
  2908. for (size_t index = 0; index < cachename.size(); index ++)
  2909. {
  2910. std::string cacheSize = this->ExtractValueFromCpuInfoFile(buffer,cachename[index]);
  2911. if (!cacheSize.empty())
  2912. {
  2913. pos = cacheSize.find(" KB");
  2914. if(pos!=cacheSize.npos)
  2915. {
  2916. cacheSize = cacheSize.substr(0,pos);
  2917. }
  2918. this->Features.L1CacheSize += atoi(cacheSize.c_str());
  2919. }
  2920. }
  2921. // processor feature flags (probably x86 specific)
  2922. std::string cpuflags = this->ExtractValueFromCpuInfoFile(buffer,"flags");
  2923. if(!cpurev.empty())
  2924. {
  2925. // now we can match every flags as space + flag + space
  2926. cpuflags = " " + cpuflags + " ";
  2927. if ((cpuflags.find(" fpu ")!=std::string::npos))
  2928. {
  2929. this->Features.HasFPU = true;
  2930. }
  2931. if ((cpuflags.find(" tsc ")!=std::string::npos))
  2932. {
  2933. this->Features.HasTSC = true;
  2934. }
  2935. if ((cpuflags.find(" mmx ")!=std::string::npos))
  2936. {
  2937. this->Features.HasMMX = true;
  2938. }
  2939. if ((cpuflags.find(" sse ")!=std::string::npos))
  2940. {
  2941. this->Features.HasSSE = true;
  2942. }
  2943. if ((cpuflags.find(" sse2 ")!=std::string::npos))
  2944. {
  2945. this->Features.HasSSE2 = true;
  2946. }
  2947. if ((cpuflags.find(" apic ")!=std::string::npos))
  2948. {
  2949. this->Features.HasAPIC = true;
  2950. }
  2951. if ((cpuflags.find(" cmov ")!=std::string::npos))
  2952. {
  2953. this->Features.HasCMOV = true;
  2954. }
  2955. if ((cpuflags.find(" mtrr ")!=std::string::npos))
  2956. {
  2957. this->Features.HasMTRR = true;
  2958. }
  2959. if ((cpuflags.find(" acpi ")!=std::string::npos))
  2960. {
  2961. this->Features.HasACPI = true;
  2962. }
  2963. if ((cpuflags.find(" 3dnow ")!=std::string::npos))
  2964. {
  2965. this->Features.ExtendedFeatures.Has3DNow = true;
  2966. }
  2967. }
  2968. return true;
  2969. }
  2970. bool SystemInformationImplementation::QueryProcessorBySysconf()
  2971. {
  2972. #if defined(_SC_NPROC_ONLN) && !defined(_SC_NPROCESSORS_ONLN)
  2973. // IRIX names this slightly different
  2974. # define _SC_NPROCESSORS_ONLN _SC_NPROC_ONLN
  2975. #endif
  2976. #ifdef _SC_NPROCESSORS_ONLN
  2977. long c = sysconf(_SC_NPROCESSORS_ONLN);
  2978. if (c <= 0)
  2979. {
  2980. return false;
  2981. }
  2982. this->NumberOfPhysicalCPU = static_cast<unsigned int>(c);
  2983. this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
  2984. return true;
  2985. #else
  2986. return false;
  2987. #endif
  2988. }
  2989. bool SystemInformationImplementation::QueryProcessor()
  2990. {
  2991. return this->QueryProcessorBySysconf();
  2992. }
  2993. /**
  2994. Get total system RAM in units of KiB.
  2995. */
  2996. SystemInformation::LongLong
  2997. SystemInformationImplementation::GetHostMemoryTotal()
  2998. {
  2999. #if defined(_WIN32)
  3000. # if defined(_MSC_VER) && _MSC_VER < 1300
  3001. MEMORYSTATUS stat;
  3002. stat.dwLength = sizeof(stat);
  3003. GlobalMemoryStatus(&stat);
  3004. return stat.dwTotalPhys/1024;
  3005. # else
  3006. MEMORYSTATUSEX statex;
  3007. statex.dwLength=sizeof(statex);
  3008. GlobalMemoryStatusEx(&statex);
  3009. return statex.ullTotalPhys/1024;
  3010. # endif
  3011. #elif defined(__linux)
  3012. SystemInformation::LongLong memTotal=0;
  3013. int ierr=GetFieldFromFile("/proc/meminfo","MemTotal:",memTotal);
  3014. if (ierr)
  3015. {
  3016. return -1;
  3017. }
  3018. return memTotal;
  3019. #elif defined(__APPLE__)
  3020. uint64_t mem;
  3021. size_t len = sizeof(mem);
  3022. int ierr=sysctlbyname("hw.memsize", &mem, &len, NULL, 0);
  3023. if (ierr)
  3024. {
  3025. return -1;
  3026. }
  3027. return mem/1024;
  3028. #else
  3029. return 0;
  3030. #endif
  3031. }
  3032. /**
  3033. Get total system RAM in units of KiB. This may differ from the
  3034. host total if a host-wide resource limit is applied.
  3035. */
  3036. SystemInformation::LongLong
  3037. SystemInformationImplementation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
  3038. {
  3039. SystemInformation::LongLong memTotal=this->GetHostMemoryTotal();
  3040. // the following mechanism is provided for systems that
  3041. // apply resource limits across groups of processes.
  3042. // this is of use on certain SMP systems (eg. SGI UV)
  3043. // where the host has a large amount of ram but a given user's
  3044. // access to it is severly restricted. The system will
  3045. // apply a limit across a set of processes. Units are in KiB.
  3046. if (hostLimitEnvVarName)
  3047. {
  3048. const char *hostLimitEnvVarValue=getenv(hostLimitEnvVarName);
  3049. if (hostLimitEnvVarValue)
  3050. {
  3051. SystemInformation::LongLong hostLimit=atoLongLong(hostLimitEnvVarValue);
  3052. if (hostLimit>0)
  3053. {
  3054. memTotal=min(hostLimit,memTotal);
  3055. }
  3056. }
  3057. }
  3058. return memTotal;
  3059. }
  3060. /**
  3061. Get total system RAM in units of KiB. This may differ from the
  3062. host total if a per-process resource limit is applied.
  3063. */
  3064. SystemInformation::LongLong
  3065. SystemInformationImplementation::GetProcMemoryAvailable(
  3066. const char *hostLimitEnvVarName,
  3067. const char *procLimitEnvVarName)
  3068. {
  3069. SystemInformation::LongLong memAvail
  3070. = this->GetHostMemoryAvailable(hostLimitEnvVarName);
  3071. // the following mechanism is provide for systems where rlimits
  3072. // are not employed. Units are in KiB.
  3073. if (procLimitEnvVarName)
  3074. {
  3075. const char *procLimitEnvVarValue=getenv(procLimitEnvVarName);
  3076. if (procLimitEnvVarValue)
  3077. {
  3078. SystemInformation::LongLong procLimit=atoLongLong(procLimitEnvVarValue);
  3079. if (procLimit>0)
  3080. {
  3081. memAvail=min(procLimit,memAvail);
  3082. }
  3083. }
  3084. }
  3085. #if defined(__linux)
  3086. int ierr;
  3087. ResourceLimitType rlim;
  3088. ierr=GetResourceLimit(RLIMIT_DATA,&rlim);
  3089. if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
  3090. {
  3091. memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
  3092. }
  3093. ierr=GetResourceLimit(RLIMIT_AS,&rlim);
  3094. if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
  3095. {
  3096. memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
  3097. }
  3098. #elif defined(__APPLE__)
  3099. struct rlimit rlim;
  3100. int ierr;
  3101. ierr=getrlimit(RLIMIT_DATA,&rlim);
  3102. if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
  3103. {
  3104. memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
  3105. }
  3106. ierr=getrlimit(RLIMIT_RSS,&rlim);
  3107. if ((ierr==0) && (rlim.rlim_cur != RLIM_INFINITY))
  3108. {
  3109. memAvail=min((SystemInformation::LongLong)rlim.rlim_cur/1024,memAvail);
  3110. }
  3111. #endif
  3112. return memAvail;
  3113. }
  3114. /**
  3115. Get RAM used by all processes in the host, in units of KiB.
  3116. */
  3117. SystemInformation::LongLong
  3118. SystemInformationImplementation::GetHostMemoryUsed()
  3119. {
  3120. #if defined(_WIN32)
  3121. # if defined(_MSC_VER) && _MSC_VER < 1300
  3122. MEMORYSTATUS stat;
  3123. stat.dwLength = sizeof(stat);
  3124. GlobalMemoryStatus(&stat);
  3125. return (stat.dwTotalPhys - stat.dwAvailPhys)/1024;
  3126. # else
  3127. MEMORYSTATUSEX statex;
  3128. statex.dwLength=sizeof(statex);
  3129. GlobalMemoryStatusEx(&statex);
  3130. return (statex.ullTotalPhys - statex.ullAvailPhys)/1024;
  3131. # endif
  3132. #elif defined(__linux)
  3133. // First try to use MemAvailable, but it only works on newer kernels
  3134. const char *names2[3]={"MemTotal:","MemAvailable:",NULL};
  3135. SystemInformation::LongLong values2[2]={SystemInformation::LongLong(0)};
  3136. int ierr=GetFieldsFromFile("/proc/meminfo",names2,values2);
  3137. if (ierr)
  3138. {
  3139. const char *names4[5]={"MemTotal:","MemFree:","Buffers:","Cached:",NULL};
  3140. SystemInformation::LongLong values4[4]={SystemInformation::LongLong(0)};
  3141. ierr=GetFieldsFromFile("/proc/meminfo",names4,values4);
  3142. if(ierr)
  3143. {
  3144. return ierr;
  3145. }
  3146. SystemInformation::LongLong &memTotal=values4[0];
  3147. SystemInformation::LongLong &memFree=values4[1];
  3148. SystemInformation::LongLong &memBuffers=values4[2];
  3149. SystemInformation::LongLong &memCached=values4[3];
  3150. return memTotal - memFree - memBuffers - memCached;
  3151. }
  3152. SystemInformation::LongLong &memTotal=values2[0];
  3153. SystemInformation::LongLong &memAvail=values2[1];
  3154. return memTotal - memAvail;
  3155. #elif defined(__APPLE__)
  3156. SystemInformation::LongLong psz=getpagesize();
  3157. if (psz<1)
  3158. {
  3159. return -1;
  3160. }
  3161. const char *names[3]={"Pages wired down:","Pages active:",NULL};
  3162. SystemInformation::LongLong values[2]={SystemInformation::LongLong(0)};
  3163. int ierr=GetFieldsFromCommand("vm_stat", names, values);
  3164. if (ierr)
  3165. {
  3166. return -1;
  3167. }
  3168. SystemInformation::LongLong &vmWired=values[0];
  3169. SystemInformation::LongLong &vmActive=values[1];
  3170. return ((vmActive+vmWired)*psz)/1024;
  3171. #else
  3172. return 0;
  3173. #endif
  3174. }
  3175. /**
  3176. Get system RAM used by the process associated with the given
  3177. process id in units of KiB.
  3178. */
  3179. SystemInformation::LongLong
  3180. SystemInformationImplementation::GetProcMemoryUsed()
  3181. {
  3182. #if defined(_WIN32) && defined(KWSYS_SYS_HAS_PSAPI)
  3183. long pid=GetCurrentProcessId();
  3184. HANDLE hProc;
  3185. hProc=OpenProcess(
  3186. PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,
  3187. false,
  3188. pid);
  3189. if (hProc==0)
  3190. {
  3191. return -1;
  3192. }
  3193. PROCESS_MEMORY_COUNTERS pmc;
  3194. int ok=GetProcessMemoryInfo(hProc,&pmc,sizeof(pmc));
  3195. CloseHandle(hProc);
  3196. if (!ok)
  3197. {
  3198. return -2;
  3199. }
  3200. return pmc.WorkingSetSize/1024;
  3201. #elif defined(__linux)
  3202. SystemInformation::LongLong memUsed=0;
  3203. int ierr=GetFieldFromFile("/proc/self/status","VmRSS:",memUsed);
  3204. if (ierr)
  3205. {
  3206. return -1;
  3207. }
  3208. return memUsed;
  3209. #elif defined(__APPLE__)
  3210. SystemInformation::LongLong memUsed=0;
  3211. pid_t pid=getpid();
  3212. std::ostringstream oss;
  3213. oss << "ps -o rss= -p " << pid;
  3214. FILE *file=popen(oss.str().c_str(),"r");
  3215. if (file==0)
  3216. {
  3217. return -1;
  3218. }
  3219. oss.str("");
  3220. while (!feof(file) && !ferror(file))
  3221. {
  3222. char buf[256]={'\0'};
  3223. errno=0;
  3224. size_t nRead=fread(buf,1,256,file);
  3225. if (ferror(file) && (errno==EINTR))
  3226. {
  3227. clearerr(file);
  3228. }
  3229. if (nRead) oss << buf;
  3230. }
  3231. int ierr=ferror(file);
  3232. pclose(file);
  3233. if (ierr)
  3234. {
  3235. return -2;
  3236. }
  3237. std::istringstream iss(oss.str());
  3238. iss >> memUsed;
  3239. return memUsed;
  3240. #else
  3241. return 0;
  3242. #endif
  3243. }
  3244. double SystemInformationImplementation::GetLoadAverage()
  3245. {
  3246. #if defined(KWSYS_CXX_HAS_GETLOADAVG)
  3247. double loadavg[3] = { 0.0, 0.0, 0.0 };
  3248. if (getloadavg(loadavg, 3) > 0)
  3249. {
  3250. return loadavg[0];
  3251. }
  3252. return -0.0;
  3253. #elif defined(KWSYS_SYSTEMINFORMATION_USE_GetSystemTimes)
  3254. // Old windows.h headers do not provide GetSystemTimes.
  3255. typedef BOOL (WINAPI *GetSystemTimesType)(LPFILETIME, LPFILETIME,
  3256. LPFILETIME);
  3257. static GetSystemTimesType pGetSystemTimes =
  3258. (GetSystemTimesType)GetProcAddress(GetModuleHandleW(L"kernel32"),
  3259. "GetSystemTimes");
  3260. FILETIME idleTime, kernelTime, userTime;
  3261. if (pGetSystemTimes && pGetSystemTimes(&idleTime, &kernelTime, &userTime))
  3262. {
  3263. unsigned __int64 const idleTicks =
  3264. fileTimeToUInt64(idleTime);
  3265. unsigned __int64 const totalTicks =
  3266. fileTimeToUInt64(kernelTime) + fileTimeToUInt64(userTime);
  3267. return calculateCPULoad(idleTicks, totalTicks) * GetNumberOfPhysicalCPU();
  3268. }
  3269. return -0.0;
  3270. #else
  3271. // Not implemented on this platform.
  3272. return -0.0;
  3273. #endif
  3274. }
  3275. /**
  3276. Get the process id of the running process.
  3277. */
  3278. SystemInformation::LongLong
  3279. SystemInformationImplementation::GetProcessId()
  3280. {
  3281. #if defined(_WIN32)
  3282. return GetCurrentProcessId();
  3283. #elif defined(__linux) || defined(__APPLE__)
  3284. return getpid();
  3285. #else
  3286. return -1;
  3287. #endif
  3288. }
  3289. /**
  3290. return current program stack in a string
  3291. demangle cxx symbols if possible.
  3292. */
  3293. std::string SystemInformationImplementation::GetProgramStack(
  3294. int firstFrame,
  3295. int wholePath)
  3296. {
  3297. std::string programStack = ""
  3298. #if !defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  3299. "WARNING: The stack could not be examined "
  3300. "because backtrace is not supported.\n"
  3301. #elif !defined(KWSYS_SYSTEMINFORMATION_HAS_DEBUG_BUILD)
  3302. "WARNING: The stack trace will not use advanced "
  3303. "capabilities because this is a release build.\n"
  3304. #else
  3305. # if !defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
  3306. "WARNING: Function names will not be demangled because "
  3307. "dladdr is not available.\n"
  3308. # endif
  3309. # if !defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
  3310. "WARNING: Function names will not be demangled "
  3311. "because cxxabi is not available.\n"
  3312. # endif
  3313. #endif
  3314. ;
  3315. std::ostringstream oss;
  3316. #if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
  3317. void *stackSymbols[256];
  3318. int nFrames=backtrace(stackSymbols,256);
  3319. for (int i=firstFrame; i<nFrames; ++i)
  3320. {
  3321. SymbolProperties symProps;
  3322. symProps.SetReportPath(wholePath);
  3323. symProps.Initialize(stackSymbols[i]);
  3324. oss << symProps << std::endl;
  3325. }
  3326. #else
  3327. (void)firstFrame;
  3328. (void)wholePath;
  3329. #endif
  3330. programStack += oss.str();
  3331. return programStack;
  3332. }
  3333. /**
  3334. when set print stack trace in response to common signals.
  3335. */
  3336. void SystemInformationImplementation::SetStackTraceOnError(int enable)
  3337. {
  3338. #if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
  3339. static int saOrigValid=0;
  3340. static struct sigaction saABRTOrig;
  3341. static struct sigaction saSEGVOrig;
  3342. static struct sigaction saTERMOrig;
  3343. static struct sigaction saINTOrig;
  3344. static struct sigaction saILLOrig;
  3345. static struct sigaction saBUSOrig;
  3346. static struct sigaction saFPEOrig;
  3347. if (enable && !saOrigValid)
  3348. {
  3349. // save the current actions
  3350. sigaction(SIGABRT,0,&saABRTOrig);
  3351. sigaction(SIGSEGV,0,&saSEGVOrig);
  3352. sigaction(SIGTERM,0,&saTERMOrig);
  3353. sigaction(SIGINT,0,&saINTOrig);
  3354. sigaction(SIGILL,0,&saILLOrig);
  3355. sigaction(SIGBUS,0,&saBUSOrig);
  3356. sigaction(SIGFPE,0,&saFPEOrig);
  3357. // enable read, disable write
  3358. saOrigValid=1;
  3359. // install ours
  3360. struct sigaction sa;
  3361. sa.sa_sigaction=(SigAction)StacktraceSignalHandler;
  3362. sa.sa_flags=SA_SIGINFO|SA_RESETHAND;
  3363. # ifdef SA_RESTART
  3364. sa.sa_flags|=SA_RESTART;
  3365. # endif
  3366. sigemptyset(&sa.sa_mask);
  3367. sigaction(SIGABRT,&sa,0);
  3368. sigaction(SIGSEGV,&sa,0);
  3369. sigaction(SIGTERM,&sa,0);
  3370. sigaction(SIGINT,&sa,0);
  3371. sigaction(SIGILL,&sa,0);
  3372. sigaction(SIGBUS,&sa,0);
  3373. sigaction(SIGFPE,&sa,0);
  3374. }
  3375. else
  3376. if (!enable && saOrigValid)
  3377. {
  3378. // restore previous actions
  3379. sigaction(SIGABRT,&saABRTOrig,0);
  3380. sigaction(SIGSEGV,&saSEGVOrig,0);
  3381. sigaction(SIGTERM,&saTERMOrig,0);
  3382. sigaction(SIGINT,&saINTOrig,0);
  3383. sigaction(SIGILL,&saILLOrig,0);
  3384. sigaction(SIGBUS,&saBUSOrig,0);
  3385. sigaction(SIGFPE,&saFPEOrig,0);
  3386. // enable write, disable read
  3387. saOrigValid=0;
  3388. }
  3389. #else
  3390. // avoid warning C4100
  3391. (void)enable;
  3392. #endif
  3393. }
  3394. bool SystemInformationImplementation::QueryWindowsMemory()
  3395. {
  3396. #if defined(_WIN32)
  3397. # if defined(_MSC_VER) && _MSC_VER < 1300
  3398. MEMORYSTATUS ms;
  3399. unsigned long tv, tp, av, ap;
  3400. ms.dwLength = sizeof(ms);
  3401. GlobalMemoryStatus(&ms);
  3402. # define MEM_VAL(value) dw##value
  3403. # else
  3404. MEMORYSTATUSEX ms;
  3405. DWORDLONG tv, tp, av, ap;
  3406. ms.dwLength = sizeof(ms);
  3407. if (0 == GlobalMemoryStatusEx(&ms))
  3408. {
  3409. return 0;
  3410. }
  3411. # define MEM_VAL(value) ull##value
  3412. # endif
  3413. tv = ms.MEM_VAL(TotalPageFile);
  3414. tp = ms.MEM_VAL(TotalPhys);
  3415. av = ms.MEM_VAL(AvailPageFile);
  3416. ap = ms.MEM_VAL(AvailPhys);
  3417. this->TotalVirtualMemory = tv>>10>>10;
  3418. this->TotalPhysicalMemory = tp>>10>>10;
  3419. this->AvailableVirtualMemory = av>>10>>10;
  3420. this->AvailablePhysicalMemory = ap>>10>>10;
  3421. return true;
  3422. #else
  3423. return false;
  3424. #endif
  3425. }
  3426. bool SystemInformationImplementation::QueryLinuxMemory()
  3427. {
  3428. #if defined(__linux)
  3429. unsigned long tv=0;
  3430. unsigned long tp=0;
  3431. unsigned long av=0;
  3432. unsigned long ap=0;
  3433. char buffer[1024]; // for reading lines
  3434. int linuxMajor = 0;
  3435. int linuxMinor = 0;
  3436. // Find the Linux kernel version first
  3437. struct utsname unameInfo;
  3438. int errorFlag = uname(&unameInfo);
  3439. if( errorFlag!=0 )
  3440. {
  3441. std::cout << "Problem calling uname(): " << strerror(errno) << std::endl;
  3442. return false;
  3443. }
  3444. if( strlen(unameInfo.release)>=3 )
  3445. {
  3446. // release looks like "2.6.3-15mdk-i686-up-4GB"
  3447. char majorChar=unameInfo.release[0];
  3448. char minorChar=unameInfo.release[2];
  3449. if( isdigit(majorChar) )
  3450. {
  3451. linuxMajor=majorChar-'0';
  3452. }
  3453. if( isdigit(minorChar) )
  3454. {
  3455. linuxMinor=minorChar-'0';
  3456. }
  3457. }
  3458. FILE *fd = fopen("/proc/meminfo", "r" );
  3459. if ( !fd )
  3460. {
  3461. std::cout << "Problem opening /proc/meminfo" << std::endl;
  3462. return false;
  3463. }
  3464. if( linuxMajor>=3 || ( (linuxMajor>=2) && (linuxMinor>=6) ) )
  3465. {
  3466. // new /proc/meminfo format since kernel 2.6.x
  3467. // Rigorously, this test should check from the developping version 2.5.x
  3468. // that introduced the new format...
  3469. enum { mMemTotal, mMemFree, mBuffers, mCached, mSwapTotal, mSwapFree };
  3470. const char* format[6] =
  3471. { "MemTotal:%lu kB", "MemFree:%lu kB", "Buffers:%lu kB",
  3472. "Cached:%lu kB", "SwapTotal:%lu kB", "SwapFree:%lu kB" };
  3473. bool have[6] = { false, false, false, false, false, false };
  3474. unsigned long value[6];
  3475. int count = 0;
  3476. while(fgets(buffer, static_cast<int>(sizeof(buffer)), fd))
  3477. {
  3478. for(int i=0; i < 6; ++i)
  3479. {
  3480. if(!have[i] && sscanf(buffer, format[i], &value[i]) == 1)
  3481. {
  3482. have[i] = true;
  3483. ++count;
  3484. }
  3485. }
  3486. }
  3487. if(count == 6)
  3488. {
  3489. this->TotalPhysicalMemory = value[mMemTotal] / 1024;
  3490. this->AvailablePhysicalMemory =
  3491. (value[mMemFree] + value[mBuffers] + value[mCached]) / 1024;
  3492. this->TotalVirtualMemory = value[mSwapTotal] / 1024;
  3493. this->AvailableVirtualMemory = value[mSwapFree] / 1024;
  3494. }
  3495. else
  3496. {
  3497. std::cout << "Problem parsing /proc/meminfo" << std::endl;
  3498. fclose(fd);
  3499. return false;
  3500. }
  3501. }
  3502. else
  3503. {
  3504. // /proc/meminfo format for kernel older than 2.6.x
  3505. unsigned long temp;
  3506. unsigned long cachedMem;
  3507. unsigned long buffersMem;
  3508. // Skip "total: used:..."
  3509. char *r=fgets(buffer, static_cast<int>(sizeof(buffer)), fd);
  3510. int status=0;
  3511. if(r==buffer)
  3512. {
  3513. status+=fscanf(fd, "Mem: %lu %lu %lu %lu %lu %lu\n",
  3514. &tp, &temp, &ap, &temp, &buffersMem, &cachedMem);
  3515. }
  3516. if(status==6)
  3517. {
  3518. status+=fscanf(fd, "Swap: %lu %lu %lu\n", &tv, &temp, &av);
  3519. }
  3520. if(status==9)
  3521. {
  3522. this->TotalVirtualMemory = tv>>10>>10;
  3523. this->TotalPhysicalMemory = tp>>10>>10;
  3524. this->AvailableVirtualMemory = av>>10>>10;
  3525. this->AvailablePhysicalMemory = (ap+buffersMem+cachedMem)>>10>>10;
  3526. }
  3527. else
  3528. {
  3529. std::cout << "Problem parsing /proc/meminfo" << std::endl;
  3530. fclose(fd);
  3531. return false;
  3532. }
  3533. }
  3534. fclose( fd );
  3535. return true;
  3536. #else
  3537. return false;
  3538. #endif
  3539. }
  3540. bool SystemInformationImplementation::QueryCygwinMemory()
  3541. {
  3542. #ifdef __CYGWIN__
  3543. // _SC_PAGE_SIZE does return the mmap() granularity on Cygwin,
  3544. // see http://cygwin.com/ml/cygwin/2006-06/msg00350.html
  3545. // Therefore just use 4096 as the page size of Windows.
  3546. long m = sysconf(_SC_PHYS_PAGES);
  3547. if (m < 0)
  3548. {
  3549. return false;
  3550. }
  3551. this->TotalPhysicalMemory = m >> 8;
  3552. return true;
  3553. #else
  3554. return false;
  3555. #endif
  3556. }
  3557. bool SystemInformationImplementation::QueryAIXMemory()
  3558. {
  3559. #if defined(_AIX) && defined(_SC_AIX_REALMEM)
  3560. long c = sysconf(_SC_AIX_REALMEM);
  3561. if (c <= 0)
  3562. {
  3563. return false;
  3564. }
  3565. this->TotalPhysicalMemory = c / 1024;
  3566. return true;
  3567. #else
  3568. return false;
  3569. #endif
  3570. }
  3571. bool SystemInformationImplementation::QueryMemoryBySysconf()
  3572. {
  3573. #if defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE)
  3574. // Assume the mmap() granularity as returned by _SC_PAGESIZE is also
  3575. // the system page size. The only known system where this isn't true
  3576. // is Cygwin.
  3577. long p = sysconf(_SC_PHYS_PAGES);
  3578. long m = sysconf(_SC_PAGESIZE);
  3579. if (p < 0 || m < 0)
  3580. {
  3581. return false;
  3582. }
  3583. // assume pagesize is a power of 2 and smaller 1 MiB
  3584. size_t pagediv = (1024 * 1024 / m);
  3585. this->TotalPhysicalMemory = p;
  3586. this->TotalPhysicalMemory /= pagediv;
  3587. #if defined(_SC_AVPHYS_PAGES)
  3588. p = sysconf(_SC_AVPHYS_PAGES);
  3589. if (p < 0)
  3590. {
  3591. return false;
  3592. }
  3593. this->AvailablePhysicalMemory = p;
  3594. this->AvailablePhysicalMemory /= pagediv;
  3595. #endif
  3596. return true;
  3597. #else
  3598. return false;
  3599. #endif
  3600. }
  3601. /** Query for the memory status */
  3602. bool SystemInformationImplementation::QueryMemory()
  3603. {
  3604. return this->QueryMemoryBySysconf();
  3605. }
  3606. /** */
  3607. size_t SystemInformationImplementation::GetTotalVirtualMemory()
  3608. {
  3609. return this->TotalVirtualMemory;
  3610. }
  3611. /** */
  3612. size_t SystemInformationImplementation::GetAvailableVirtualMemory()
  3613. {
  3614. return this->AvailableVirtualMemory;
  3615. }
  3616. size_t SystemInformationImplementation::GetTotalPhysicalMemory()
  3617. {
  3618. return this->TotalPhysicalMemory;
  3619. }
  3620. /** */
  3621. size_t SystemInformationImplementation::GetAvailablePhysicalMemory()
  3622. {
  3623. return this->AvailablePhysicalMemory;
  3624. }
  3625. /** Get Cycle differences */
  3626. SystemInformation::LongLong
  3627. SystemInformationImplementation::GetCyclesDifference (DELAY_FUNC DelayFunction,
  3628. unsigned int uiParameter)
  3629. {
  3630. #if defined(_MSC_VER) && (_MSC_VER >= 1400)
  3631. unsigned __int64 stamp1, stamp2;
  3632. stamp1 = __rdtsc();
  3633. DelayFunction(uiParameter);
  3634. stamp2 = __rdtsc();
  3635. return stamp2 - stamp1;
  3636. #elif USE_ASM_INSTRUCTIONS
  3637. unsigned int edx1, eax1;
  3638. unsigned int edx2, eax2;
  3639. // Calculate the frequency of the CPU instructions.
  3640. __try {
  3641. _asm {
  3642. push uiParameter ; push parameter param
  3643. mov ebx, DelayFunction ; store func in ebx
  3644. RDTSC_INSTRUCTION
  3645. mov esi, eax ; esi = eax
  3646. mov edi, edx ; edi = edx
  3647. call ebx ; call the delay functions
  3648. RDTSC_INSTRUCTION
  3649. pop ebx
  3650. mov edx2, edx ; edx2 = edx
  3651. mov eax2, eax ; eax2 = eax
  3652. mov edx1, edi ; edx2 = edi
  3653. mov eax1, esi ; eax2 = esi
  3654. }
  3655. }
  3656. __except(1)
  3657. {
  3658. return -1;
  3659. }
  3660. return ((((__int64) edx2 << 32) + eax2) - (((__int64) edx1 << 32) + eax1));
  3661. #else
  3662. (void)DelayFunction;
  3663. (void)uiParameter;
  3664. return -1;
  3665. #endif
  3666. }
  3667. /** Compute the delay overhead */
  3668. void SystemInformationImplementation::DelayOverhead(unsigned int uiMS)
  3669. {
  3670. #if defined(_WIN32)
  3671. LARGE_INTEGER Frequency, StartCounter, EndCounter;
  3672. __int64 x;
  3673. // Get the frequency of the high performance counter.
  3674. if(!QueryPerformanceFrequency (&Frequency))
  3675. {
  3676. return;
  3677. }
  3678. x = Frequency.QuadPart / 1000 * uiMS;
  3679. // Get the starting position of the counter.
  3680. QueryPerformanceCounter (&StartCounter);
  3681. do {
  3682. // Get the ending position of the counter.
  3683. QueryPerformanceCounter (&EndCounter);
  3684. } while (EndCounter.QuadPart - StartCounter.QuadPart == x);
  3685. #endif
  3686. (void)uiMS;
  3687. }
  3688. /** Return the number of logical CPU per physical CPUs Works only for windows */
  3689. unsigned char SystemInformationImplementation::LogicalCPUPerPhysicalCPU(void)
  3690. {
  3691. #ifdef __APPLE__
  3692. size_t len = 4;
  3693. int cores_per_package = 0;
  3694. int err = sysctlbyname("machdep.cpu.cores_per_package", &cores_per_package, &len, NULL, 0);
  3695. if (err != 0)
  3696. {
  3697. return 1; // That name was not found, default to 1
  3698. }
  3699. return static_cast<unsigned char>(cores_per_package);
  3700. #else
  3701. int Regs[4] = { 0, 0, 0, 0 };
  3702. #if USE_CPUID
  3703. if (!this->IsHyperThreadingSupported())
  3704. {
  3705. return static_cast<unsigned char>(1); // HT not supported
  3706. }
  3707. call_cpuid(1, Regs);
  3708. #endif
  3709. return static_cast<unsigned char> ((Regs[1] & NUM_LOGICAL_BITS) >> 16);
  3710. #endif
  3711. }
  3712. /** Works only for windows */
  3713. bool SystemInformationImplementation::IsHyperThreadingSupported()
  3714. {
  3715. if (this->Features.ExtendedFeatures.SupportsHyperthreading)
  3716. {
  3717. return true;
  3718. }
  3719. #if USE_CPUID
  3720. int Regs[4] = { 0, 0, 0, 0 },
  3721. VendorId[4] = { 0, 0, 0, 0 };
  3722. // Get vendor id string
  3723. if (!call_cpuid(0, VendorId))
  3724. {
  3725. return false;
  3726. }
  3727. // eax contains family processor type
  3728. // edx has info about the availability of hyper-Threading
  3729. if (!call_cpuid(1, Regs))
  3730. {
  3731. return false;
  3732. }
  3733. if (((Regs[0] & FAMILY_ID) == PENTIUM4_ID) || (Regs[0] & EXT_FAMILY_ID))
  3734. {
  3735. if (VendorId[1] == 0x756e6547) // 'uneG'
  3736. {
  3737. if (VendorId[3] == 0x49656e69) // 'Ieni'
  3738. {
  3739. if (VendorId[2] == 0x6c65746e) // 'letn'
  3740. {
  3741. // Genuine Intel with hyper-Threading technology
  3742. this->Features.ExtendedFeatures.SupportsHyperthreading = ((Regs[3] & HT_BIT) != 0);
  3743. return this->Features.ExtendedFeatures.SupportsHyperthreading;
  3744. }
  3745. }
  3746. }
  3747. }
  3748. #endif
  3749. return 0; // Not genuine Intel processor
  3750. }
  3751. /** Return the APIC Id. Works only for windows. */
  3752. unsigned char SystemInformationImplementation::GetAPICId()
  3753. {
  3754. int Regs[4] = { 0, 0, 0, 0 };
  3755. #if USE_CPUID
  3756. if (!this->IsHyperThreadingSupported())
  3757. {
  3758. return static_cast<unsigned char>(-1); // HT not supported
  3759. } // Logical processor = 1
  3760. call_cpuid(1, Regs);
  3761. #endif
  3762. return static_cast<unsigned char>((Regs[1] & INITIAL_APIC_ID_BITS) >> 24);
  3763. }
  3764. /** Count the number of CPUs. Works only on windows. */
  3765. int SystemInformationImplementation::CPUCount()
  3766. {
  3767. #if defined(_WIN32)
  3768. unsigned char StatusFlag = 0;
  3769. SYSTEM_INFO info;
  3770. this->NumberOfPhysicalCPU = 0;
  3771. this->NumberOfLogicalCPU = 0;
  3772. info.dwNumberOfProcessors = 0;
  3773. GetSystemInfo (&info);
  3774. // Number of physical processors in a non-Intel system
  3775. // or in a 32-bit Intel system with Hyper-Threading technology disabled
  3776. this->NumberOfPhysicalCPU = (unsigned char) info.dwNumberOfProcessors;
  3777. if (this->IsHyperThreadingSupported())
  3778. {
  3779. unsigned char HT_Enabled = 0;
  3780. this->NumberOfLogicalCPU = this->LogicalCPUPerPhysicalCPU();
  3781. if (this->NumberOfLogicalCPU >= 1) // >1 Doesn't mean HT is enabled in the BIOS
  3782. {
  3783. HANDLE hCurrentProcessHandle;
  3784. #ifndef _WIN64
  3785. # define DWORD_PTR DWORD
  3786. #endif
  3787. DWORD_PTR dwProcessAffinity;
  3788. DWORD_PTR dwSystemAffinity;
  3789. DWORD dwAffinityMask;
  3790. // Calculate the appropriate shifts and mask based on the
  3791. // number of logical processors.
  3792. unsigned int i = 1;
  3793. unsigned char PHY_ID_MASK = 0xFF;
  3794. //unsigned char PHY_ID_SHIFT = 0;
  3795. while (i < this->NumberOfLogicalCPU)
  3796. {
  3797. i *= 2;
  3798. PHY_ID_MASK <<= 1;
  3799. // PHY_ID_SHIFT++;
  3800. }
  3801. hCurrentProcessHandle = GetCurrentProcess();
  3802. GetProcessAffinityMask(hCurrentProcessHandle, &dwProcessAffinity,
  3803. &dwSystemAffinity);
  3804. // Check if available process affinity mask is equal to the
  3805. // available system affinity mask
  3806. if (dwProcessAffinity != dwSystemAffinity)
  3807. {
  3808. StatusFlag = HT_CANNOT_DETECT;
  3809. this->NumberOfPhysicalCPU = (unsigned char)-1;
  3810. return StatusFlag;
  3811. }
  3812. dwAffinityMask = 1;
  3813. while (dwAffinityMask != 0 && dwAffinityMask <= dwProcessAffinity)
  3814. {
  3815. // Check if this CPU is available
  3816. if (dwAffinityMask & dwProcessAffinity)
  3817. {
  3818. if (SetProcessAffinityMask(hCurrentProcessHandle,
  3819. dwAffinityMask))
  3820. {
  3821. unsigned char APIC_ID, LOG_ID;
  3822. Sleep(0); // Give OS time to switch CPU
  3823. APIC_ID = GetAPICId();
  3824. LOG_ID = APIC_ID & ~PHY_ID_MASK;
  3825. if (LOG_ID != 0)
  3826. {
  3827. HT_Enabled = 1;
  3828. }
  3829. }
  3830. }
  3831. dwAffinityMask = dwAffinityMask << 1;
  3832. }
  3833. // Reset the processor affinity
  3834. SetProcessAffinityMask(hCurrentProcessHandle, dwProcessAffinity);
  3835. if (this->NumberOfLogicalCPU == 1) // Normal P4 : HT is disabled in hardware
  3836. {
  3837. StatusFlag = HT_DISABLED;
  3838. }
  3839. else
  3840. {
  3841. if (HT_Enabled)
  3842. {
  3843. // Total physical processors in a Hyper-Threading enabled system.
  3844. this->NumberOfPhysicalCPU /= (this->NumberOfLogicalCPU);
  3845. StatusFlag = HT_ENABLED;
  3846. }
  3847. else
  3848. {
  3849. StatusFlag = HT_SUPPORTED_NOT_ENABLED;
  3850. }
  3851. }
  3852. }
  3853. }
  3854. else
  3855. {
  3856. // Processors do not have Hyper-Threading technology
  3857. StatusFlag = HT_NOT_CAPABLE;
  3858. this->NumberOfLogicalCPU = 1;
  3859. }
  3860. return StatusFlag;
  3861. #else
  3862. return 0;
  3863. #endif
  3864. }
  3865. /** Return the number of logical CPUs on the system */
  3866. unsigned int SystemInformationImplementation::GetNumberOfLogicalCPU()
  3867. {
  3868. return this->NumberOfLogicalCPU;
  3869. }
  3870. /** Return the number of physical CPUs on the system */
  3871. unsigned int SystemInformationImplementation::GetNumberOfPhysicalCPU()
  3872. {
  3873. return this->NumberOfPhysicalCPU;
  3874. }
  3875. /** For Mac use sysctlbyname calls to find system info */
  3876. bool SystemInformationImplementation::ParseSysCtl()
  3877. {
  3878. #if defined(__APPLE__)
  3879. char retBuf[128];
  3880. int err = 0;
  3881. uint64_t value = 0;
  3882. size_t len = sizeof(value);
  3883. sysctlbyname("hw.memsize", &value, &len, NULL, 0);
  3884. this->TotalPhysicalMemory = static_cast< size_t >( value/1048576 );
  3885. // Parse values for Mac
  3886. this->AvailablePhysicalMemory = 0;
  3887. vm_statistics_data_t vmstat;
  3888. mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
  3889. if ( host_statistics(mach_host_self(), HOST_VM_INFO,
  3890. (host_info_t) &vmstat, &count) == KERN_SUCCESS )
  3891. {
  3892. len = sizeof(value);
  3893. err = sysctlbyname("hw.pagesize", &value, &len, NULL, 0);
  3894. int64_t available_memory = vmstat.free_count * value;
  3895. this->AvailablePhysicalMemory = static_cast< size_t >( available_memory / 1048576 );
  3896. }
  3897. #ifdef VM_SWAPUSAGE
  3898. // Virtual memory.
  3899. int mib[2] = { CTL_VM, VM_SWAPUSAGE };
  3900. size_t miblen = sizeof(mib) / sizeof(mib[0]);
  3901. struct xsw_usage swap;
  3902. len = sizeof(swap);
  3903. err = sysctl(mib, miblen, &swap, &len, NULL, 0);
  3904. if (err == 0)
  3905. {
  3906. this->AvailableVirtualMemory = static_cast< size_t >( swap.xsu_avail/1048576 );
  3907. this->TotalVirtualMemory = static_cast< size_t >( swap.xsu_total/1048576 );
  3908. }
  3909. #else
  3910. this->AvailableVirtualMemory = 0;
  3911. this->TotalVirtualMemory = 0;
  3912. #endif
  3913. // CPU Info
  3914. len = sizeof(this->NumberOfPhysicalCPU);
  3915. sysctlbyname("hw.physicalcpu", &this->NumberOfPhysicalCPU, &len, NULL, 0);
  3916. len = sizeof(this->NumberOfLogicalCPU);
  3917. sysctlbyname("hw.logicalcpu", &this->NumberOfLogicalCPU, &len, NULL, 0);
  3918. this->Features.ExtendedFeatures.LogicalProcessorsPerPhysical =
  3919. this->LogicalCPUPerPhysicalCPU();
  3920. len = sizeof(value);
  3921. sysctlbyname("hw.cpufrequency", &value, &len, NULL, 0);
  3922. this->CPUSpeedInMHz = static_cast< float >( value )/ 1000000;
  3923. // Chip family
  3924. len = sizeof(this->ChipID.Family);
  3925. //Seems only the intel chips will have this name so if this fails it is
  3926. //probably a PPC machine
  3927. err = sysctlbyname("machdep.cpu.family",
  3928. &this->ChipID.Family, &len, NULL, 0);
  3929. if (err != 0) // Go back to names we know but are less descriptive
  3930. {
  3931. this->ChipID.Family = 0;
  3932. ::memset(retBuf, 0, 128);
  3933. len = 32;
  3934. err = sysctlbyname("hw.machine", &retBuf, &len, NULL, 0);
  3935. std::string machineBuf(retBuf);
  3936. if (machineBuf.find_first_of("Power") != std::string::npos)
  3937. {
  3938. this->ChipID.Vendor = "IBM";
  3939. len = sizeof(this->ChipID.Family);
  3940. err = sysctlbyname("hw.cputype", &this->ChipID.Family, &len, NULL, 0);
  3941. len = sizeof(this->ChipID.Model);
  3942. err = sysctlbyname("hw.cpusubtype", &this->ChipID.Model, &len, NULL, 0);
  3943. this->FindManufacturer();
  3944. }
  3945. }
  3946. else // Should be an Intel Chip.
  3947. {
  3948. len = sizeof(this->ChipID.Family);
  3949. err =
  3950. sysctlbyname("machdep.cpu.family", &this->ChipID.Family, &len, NULL, 0);
  3951. ::memset(retBuf, 0, 128);
  3952. len = 128;
  3953. err = sysctlbyname("machdep.cpu.vendor", retBuf, &len, NULL, 0);
  3954. // Chip Vendor
  3955. this->ChipID.Vendor = retBuf;
  3956. this->FindManufacturer();
  3957. // Chip Model
  3958. len = sizeof(value);
  3959. err = sysctlbyname("machdep.cpu.model", &value, &len, NULL, 0);
  3960. this->ChipID.Model = static_cast< int >( value );
  3961. // Chip Stepping
  3962. len = sizeof(value);
  3963. value = 0;
  3964. err = sysctlbyname("machdep.cpu.stepping", &value, &len, NULL, 0);
  3965. if (!err)
  3966. {
  3967. this->ChipID.Revision = static_cast< int >( value );
  3968. }
  3969. // feature string
  3970. char *buf = 0;
  3971. size_t allocSize = 128;
  3972. err = 0;
  3973. len = 0;
  3974. // sysctlbyname() will return with err==0 && len==0 if the buffer is too small
  3975. while (err == 0 && len == 0)
  3976. {
  3977. delete[] buf;
  3978. allocSize *= 2;
  3979. buf = new char[allocSize];
  3980. if (!buf)
  3981. {
  3982. break;
  3983. }
  3984. buf[0] = ' ';
  3985. len = allocSize - 2; // keep space for leading and trailing space
  3986. err = sysctlbyname("machdep.cpu.features", buf + 1, &len, NULL, 0);
  3987. }
  3988. if (!err && buf && len)
  3989. {
  3990. // now we can match every flags as space + flag + space
  3991. buf[len + 1] = ' ';
  3992. std::string cpuflags(buf, len + 2);
  3993. if ((cpuflags.find(" FPU ")!=std::string::npos))
  3994. {
  3995. this->Features.HasFPU = true;
  3996. }
  3997. if ((cpuflags.find(" TSC ")!=std::string::npos))
  3998. {
  3999. this->Features.HasTSC = true;
  4000. }
  4001. if ((cpuflags.find(" MMX ")!=std::string::npos))
  4002. {
  4003. this->Features.HasMMX = true;
  4004. }
  4005. if ((cpuflags.find(" SSE ")!=std::string::npos))
  4006. {
  4007. this->Features.HasSSE = true;
  4008. }
  4009. if ((cpuflags.find(" SSE2 ")!=std::string::npos))
  4010. {
  4011. this->Features.HasSSE2 = true;
  4012. }
  4013. if ((cpuflags.find(" APIC ")!=std::string::npos))
  4014. {
  4015. this->Features.HasAPIC = true;
  4016. }
  4017. if ((cpuflags.find(" CMOV ")!=std::string::npos))
  4018. {
  4019. this->Features.HasCMOV = true;
  4020. }
  4021. if ((cpuflags.find(" MTRR ")!=std::string::npos))
  4022. {
  4023. this->Features.HasMTRR = true;
  4024. }
  4025. if ((cpuflags.find(" ACPI ")!=std::string::npos))
  4026. {
  4027. this->Features.HasACPI = true;
  4028. }
  4029. }
  4030. delete[] buf;
  4031. }
  4032. // brand string
  4033. ::memset(retBuf, 0, sizeof(retBuf));
  4034. len = sizeof(retBuf);
  4035. err = sysctlbyname("machdep.cpu.brand_string", retBuf, &len, NULL, 0);
  4036. if (!err)
  4037. {
  4038. this->ChipID.ProcessorName = retBuf;
  4039. this->ChipID.ModelName = retBuf;
  4040. }
  4041. // Cache size
  4042. len = sizeof(value);
  4043. err = sysctlbyname("hw.l1icachesize", &value, &len, NULL, 0);
  4044. this->Features.L1CacheSize = static_cast< int >( value );
  4045. len = sizeof(value);
  4046. err = sysctlbyname("hw.l2cachesize", &value, &len, NULL, 0);
  4047. this->Features.L2CacheSize = static_cast< int >( value );
  4048. return true;
  4049. #else
  4050. return false;
  4051. #endif
  4052. }
  4053. /** Extract a value from sysctl command */
  4054. std::string SystemInformationImplementation::ExtractValueFromSysCtl(const char* word)
  4055. {
  4056. size_t pos = this->SysCtlBuffer.find(word);
  4057. if(pos != this->SysCtlBuffer.npos)
  4058. {
  4059. pos = this->SysCtlBuffer.find(": ",pos);
  4060. size_t pos2 = this->SysCtlBuffer.find("\n",pos);
  4061. if(pos!=this->SysCtlBuffer.npos && pos2!=this->SysCtlBuffer.npos)
  4062. {
  4063. return this->SysCtlBuffer.substr(pos+2,pos2-pos-2);
  4064. }
  4065. }
  4066. return "";
  4067. }
  4068. /** Run a given process */
  4069. std::string SystemInformationImplementation::RunProcess(std::vector<const char*> args)
  4070. {
  4071. std::string buffer = "";
  4072. // Run the application
  4073. kwsysProcess* gp = kwsysProcess_New();
  4074. kwsysProcess_SetCommand(gp, &*args.begin());
  4075. kwsysProcess_SetOption(gp,kwsysProcess_Option_HideWindow,1);
  4076. kwsysProcess_Execute(gp);
  4077. char* data = NULL;
  4078. int length;
  4079. double timeout = 255;
  4080. int pipe; // pipe id as returned by kwsysProcess_WaitForData()
  4081. while( ( static_cast<void>(pipe = kwsysProcess_WaitForData(gp,&data,&length,&timeout)),
  4082. (pipe == kwsysProcess_Pipe_STDOUT || pipe == kwsysProcess_Pipe_STDERR) ) ) // wait for 1s
  4083. {
  4084. buffer.append(data, length);
  4085. }
  4086. kwsysProcess_WaitForExit(gp, 0);
  4087. int result = 0;
  4088. switch(kwsysProcess_GetState(gp))
  4089. {
  4090. case kwsysProcess_State_Exited:
  4091. {
  4092. result = kwsysProcess_GetExitValue(gp);
  4093. } break;
  4094. case kwsysProcess_State_Error:
  4095. {
  4096. std::cerr << "Error: Could not run " << args[0] << ":\n";
  4097. std::cerr << kwsysProcess_GetErrorString(gp) << "\n";
  4098. } break;
  4099. case kwsysProcess_State_Exception:
  4100. {
  4101. std::cerr << "Error: " << args[0]
  4102. << " terminated with an exception: "
  4103. << kwsysProcess_GetExceptionString(gp) << "\n";
  4104. } break;
  4105. case kwsysProcess_State_Starting:
  4106. case kwsysProcess_State_Executing:
  4107. case kwsysProcess_State_Expired:
  4108. case kwsysProcess_State_Killed:
  4109. {
  4110. // Should not get here.
  4111. std::cerr << "Unexpected ending state after running " << args[0]
  4112. << std::endl;
  4113. } break;
  4114. }
  4115. kwsysProcess_Delete(gp);
  4116. if(result)
  4117. {
  4118. std::cerr << "Error " << args[0] << " returned :" << result << "\n";
  4119. }
  4120. return buffer;
  4121. }
  4122. std::string SystemInformationImplementation::ParseValueFromKStat(const char* arguments)
  4123. {
  4124. std::vector<const char*> args;
  4125. args.clear();
  4126. args.push_back("kstat");
  4127. args.push_back("-p");
  4128. std::string command = arguments;
  4129. size_t start = command.npos;
  4130. size_t pos = command.find(' ',0);
  4131. while(pos!=command.npos)
  4132. {
  4133. bool inQuotes = false;
  4134. // Check if we are between quotes
  4135. size_t b0 = command.find('"',0);
  4136. size_t b1 = command.find('"',b0+1);
  4137. while(b0 != command.npos && b1 != command.npos && b1>b0)
  4138. {
  4139. if(pos>b0 && pos<b1)
  4140. {
  4141. inQuotes = true;
  4142. break;
  4143. }
  4144. b0 = command.find('"',b1+1);
  4145. b1 = command.find('"',b0+1);
  4146. }
  4147. if(!inQuotes)
  4148. {
  4149. std::string arg = command.substr(start+1,pos-start-1);
  4150. // Remove the quotes if any
  4151. size_t quotes = arg.find('"');
  4152. while(quotes != arg.npos)
  4153. {
  4154. arg.erase(quotes,1);
  4155. quotes = arg.find('"');
  4156. }
  4157. args.push_back(arg.c_str());
  4158. start = pos;
  4159. }
  4160. pos = command.find(' ',pos+1);
  4161. }
  4162. std::string lastArg = command.substr(start+1,command.size()-start-1);
  4163. args.push_back(lastArg.c_str());
  4164. args.push_back(0);
  4165. std::string buffer = this->RunProcess(args);
  4166. std::string value = "";
  4167. for(size_t i=buffer.size()-1;i>0;i--)
  4168. {
  4169. if(buffer[i] == ' ' || buffer[i] == '\t')
  4170. {
  4171. break;
  4172. }
  4173. if(buffer[i] != '\n' && buffer[i] != '\r')
  4174. {
  4175. std::string val = value;
  4176. value = buffer[i];
  4177. value += val;
  4178. }
  4179. }
  4180. return value;
  4181. }
  4182. /** Querying for system information from Solaris */
  4183. bool SystemInformationImplementation::QuerySolarisMemory()
  4184. {
  4185. #if defined (__SVR4) && defined (__sun)
  4186. // Solaris allows querying this value by sysconf, but if this is
  4187. // a 32 bit process on a 64 bit host the returned memory will be
  4188. // limited to 4GiB. So if this is a 32 bit process or if the sysconf
  4189. // method fails use the kstat interface.
  4190. #if SIZEOF_VOID_P == 8
  4191. if (this->QueryMemoryBySysconf())
  4192. {
  4193. return true;
  4194. }
  4195. #endif
  4196. char* tail;
  4197. unsigned long totalMemory =
  4198. strtoul(this->ParseValueFromKStat("-s physmem").c_str(),&tail,0);
  4199. this->TotalPhysicalMemory = totalMemory/128;
  4200. return true;
  4201. #else
  4202. return false;
  4203. #endif
  4204. }
  4205. bool SystemInformationImplementation::QuerySolarisProcessor()
  4206. {
  4207. if (!this->QueryProcessorBySysconf())
  4208. {
  4209. return false;
  4210. }
  4211. // Parse values
  4212. this->CPUSpeedInMHz = static_cast<float>(atoi(this->ParseValueFromKStat("-s clock_MHz").c_str()));
  4213. // Chip family
  4214. this->ChipID.Family = 0;
  4215. // Chip Model
  4216. this->ChipID.ProcessorName = this->ParseValueFromKStat("-s cpu_type");
  4217. this->ChipID.Model = 0;
  4218. // Chip Vendor
  4219. if (this->ChipID.ProcessorName != "i386")
  4220. {
  4221. this->ChipID.Vendor = "Sun";
  4222. this->FindManufacturer();
  4223. }
  4224. return true;
  4225. }
  4226. /** Querying for system information from Haiku OS */
  4227. bool SystemInformationImplementation::QueryHaikuInfo()
  4228. {
  4229. #if defined(__HAIKU__)
  4230. // CPU count
  4231. system_info info;
  4232. get_system_info(&info);
  4233. this->NumberOfPhysicalCPU = info.cpu_count;
  4234. // CPU speed
  4235. uint32 topologyNodeCount = 0;
  4236. cpu_topology_node_info* topology = 0;
  4237. get_cpu_topology_info(0, &topologyNodeCount);
  4238. if (topologyNodeCount != 0)
  4239. topology = new cpu_topology_node_info[topologyNodeCount];
  4240. get_cpu_topology_info(topology, &topologyNodeCount);
  4241. for (uint32 i = 0; i < topologyNodeCount; i++) {
  4242. if (topology[i].type == B_TOPOLOGY_CORE) {
  4243. this->CPUSpeedInMHz = topology[i].data.core.default_frequency /
  4244. 1000000.0f;
  4245. break;
  4246. }
  4247. }
  4248. delete[] topology;
  4249. // Physical Memory
  4250. this->TotalPhysicalMemory = (info.max_pages * B_PAGE_SIZE) / (1024 * 1024) ;
  4251. this->AvailablePhysicalMemory = this->TotalPhysicalMemory -
  4252. ((info.used_pages * B_PAGE_SIZE) / (1024 * 1024));
  4253. // NOTE: get_system_info_etc is currently a private call so just set to 0
  4254. // until it becomes public
  4255. this->TotalVirtualMemory = 0;
  4256. this->AvailableVirtualMemory = 0;
  4257. // Retrieve cpuid_info union for cpu 0
  4258. cpuid_info cpu_info;
  4259. get_cpuid(&cpu_info, 0, 0);
  4260. // Chip Vendor
  4261. // Use a temporary buffer so that we can add NULL termination to the string
  4262. char vbuf[13];
  4263. strncpy(vbuf, cpu_info.eax_0.vendor_id, 12);
  4264. vbuf[12] = '\0';
  4265. this->ChipID.Vendor = vbuf;
  4266. this->FindManufacturer();
  4267. // Retrieve cpuid_info union for cpu 0 this time using a register value of 1
  4268. get_cpuid(&cpu_info, 1, 0);
  4269. this->NumberOfLogicalCPU = cpu_info.eax_1.logical_cpus;
  4270. // Chip type
  4271. this->ChipID.Type = cpu_info.eax_1.type;
  4272. // Chip family
  4273. this->ChipID.Family = cpu_info.eax_1.family;
  4274. // Chip Model
  4275. this->ChipID.Model = cpu_info.eax_1.model;
  4276. // Chip Revision
  4277. this->ChipID.Revision = cpu_info.eax_1.stepping;
  4278. // Chip Extended Family
  4279. this->ChipID.ExtendedFamily = cpu_info.eax_1.extended_family;
  4280. // Chip Extended Model
  4281. this->ChipID.ExtendedModel = cpu_info.eax_1.extended_model;
  4282. // Get ChipID.ProcessorName from other information already gathered
  4283. this->RetrieveClassicalCPUIdentity();
  4284. // Cache size
  4285. this->Features.L1CacheSize = 0;
  4286. this->Features.L2CacheSize = 0;
  4287. return true;
  4288. #else
  4289. return false;
  4290. #endif
  4291. }
  4292. bool SystemInformationImplementation::QueryQNXMemory()
  4293. {
  4294. #if defined(__QNX__)
  4295. std::string buffer;
  4296. std::vector<const char*> args;
  4297. args.clear();
  4298. args.push_back("showmem");
  4299. args.push_back("-S");
  4300. args.push_back(0);
  4301. buffer = this->RunProcess(args);
  4302. args.clear();
  4303. size_t pos = buffer.find("System RAM:");
  4304. if (pos == buffer.npos)
  4305. return false;
  4306. pos = buffer.find(":", pos);
  4307. size_t pos2 = buffer.find("M (", pos);
  4308. if (pos2 == buffer.npos)
  4309. return false;
  4310. pos++;
  4311. while (buffer[pos] == ' ')
  4312. pos++;
  4313. this->TotalPhysicalMemory = atoi(buffer.substr(pos, pos2 - pos).c_str());
  4314. return true;
  4315. #endif
  4316. return false;
  4317. }
  4318. bool SystemInformationImplementation::QueryBSDMemory()
  4319. {
  4320. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  4321. int ctrl[2] = { CTL_HW, HW_PHYSMEM };
  4322. #if defined(HW_PHYSMEM64)
  4323. int64_t k;
  4324. ctrl[1] = HW_PHYSMEM64;
  4325. #else
  4326. int k;
  4327. #endif
  4328. size_t sz = sizeof(k);
  4329. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4330. {
  4331. return false;
  4332. }
  4333. this->TotalPhysicalMemory = k>>10>>10;
  4334. return true;
  4335. #else
  4336. return false;
  4337. #endif
  4338. }
  4339. bool SystemInformationImplementation::QueryQNXProcessor()
  4340. {
  4341. #if defined(__QNX__)
  4342. // the output on my QNX 6.4.1 looks like this:
  4343. // Processor1: 686 Pentium II Stepping 3 2175MHz FPU
  4344. std::string buffer;
  4345. std::vector<const char*> args;
  4346. args.clear();
  4347. args.push_back("pidin");
  4348. args.push_back("info");
  4349. args.push_back(0);
  4350. buffer = this->RunProcess(args);
  4351. args.clear();
  4352. size_t pos = buffer.find("Processor1:");
  4353. if (pos == buffer.npos)
  4354. return false;
  4355. size_t pos2 = buffer.find("MHz", pos);
  4356. if (pos2 == buffer.npos)
  4357. return false;
  4358. size_t pos3 = pos2;
  4359. while (buffer[pos3] != ' ')
  4360. --pos3;
  4361. this->CPUSpeedInMHz = atoi(buffer.substr(pos3 + 1, pos2 - pos3 - 1).c_str());
  4362. pos2 = buffer.find(" Stepping", pos);
  4363. if (pos2 != buffer.npos)
  4364. {
  4365. pos2 = buffer.find(" ", pos2 + 1);
  4366. if (pos2 != buffer.npos && pos2 < pos3)
  4367. {
  4368. this->ChipID.Revision = atoi(buffer.substr(pos2 + 1, pos3 - pos2).c_str());
  4369. }
  4370. }
  4371. this->NumberOfPhysicalCPU = 0;
  4372. do
  4373. {
  4374. pos = buffer.find("\nProcessor", pos + 1);
  4375. ++this->NumberOfPhysicalCPU;
  4376. } while (pos != buffer.npos);
  4377. this->NumberOfLogicalCPU = 1;
  4378. return true;
  4379. #else
  4380. return false;
  4381. #endif
  4382. }
  4383. bool SystemInformationImplementation::QueryBSDProcessor()
  4384. {
  4385. #if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
  4386. int k;
  4387. size_t sz = sizeof(k);
  4388. int ctrl[2] = { CTL_HW, HW_NCPU };
  4389. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4390. {
  4391. return false;
  4392. }
  4393. this->NumberOfPhysicalCPU = k;
  4394. this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
  4395. #if defined(HW_CPUSPEED)
  4396. ctrl[1] = HW_CPUSPEED;
  4397. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4398. {
  4399. return false;
  4400. }
  4401. this->CPUSpeedInMHz = (float) k;
  4402. #endif
  4403. #if defined(CPU_SSE)
  4404. ctrl[0] = CTL_MACHDEP;
  4405. ctrl[1] = CPU_SSE;
  4406. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4407. {
  4408. return false;
  4409. }
  4410. this->Features.HasSSE = (k > 0);
  4411. #endif
  4412. #if defined(CPU_SSE2)
  4413. ctrl[0] = CTL_MACHDEP;
  4414. ctrl[1] = CPU_SSE2;
  4415. if (sysctl(ctrl, 2, &k, &sz, NULL, 0) != 0)
  4416. {
  4417. return false;
  4418. }
  4419. this->Features.HasSSE2 = (k > 0);
  4420. #endif
  4421. #if defined(CPU_CPUVENDOR)
  4422. ctrl[0] = CTL_MACHDEP;
  4423. ctrl[1] = CPU_CPUVENDOR;
  4424. char vbuf[25];
  4425. ::memset(vbuf, 0, sizeof(vbuf));
  4426. sz = sizeof(vbuf) - 1;
  4427. if (sysctl(ctrl, 2, vbuf, &sz, NULL, 0) != 0)
  4428. {
  4429. return false;
  4430. }
  4431. this->ChipID.Vendor = vbuf;
  4432. this->FindManufacturer();
  4433. #endif
  4434. return true;
  4435. #else
  4436. return false;
  4437. #endif
  4438. }
  4439. bool SystemInformationImplementation::QueryHPUXMemory()
  4440. {
  4441. #if defined(__hpux)
  4442. unsigned long tv=0;
  4443. unsigned long tp=0;
  4444. unsigned long av=0;
  4445. unsigned long ap=0;
  4446. struct pst_static pst;
  4447. struct pst_dynamic pdy;
  4448. unsigned long ps = 0;
  4449. if (pstat_getstatic(&pst, sizeof(pst), (size_t) 1, 0) == -1)
  4450. {
  4451. return false;
  4452. }
  4453. ps = pst.page_size;
  4454. tp = pst.physical_memory *ps;
  4455. tv = (pst.physical_memory + pst.pst_maxmem) * ps;
  4456. if (pstat_getdynamic(&pdy, sizeof(pdy), (size_t) 1, 0) == -1)
  4457. {
  4458. return false;
  4459. }
  4460. ap = tp - pdy.psd_rm * ps;
  4461. av = tv - pdy.psd_vm;
  4462. this->TotalVirtualMemory = tv>>10>>10;
  4463. this->TotalPhysicalMemory = tp>>10>>10;
  4464. this->AvailableVirtualMemory = av>>10>>10;
  4465. this->AvailablePhysicalMemory = ap>>10>>10;
  4466. return true;
  4467. #else
  4468. return false;
  4469. #endif
  4470. }
  4471. bool SystemInformationImplementation::QueryHPUXProcessor()
  4472. {
  4473. #if defined(__hpux)
  4474. # if defined(KWSYS_SYS_HAS_MPCTL_H)
  4475. int c = mpctl(MPC_GETNUMSPUS_SYS, 0, 0);
  4476. if (c <= 0)
  4477. {
  4478. return false;
  4479. }
  4480. this->NumberOfPhysicalCPU = c;
  4481. this->NumberOfLogicalCPU = this->NumberOfPhysicalCPU;
  4482. long t = sysconf(_SC_CPU_VERSION);
  4483. if (t == -1)
  4484. {
  4485. return false;
  4486. }
  4487. switch (t)
  4488. {
  4489. case CPU_PA_RISC1_0:
  4490. this->ChipID.Vendor = "Hewlett-Packard";
  4491. this->ChipID.Family = 0x100;
  4492. break;
  4493. case CPU_PA_RISC1_1:
  4494. this->ChipID.Vendor = "Hewlett-Packard";
  4495. this->ChipID.Family = 0x110;
  4496. break;
  4497. case CPU_PA_RISC2_0:
  4498. this->ChipID.Vendor = "Hewlett-Packard";
  4499. this->ChipID.Family = 0x200;
  4500. break;
  4501. # if defined(CPU_HP_INTEL_EM_1_0) || defined(CPU_IA64_ARCHREV_0)
  4502. # ifdef CPU_HP_INTEL_EM_1_0
  4503. case CPU_HP_INTEL_EM_1_0:
  4504. # endif
  4505. # ifdef CPU_IA64_ARCHREV_0
  4506. case CPU_IA64_ARCHREV_0:
  4507. # endif
  4508. this->ChipID.Vendor = "GenuineIntel";
  4509. this->Features.HasIA64 = true;
  4510. break;
  4511. # endif
  4512. default:
  4513. return false;
  4514. }
  4515. this->FindManufacturer();
  4516. return true;
  4517. # else
  4518. return false;
  4519. # endif
  4520. #else
  4521. return false;
  4522. #endif
  4523. }
  4524. /** Query the operating system information */
  4525. bool SystemInformationImplementation::QueryOSInformation()
  4526. {
  4527. #if defined(_WIN32)
  4528. this->OSName = "Windows";
  4529. OSVERSIONINFOEXW osvi;
  4530. BOOL bIsWindows64Bit;
  4531. BOOL bOsVersionInfoEx;
  4532. char operatingSystem[256];
  4533. // Try calling GetVersionEx using the OSVERSIONINFOEX structure.
  4534. ZeroMemory (&osvi, sizeof (OSVERSIONINFOEXW));
  4535. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOEXW);
  4536. #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  4537. # pragma warning (push)
  4538. # ifdef __INTEL_COMPILER
  4539. # pragma warning (disable:1478)
  4540. # else
  4541. # pragma warning (disable:4996)
  4542. # endif
  4543. #endif
  4544. bOsVersionInfoEx = GetVersionExW ((OSVERSIONINFOW*)&osvi);
  4545. if (!bOsVersionInfoEx)
  4546. {
  4547. osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFOW);
  4548. if (!GetVersionExW((OSVERSIONINFOW*)&osvi))
  4549. {
  4550. return false;
  4551. }
  4552. }
  4553. #ifdef KWSYS_WINDOWS_DEPRECATED_GetVersionEx
  4554. # pragma warning (pop)
  4555. #endif
  4556. switch (osvi.dwPlatformId)
  4557. {
  4558. case VER_PLATFORM_WIN32_NT:
  4559. // Test for the product.
  4560. if (osvi.dwMajorVersion <= 4)
  4561. {
  4562. this->OSRelease = "NT";
  4563. }
  4564. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
  4565. {
  4566. this->OSRelease = "2000";
  4567. }
  4568. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4569. {
  4570. this->OSRelease = "XP";
  4571. }
  4572. // XP Professional x64
  4573. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
  4574. {
  4575. this->OSRelease = "XP";
  4576. }
  4577. #ifdef VER_NT_WORKSTATION
  4578. // Test for product type.
  4579. if (bOsVersionInfoEx)
  4580. {
  4581. if (osvi.wProductType == VER_NT_WORKSTATION)
  4582. {
  4583. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
  4584. {
  4585. this->OSRelease = "Vista";
  4586. }
  4587. if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 1)
  4588. {
  4589. this->OSRelease = "7";
  4590. }
  4591. // VER_SUITE_PERSONAL may not be defined
  4592. #ifdef VER_SUITE_PERSONAL
  4593. else
  4594. {
  4595. if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
  4596. {
  4597. this->OSRelease += " Personal";
  4598. }
  4599. else
  4600. {
  4601. this->OSRelease += " Professional";
  4602. }
  4603. }
  4604. #endif
  4605. }
  4606. else if (osvi.wProductType == VER_NT_SERVER)
  4607. {
  4608. // Check for .NET Server instead of Windows XP.
  4609. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4610. {
  4611. this->OSRelease = ".NET";
  4612. }
  4613. // Continue with the type detection.
  4614. if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
  4615. {
  4616. this->OSRelease += " DataCenter Server";
  4617. }
  4618. else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
  4619. {
  4620. this->OSRelease += " Advanced Server";
  4621. }
  4622. else
  4623. {
  4624. this->OSRelease += " Server";
  4625. }
  4626. }
  4627. sprintf (operatingSystem, "%ls (Build %ld)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
  4628. this->OSVersion = operatingSystem;
  4629. }
  4630. else
  4631. #endif // VER_NT_WORKSTATION
  4632. {
  4633. HKEY hKey;
  4634. wchar_t szProductType[80];
  4635. DWORD dwBufLen;
  4636. // Query the registry to retrieve information.
  4637. RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions", 0, KEY_QUERY_VALUE, &hKey);
  4638. RegQueryValueExW(hKey, L"ProductType", NULL, NULL, (LPBYTE) szProductType, &dwBufLen);
  4639. RegCloseKey (hKey);
  4640. if (lstrcmpiW(L"WINNT", szProductType) == 0)
  4641. {
  4642. this->OSRelease += " Professional";
  4643. }
  4644. if (lstrcmpiW(L"LANMANNT", szProductType) == 0)
  4645. {
  4646. // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
  4647. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4648. {
  4649. this->OSRelease += " Standard Server";
  4650. }
  4651. else
  4652. {
  4653. this->OSRelease += " Server";
  4654. }
  4655. }
  4656. if (lstrcmpiW(L"SERVERNT", szProductType) == 0)
  4657. {
  4658. // Decide between Windows 2000 Advanced Server and Windows .NET Enterprise Server.
  4659. if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4660. {
  4661. this->OSRelease += " Enterprise Server";
  4662. }
  4663. else
  4664. {
  4665. this->OSRelease += " Advanced Server";
  4666. }
  4667. }
  4668. }
  4669. // Display version, service pack (if any), and build number.
  4670. if (osvi.dwMajorVersion <= 4)
  4671. {
  4672. // NB: NT 4.0 and earlier.
  4673. sprintf (operatingSystem, "version %ld.%ld %ls (Build %ld)",
  4674. osvi.dwMajorVersion,
  4675. osvi.dwMinorVersion,
  4676. osvi.szCSDVersion,
  4677. osvi.dwBuildNumber & 0xFFFF);
  4678. this->OSVersion = operatingSystem;
  4679. }
  4680. else if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1)
  4681. {
  4682. // Windows XP and .NET server.
  4683. typedef BOOL (CALLBACK* LPFNPROC) (HANDLE, BOOL *);
  4684. HINSTANCE hKernelDLL;
  4685. LPFNPROC DLLProc;
  4686. // Load the Kernel32 DLL.
  4687. hKernelDLL = LoadLibraryW(L"kernel32");
  4688. if (hKernelDLL != NULL) {
  4689. // Only XP and .NET Server support IsWOW64Process so... Load dynamically!
  4690. DLLProc = (LPFNPROC) GetProcAddress (hKernelDLL, "IsWow64Process");
  4691. // If the function address is valid, call the function.
  4692. if (DLLProc != NULL) (DLLProc) (GetCurrentProcess (), &bIsWindows64Bit);
  4693. else bIsWindows64Bit = false;
  4694. // Free the DLL module.
  4695. FreeLibrary (hKernelDLL);
  4696. }
  4697. }
  4698. else
  4699. {
  4700. // Windows 2000 and everything else.
  4701. sprintf (operatingSystem,"%ls (Build %ld)", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
  4702. this->OSVersion = operatingSystem;
  4703. }
  4704. break;
  4705. case VER_PLATFORM_WIN32_WINDOWS:
  4706. // Test for the product.
  4707. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
  4708. {
  4709. this->OSRelease = "95";
  4710. if(osvi.szCSDVersion[1] == 'C')
  4711. {
  4712. this->OSRelease += "OSR 2.5";
  4713. }
  4714. else if(osvi.szCSDVersion[1] == 'B')
  4715. {
  4716. this->OSRelease += "OSR 2";
  4717. }
  4718. }
  4719. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
  4720. {
  4721. this->OSRelease = "98";
  4722. if (osvi.szCSDVersion[1] == 'A' )
  4723. {
  4724. this->OSRelease += "SE";
  4725. }
  4726. }
  4727. if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
  4728. {
  4729. this->OSRelease = "Me";
  4730. }
  4731. break;
  4732. case VER_PLATFORM_WIN32s:
  4733. this->OSRelease = "Win32s";
  4734. break;
  4735. default:
  4736. this->OSRelease = "Unknown";
  4737. break;
  4738. }
  4739. // Get the hostname
  4740. WORD wVersionRequested;
  4741. WSADATA wsaData;
  4742. char name[255];
  4743. wVersionRequested = MAKEWORD(2,0);
  4744. if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
  4745. {
  4746. gethostname(name,sizeof(name));
  4747. WSACleanup( );
  4748. }
  4749. this->Hostname = name;
  4750. const char* arch = getenv("PROCESSOR_ARCHITECTURE");
  4751. if(arch)
  4752. {
  4753. this->OSPlatform = arch;
  4754. }
  4755. #else
  4756. struct utsname unameInfo;
  4757. int errorFlag = uname(&unameInfo);
  4758. if(errorFlag == 0)
  4759. {
  4760. this->OSName = unameInfo.sysname;
  4761. this->Hostname = unameInfo.nodename;
  4762. this->OSRelease = unameInfo.release;
  4763. this->OSVersion = unameInfo.version;
  4764. this->OSPlatform = unameInfo.machine;
  4765. }
  4766. #ifdef __APPLE__
  4767. this->OSName="Unknown Apple OS";
  4768. this->OSRelease="Unknown product version";
  4769. this->OSVersion="Unknown build version";
  4770. this->CallSwVers("-productName",this->OSName);
  4771. this->CallSwVers("-productVersion",this->OSRelease);
  4772. this->CallSwVers("-buildVersion",this->OSVersion);
  4773. #endif
  4774. #endif
  4775. return true;
  4776. }
  4777. int SystemInformationImplementation::CallSwVers(
  4778. const char *arg,
  4779. std::string &ver)
  4780. {
  4781. #ifdef __APPLE__
  4782. std::vector<const char*> args;
  4783. args.push_back("sw_vers");
  4784. args.push_back(arg);
  4785. args.push_back(0);
  4786. ver = this->RunProcess(args);
  4787. this->TrimNewline(ver);
  4788. #else
  4789. // avoid C4100
  4790. (void)arg;
  4791. (void)ver;
  4792. #endif
  4793. return 0;
  4794. }
  4795. void SystemInformationImplementation::TrimNewline(std::string& output)
  4796. {
  4797. // remove \r
  4798. std::string::size_type pos=0;
  4799. while((pos = output.find("\r", pos)) != std::string::npos)
  4800. {
  4801. output.erase(pos);
  4802. }
  4803. // remove \n
  4804. pos = 0;
  4805. while((pos = output.find("\n", pos)) != std::string::npos)
  4806. {
  4807. output.erase(pos);
  4808. }
  4809. }
  4810. /** Return true if the machine is 64 bits */
  4811. bool SystemInformationImplementation::Is64Bits()
  4812. {
  4813. return (sizeof(void*) == 8);
  4814. }
  4815. } // namespace @KWSYS_NAMESPACE@