SystemInformation.cxx 149 KB

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