Debian Codegraph @

Utilities/KWSys/SystemInformation.cxx

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