SystemInformation.cxx 150 KB

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