SystemInformation.cxx 146 KB

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