SystemInformation.cxx 149 KB

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