SystemInformation.cxx 147 KB

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