SystemInformation.cxx 151 KB

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