SystemInformation.cxx 145 KB
Newer Older
1 2 3
/*============================================================================
  KWSys - Kitware System Library
  Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
4

5 6
  Distributed under the OSI-approved BSD License (the "License");
  see accompanying file Copyright.txt for details.
7

8 9 10 11
  This software is distributed WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the License for more information.
============================================================================*/
12 13 14

#if defined(_WIN32)
# define NOMINMAX // use our min,max
15 16 17
# if !defined(_WIN32_WINNT) && !(defined(_MSC_VER) && _MSC_VER < 1300)
#  define _WIN32_WINNT 0x0501
# endif
Sebastien Barre's avatar
Sebastien Barre committed
18 19 20
# include <winsock.h> // WSADATA, include before sys/types.h
#endif

21 22 23 24
#if (defined(__GNUC__) || defined(__PGI)) && !defined(_GNU_SOURCE)
# define _GNU_SOURCE
#endif

25 26 27 28 29 30 31 32 33 34 35 36
// TODO:
// We need an alternative implementation for many functions in this file
// when USE_ASM_INSTRUCTIONS gets defined as 0.
//
// Consider using these on Win32/Win64 for some of them:
//
// IsProcessorFeaturePresent
// http://msdn.microsoft.com/en-us/library/ms724482(VS.85).aspx
//
// GetProcessMemoryInfo
// http://msdn.microsoft.com/en-us/library/ms683219(VS.85).aspx

37
#include "kwsysPrivate.h"
38 39 40
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/vector)
#include KWSYS_HEADER(ios/iosfwd)
41 42 43
#include KWSYS_HEADER(SystemInformation.hxx)
#include KWSYS_HEADER(Process.h)
#include KWSYS_HEADER(ios/iostream)
44
#include KWSYS_HEADER(ios/sstream)
45
#include KWSYS_HEADER(ios/fstream)
46

47 48 49 50 51 52 53 54 55 56 57
// Work-around CMake dependency scanning limitation.  This must
// duplicate the above list of headers.
#if 0
# include "SystemInformation.hxx.in"
# include "Process.h.in"
# include "Configure.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_stl_vector.in"
# include "kwsys_stl_iosfwd.in"
# include "kwsys_ios_sstream.h.in"
# include "kwsys_ios_iostream.h.in"
58
# include "kwsys_ios_fstream.h.in"
59 60
#endif

61
#if defined(_WIN32)
62
# include <windows.h>
63
# include <errno.h>
64 65 66
# if defined(KWSYS_SYS_HAS_PSAPI)
#  include <psapi.h>
# endif
67
# if !defined(siginfo_t)
68
typedef int siginfo_t;
69 70 71 72 73
# endif
#else
# include <sys/types.h>
# include <sys/time.h>
# include <sys/utsname.h> // int uname(struct utsname *buf);
74
# include <sys/resource.h> // getrlimit
75 76 77 78
# include <unistd.h>
# include <signal.h>
# include <fcntl.h>
# include <errno.h> // extern int errno;
79 80
#endif

81 82 83 84 85 86 87 88 89 90
#ifdef __FreeBSD__
# include <sys/sysctl.h>
# include <fenv.h>
# include <sys/socket.h>
# include <netdb.h>
# include <netinet/in.h>
# if defined(KWSYS_SYS_HAS_IFADDRS_H)
#  include <ifaddrs.h>
#  define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
# endif
91 92 93 94 95 96 97 98 99
# if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
#  include <execinfo.h>
#  if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
#    include <cxxabi.h>
#  endif
#  if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
#    include <dlfcn.h>
#  endif
# endif
100 101
#endif

102 103 104 105 106
#if defined(__OpenBSD__) || defined(__NetBSD__)
# include <sys/param.h>
# include <sys/sysctl.h>
#endif

107 108 109 110
#if defined(KWSYS_SYS_HAS_MACHINE_CPU_H)
# include <machine/cpu.h>
#endif

111 112 113 114
#if defined(__DragonFly__)
# include <sys/sysctl.h>
#endif

115
#ifdef __APPLE__
116 117 118 119 120 121 122 123 124
# include <sys/sysctl.h>
# include <mach/vm_statistics.h>
# include <mach/host_info.h>
# include <mach/mach.h>
# include <mach/mach_types.h>
# include <fenv.h>
# include <sys/socket.h>
# include <netdb.h>
# include <netinet/in.h>
125 126 127 128
# if defined(KWSYS_SYS_HAS_IFADDRS_H)
#  include <ifaddrs.h>
#  define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
# endif
129
# if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__-0 >= 1050
130 131 132 133 134 135 136 137 138
#  if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
#   include <execinfo.h>
#   if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
#     include <cxxabi.h>
#   endif
#   if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
#     include <dlfcn.h>
#   endif
#  endif
139
# endif
140 141
#endif

142
#ifdef __linux
143 144 145 146
# include <fenv.h>
# include <sys/socket.h>
# include <netdb.h>
# include <netinet/in.h>
147 148 149 150 151 152
# if defined(KWSYS_SYS_HAS_IFADDRS_H)
#  include <ifaddrs.h>
#  if !defined(__LSB_VERSION__) /* LSB has no getifaddrs */
#   define KWSYS_SYSTEMINFORMATION_IMPLEMENT_FQDN
#  endif
# endif
153
# if defined(KWSYS_SYSTEMINFORMATION_HAS_BACKTRACE)
154
#  include <execinfo.h>
155 156 157 158 159
#  if defined(KWSYS_SYSTEMINFORMATION_HAS_CPP_DEMANGLE)
#    include <cxxabi.h>
#  endif
#  if defined(KWSYS_SYSTEMINFORMATION_HAS_SYMBOL_LOOKUP)
#    include <dlfcn.h>
160
#  endif
161
# endif
162 163 164 165 166 167 168
# if defined(KWSYS_CXX_HAS_RLIMIT64)
typedef struct rlimit64 ResourceLimitType;
#  define GetResourceLimit getrlimit64
# else
typedef struct rlimit ResourceLimitType;
#  define GetResourceLimit getrlimit
# endif
169
#elif defined( __hpux )
170 171
# include <sys/param.h>
# include <sys/pstat.h>
172 173 174
# if defined(KWSYS_SYS_HAS_MPCTL_H)
#  include <sys/mpctl.h>
# endif
175 176
#endif

177
#ifdef __HAIKU__
178
# include <OS.h>
179 180
#endif

181 182 183 184
#include <memory.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
185
#include <ctype.h> // int isdigit(int c);
186

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
#if defined(KWSYS_USE_LONG_LONG)
# if defined(KWSYS_IOS_HAS_OSTREAM_LONG_LONG)
#  define iostreamLongLong(x) (x)
# else
#  define iostreamLongLong(x) ((long)x)
# endif
#elif defined(KWSYS_USE___INT64)
# if defined(KWSYS_IOS_HAS_OSTREAM___INT64)
#  define iostreamLongLong(x) (x)
# else
#  define iostreamLongLong(x) ((long)x)
# endif
#else
# error "No Long Long"
#endif

#if defined(KWSYS_CXX_HAS_ATOLL)
# define atoLongLong atoll
#else
# if defined(KWSYS_CXX_HAS__ATOI64)
#  define atoLongLong _atoi64
# elif defined(KWSYS_CXX_HAS_ATOL)
#  define atoLongLong atol
# else
#  define atoLongLong atoi
# endif
#endif

215 216 217 218 219 220
#if defined(_MSC_VER) && (_MSC_VER >= 1300) && !defined(_WIN64)
#define USE_ASM_INSTRUCTIONS 1
#else
#define USE_ASM_INSTRUCTIONS 0
#endif

221 222 223 224 225 226 227
#if defined(_MSC_VER) && (_MSC_VER >= 1400)
#include <intrin.h>
#define USE_CPUID_INTRINSICS 1
#else
#define USE_CPUID_INTRINSICS 0
#endif

228
#if USE_ASM_INSTRUCTIONS || USE_CPUID_INTRINSICS || defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
229 230 231 232 233 234
# define USE_CPUID 1
#else
# define USE_CPUID 0
#endif

#if USE_CPUID
235 236 237 238 239 240 241 242 243 244

#define CPUID_AWARE_COMPILER

/**
 * call CPUID instruction
 *
 * Will return false if the instruction failed.
 */
static bool call_cpuid(int select, int result[4])
{
245 246 247 248
#if USE_CPUID_INTRINSICS
  __cpuid(result, select);
  return true;
#else
249
  int tmp[4];
250
#if defined(_MSC_VER)
251 252 253 254 255
  // Use SEH to determine CPUID presence
  __try {
    _asm {
#ifdef CPUID_AWARE_COMPILER
      ; we must push/pop the registers <<CPUID>> writes to, as the
256
      ; optimiser does not know about <<CPUID>>, and so does not expect
257 258 259 260 261 262 263 264
      ; these registers to change.
      push eax
      push ebx
      push ecx
      push edx
#endif
      ; <<CPUID>>
      mov eax, select
265 266 267 268 269 270
#ifdef CPUID_AWARE_COMPILER
      cpuid
#else
      _asm _emit 0x0f
      _asm _emit 0xa2
#endif
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
      mov tmp[0 * TYPE int], eax
      mov tmp[1 * TYPE int], ebx
      mov tmp[2 * TYPE int], ecx
      mov tmp[3 * TYPE int], edx

#ifdef CPUID_AWARE_COMPILER
      pop edx
      pop ecx
      pop ebx
      pop eax
#endif
      }
    }
  __except(1)
    {
    return false;
    }

289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
    memcpy(result, tmp, sizeof(tmp));
#elif defined(KWSYS_CXX_HAS_BORLAND_ASM_CPUID)
  unsigned int a, b, c, d;
  __asm {
    mov EAX, select;
    cpuid
    mov a, EAX;
    mov b, EBX;
    mov c, ECX;
    mov d, EDX;
  }

  result[0] = a;
  result[1] = b;
  result[2] = c;
  result[3] = d;
#endif

307 308
  // The cpuid instruction succeeded.
  return true;
309
#endif
310 311 312 313
}
#endif


314 315
namespace KWSYS_NAMESPACE
{
316 317
template<typename T>
T min(T a, T b){ return a<b ? a : b; }
318

319 320
extern "C" { typedef void (*SigAction)(int,siginfo_t*,void*); }

321 322 323
//  Define SystemInformationImplementation class
typedef  void (*DELAY_FUNC)(unsigned int uiMS);

324 325
class SystemInformationImplementation
{
326
public:
327
  typedef SystemInformation::LongLong LongLong;
328 329 330 331 332 333 334 335
  SystemInformationImplementation ();
  ~SystemInformationImplementation ();

  const char * GetVendorString();
  const char * GetVendorID();
  kwsys_stl::string GetTypeID();
  kwsys_stl::string GetFamilyID();
  kwsys_stl::string GetModelID();
336
  kwsys_stl::string GetModelName();
337 338 339 340
  kwsys_stl::string GetSteppingCode();
  const char * GetExtendedProcessorName();
  const char * GetProcessorSerialNumber();
  int GetProcessorCacheSize();
341
  unsigned int GetLogicalProcessorsPerPhysical();
342 343 344 345
  float GetProcessorClockFrequency();
  int GetProcessorAPICID();
  int GetProcessorCacheXSize(long int);
  bool DoesCPUSupportFeature(long int);
346

347 348
  const char * GetOSName();
  const char * GetHostname();
349
  int GetFullyQualifiedDomainName(kwsys_stl::string &fqdn);
350 351 352 353 354 355 356 357 358 359 360 361
  const char * GetOSRelease();
  const char * GetOSVersion();
  const char * GetOSPlatform();

  bool Is64Bits();

  unsigned int GetNumberOfLogicalCPU(); // per physical cpu
  unsigned int GetNumberOfPhysicalCPU();

  bool DoesCPUSupportCPUID();

  // Retrieve memory information in megabyte.
362 363 364
  size_t GetTotalVirtualMemory();
  size_t GetAvailableVirtualMemory();
  size_t GetTotalPhysicalMemory();
365 366
  size_t GetAvailablePhysicalMemory();

367
  LongLong GetProcessId();
368 369

  // Retrieve memory information in kib
370 371 372 373 374 375 376 377
  LongLong GetHostMemoryTotal();
  LongLong GetHostMemoryAvailable(const char *envVarName);
  LongLong GetHostMemoryUsed();

  LongLong GetProcMemoryAvailable(
        const char *hostLimitEnvVarName,
        const char *procLimitEnvVarName);
  LongLong GetProcMemoryUsed();
378 379 380 381

  // enable/disable stack trace signal handler.
  static
  void SetStackTraceOnError(int enable);
382

383 384 385 386
  // get current stack
  static
  kwsys_stl::string GetProgramStack(int firstFrame, int wholePath);

387 388 389 390
  /** Run the different checks */
  void RunCPUCheck();
  void RunOSCheck();
  void RunMemoryCheck();
391

392
public:
393
  typedef struct tagID
394 395 396 397 398 399 400
    {
    int Type;
    int Family;
    int Model;
    int Revision;
    int ExtendedFamily;
    int ExtendedModel;
401 402 403
    kwsys_stl::string ProcessorName;
    kwsys_stl::string Vendor;
    kwsys_stl::string SerialNumber;
404
    kwsys_stl::string ModelName;
405 406
    } ID;

407
  typedef struct tagCPUPowerManagement
408 409 410 411 412 413
    {
    bool HasVoltageID;
    bool HasFrequencyID;
    bool HasTempSenseDiode;
    } CPUPowerManagement;

414
  typedef struct tagCPUExtendedFeatures
415 416 417 418 419 420 421
    {
    bool Has3DNow;
    bool Has3DNowPlus;
    bool SupportsMP;
    bool HasMMXPlus;
    bool HasSSEMMX;
    bool SupportsHyperthreading;
422
    unsigned int LogicalProcessorsPerPhysical;
423 424
    int APIC_ID;
    CPUPowerManagement PowerManagement;
425 426 427
    } CPUExtendedFeatures;

  typedef struct CPUtagFeatures
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
    {
    bool HasFPU;
    bool HasTSC;
    bool HasMMX;
    bool HasSSE;
    bool HasSSEFP;
    bool HasSSE2;
    bool HasIA64;
    bool HasAPIC;
    bool HasCMOV;
    bool HasMTRR;
    bool HasACPI;
    bool HasSerial;
    bool HasThermal;
    int CPUSpeed;
    int L1CacheSize;
    int L2CacheSize;
    int L3CacheSize;
    CPUExtendedFeatures ExtendedFeatures;
    } CPUFeatures;
448 449

  enum Manufacturer
450
    {
451
    AMD, Intel, NSC, UMC, Cyrix, NexGen, IDT, Rise, Transmeta, Sun, IBM,
452
    Motorola, HP, UnknownManufacturer
453 454
    };

455
protected:
456 457 458 459 460 461 462 463 464 465 466 467 468
  // Functions.
  bool RetrieveCPUFeatures();
  bool RetrieveCPUIdentity();
  bool RetrieveCPUCacheDetails();
  bool RetrieveClassicalCPUCacheDetails();
  bool RetrieveCPUClockSpeed();
  bool RetrieveClassicalCPUClockSpeed();
  bool RetrieveCPUExtendedLevelSupport(int);
  bool RetrieveExtendedCPUFeatures();
  bool RetrieveProcessorSerialNumber();
  bool RetrieveCPUPowerManagement();
  bool RetrieveClassicalCPUIdentity();
  bool RetrieveExtendedCPUIdentity();
469

470 471 472 473 474 475 476 477 478 479
  Manufacturer  ChipManufacturer;
  CPUFeatures   Features;
  ID            ChipID;
  float         CPUSpeedInMHz;
  unsigned int  NumberOfLogicalCPU;
  unsigned int  NumberOfPhysicalCPU;

  int CPUCount();
  unsigned char LogicalCPUPerPhysicalCPU();
  unsigned char GetAPICId();
480
  bool IsHyperThreadingSupported();
481
  static LongLong GetCyclesDifference(DELAY_FUNC, unsigned int);
482

483
  // For Linux and Cygwin, /proc/cpuinfo formats are slightly different
484
  bool RetreiveInformationFromCpuInfoFile();
485
  kwsys_stl::string ExtractValueFromCpuInfoFile(kwsys_stl::string buffer,
Bill Hoffman's avatar
Bill Hoffman committed
486
                                          const char* word, size_t init=0);
487

488
  bool QueryLinuxMemory();
489
  bool QueryCygwinMemory();
490

491 492 493
  static void Delay (unsigned int);
  static void DelayOverhead (unsigned int);

494
  void FindManufacturer(const kwsys_stl::string &family = "");
495 496 497

  // For Mac
  bool ParseSysCtl();
498
  int CallSwVers(const char *arg, kwsys_stl::string &ver);
499
  void TrimNewline(kwsys_stl::string&);
500 501 502 503
  kwsys_stl::string ExtractValueFromSysCtl(const char* word);
  kwsys_stl::string SysCtlBuffer;

  // For Solaris
504 505
  bool QuerySolarisMemory();
  bool QuerySolarisProcessor();
506 507 508
  kwsys_stl::string ParseValueFromKStat(const char* arguments);
  kwsys_stl::string RunProcess(kwsys_stl::vector<const char*> args);

509 510 511
  //For Haiku OS
  bool QueryHaikuInfo();

512 513 514 515
  //For QNX
  bool QueryQNXMemory();
  bool QueryQNXProcessor();

516 517 518 519
  //For OpenBSD, FreeBSD, NetBSD, DragonFly
  bool QueryBSDMemory();
  bool QueryBSDProcessor();

520
  //For HP-UX
521
  bool QueryHPUXMemory();
522 523
  bool QueryHPUXProcessor();

524 525 526
  //For Microsoft Windows
  bool QueryWindowsMemory();

527 528 529
  //For AIX
  bool QueryAIXMemory();

530
  bool QueryProcessorBySysconf();
531 532
  bool QueryProcessor();

533
  // Evaluate the memory information.
534
  bool QueryMemoryBySysconf();
535
  bool QueryMemory();
536 537 538 539
  size_t TotalVirtualMemory;
  size_t AvailableVirtualMemory;
  size_t TotalPhysicalMemory;
  size_t AvailablePhysicalMemory;
540

Bill Hoffman's avatar
Bill Hoffman committed
541
  size_t CurrentPositionInFile;
542 543 544 545 546 547 548

  // Operating System information
  bool QueryOSInformation();
  kwsys_stl::string OSName;
  kwsys_stl::string Hostname;
  kwsys_stl::string OSRelease;
  kwsys_stl::string OSVersion;
549
  kwsys_stl::string OSPlatform;
550
};
551

552

553
SystemInformation::SystemInformation()
554 555 556 557
{
  this->Implementation = new SystemInformationImplementation;
}

558
SystemInformation::~SystemInformation()
559 560 561 562 563 564 565 566
{
  delete this->Implementation;
}

const char * SystemInformation::GetVendorString()
{
  return this->Implementation->GetVendorString();
}
567

568 569 570 571
const char * SystemInformation::GetVendorID()
{
  return this->Implementation->GetVendorID();
}
572

573 574 575 576
kwsys_stl::string SystemInformation::GetTypeID()
{
  return this->Implementation->GetTypeID();
}
577

578 579 580 581
kwsys_stl::string SystemInformation::GetFamilyID()
{
  return this->Implementation->GetFamilyID();
}
582

583 584 585 586
kwsys_stl::string SystemInformation::GetModelID()
{
  return this->Implementation->GetModelID();
}
587

588 589 590 591 592
kwsys_stl::string SystemInformation::GetModelName()
{
  return this->Implementation->GetModelName();
}

593 594 595 596
kwsys_stl::string SystemInformation::GetSteppingCode()
{
  return this->Implementation->GetSteppingCode();
}
597

598 599 600 601
const char * SystemInformation::GetExtendedProcessorName()
{
  return this->Implementation->GetExtendedProcessorName();
}
602

603 604 605 606
const char * SystemInformation::GetProcessorSerialNumber()
{
  return this->Implementation->GetProcessorSerialNumber();
}
607

608 609 610 611
int SystemInformation::GetProcessorCacheSize()
{
  return this->Implementation->GetProcessorCacheSize();
}
612

613
unsigned int SystemInformation::GetLogicalProcessorsPerPhysical()
614 615 616
{
  return this->Implementation->GetLogicalProcessorsPerPhysical();
}
617

618 619 620 621
float SystemInformation::GetProcessorClockFrequency()
{
  return this->Implementation->GetProcessorClockFrequency();
}
622

623 624 625 626
int SystemInformation::GetProcessorAPICID()
{
  return this->Implementation->GetProcessorAPICID();
}
627

628 629 630 631
int SystemInformation::GetProcessorCacheXSize(long int l)
{
  return this->Implementation->GetProcessorCacheXSize(l);
}
632

633 634 635 636 637
bool SystemInformation::DoesCPUSupportFeature(long int i)
{
  return this->Implementation->DoesCPUSupportFeature(i);
}

638 639
kwsys_stl::string SystemInformation::GetCPUDescription()
{
640
  kwsys_ios::ostringstream oss;
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
  oss
    << this->GetNumberOfPhysicalCPU()
    << " core ";
  if (this->GetModelName().empty())
    {
    oss
      << this->GetProcessorClockFrequency()
      << " MHz "
      << this->GetVendorString()
      << " "
      << this->GetExtendedProcessorName();
    }
  else
    {
    oss << this->GetModelName();
    }

  // remove extra spaces
  kwsys_stl::string tmp=oss.str();
  size_t pos;
  while( (pos=tmp.find("  "))!=kwsys_stl::string::npos)
    {
    tmp.replace(pos,2," ");
    }

  return tmp;
}

669 670 671 672
const char * SystemInformation::GetOSName()
{
  return this->Implementation->GetOSName();
}
673

674 675 676 677
const char * SystemInformation::GetHostname()
{
  return this->Implementation->GetHostname();
}
678

679 680 681
kwsys_stl::string SystemInformation::GetFullyQualifiedDomainName()
{
  kwsys_stl::string fqdn;
682
  this->Implementation->GetFullyQualifiedDomainName(fqdn);
683 684 685
  return fqdn;
}

686 687 688 689
const char * SystemInformation::GetOSRelease()
{
  return this->Implementation->GetOSRelease();
}
690

691 692 693 694
const char * SystemInformation::GetOSVersion()
{
  return this->Implementation->GetOSVersion();
}
695

696 697 698 699 700
const char * SystemInformation::GetOSPlatform()
{
  return this->Implementation->GetOSPlatform();
}

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
int SystemInformation::GetOSIsWindows()
{
#if defined(_WIN32)
  return 1;
#else
  return 0;
#endif
}

int SystemInformation::GetOSIsLinux()
{
#if defined(__linux)
  return 1;
#else
  return 0;
#endif
}

int SystemInformation::GetOSIsApple()
{
#if defined(__APPLE__)
  return 1;
#else
  return 0;
#endif
}

kwsys_stl::string SystemInformation::GetOSDescription()
{
730
  kwsys_ios::ostringstream oss;
731 732 733 734 735 736 737 738 739 740
  oss
    << this->GetOSName()
    << " "
    << this->GetOSRelease()
    << " "
    << this->GetOSVersion();

  return oss.str();
}

741 742 743 744 745 746 747 748 749
bool SystemInformation::Is64Bits()
{
  return this->Implementation->Is64Bits();
}

unsigned int SystemInformation::GetNumberOfLogicalCPU() // per physical cpu
{
  return this->Implementation->GetNumberOfLogicalCPU();
}
750

751 752 753 754 755 756 757 758 759 760 761
unsigned int SystemInformation::GetNumberOfPhysicalCPU()
{
  return this->Implementation->GetNumberOfPhysicalCPU();
}

bool SystemInformation::DoesCPUSupportCPUID()
{
  return this->Implementation->DoesCPUSupportCPUID();
}

// Retrieve memory information in megabyte.
762
size_t SystemInformation::GetTotalVirtualMemory()
763 764 765
{
  return this->Implementation->GetTotalVirtualMemory();
}
766

767
size_t SystemInformation::GetAvailableVirtualMemory()
768 769 770
{
  return this->Implementation->GetAvailableVirtualMemory();
}
771

772
size_t SystemInformation::GetTotalPhysicalMemory()
773 774 775 776
{
  return this->Implementation->GetTotalPhysicalMemory();
}

777
size_t SystemInformation::GetAvailablePhysicalMemory()
778 779 780 781
{
  return this->Implementation->GetAvailablePhysicalMemory();
}

782 783 784
kwsys_stl::string SystemInformation::GetMemoryDescription(
      const char *hostLimitEnvVarName,
      const char *procLimitEnvVarName)
785
{
786
  kwsys_ios::ostringstream oss;
787
  oss
788 789 790 791 792 793 794 795
    << "Host Total: "
    << iostreamLongLong(this->GetHostMemoryTotal())
    << " KiB, Host Available: "
    << iostreamLongLong(this->GetHostMemoryAvailable(hostLimitEnvVarName))
    << " KiB, Process Available: "
    << iostreamLongLong(
         this->GetProcMemoryAvailable(hostLimitEnvVarName,procLimitEnvVarName))
    << " KiB";
796 797 798
  return oss.str();
}

799 800
// host memory info in units of KiB.
SystemInformation::LongLong SystemInformation::GetHostMemoryTotal()
801
{
802
  return this->Implementation->GetHostMemoryTotal();
803 804
}

805 806
SystemInformation::LongLong
SystemInformation::GetHostMemoryAvailable(const char *hostLimitEnvVarName)
807
{
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
  return this->Implementation->GetHostMemoryAvailable(hostLimitEnvVarName);
}

SystemInformation::LongLong SystemInformation::GetHostMemoryUsed()
{
  return this->Implementation->GetHostMemoryUsed();
}

// process memory info in units of KiB.
SystemInformation::LongLong
SystemInformation::GetProcMemoryAvailable(
        const char *hostLimitEnvVarName,
        const char *procLimitEnvVarName)
{
  return this->Implementation->GetProcMemoryAvailable(
          hostLimitEnvVarName,
          procLimitEnvVarName);
}

SystemInformation::LongLong SystemInformation::GetProcMemoryUsed()
{
  return this->Implementation->GetProcMemoryUsed();
830 831
}

832
SystemInformation::LongLong SystemInformation::GetProcessId()
833 834 835 836 837 838 839 840 841
{
  return this->Implementation->GetProcessId();
}

void SystemInformation::SetStackTraceOnError(int enable)
{
  SystemInformationImplementation::SetStackTraceOnError(enable);
}

842 843 844 845 846
kwsys_stl::string SystemInformation::GetProgramStack(int firstFrame, int wholePath)
{
  return SystemInformationImplementation::GetProgramStack(firstFrame, wholePath);
}

847 848 849
/** Run the different checks */
void SystemInformation::RunCPUCheck()
{
850
  this->Implementation->RunCPUCheck();
851
}
852

853 854
void SystemInformation::RunOSCheck()
{
855
  this->Implementation->RunOSCheck();
856
}
857

858 859
void SystemInformation::RunMemoryCheck()
{
860
  this->Implementation->RunMemoryCheck();
861 862 863 864 865 866 867 868 869 870 871
}


// --------------------------------------------------------------
// SystemInformationImplementation starts here

#define STORE_TLBCACHE_INFO(x,y)  x = (x < y) ? y : x
#define TLBCACHE_INFO_UNITS      (15)
#define CLASSICAL_CPU_FREQ_LOOP    10000000
#define RDTSC_INSTRUCTION      _asm _emit 0x0f _asm _emit 0x31

872 873 874 875
#define MMX_FEATURE            0x00000001
#define MMX_PLUS_FEATURE       0x00000002
#define SSE_FEATURE            0x00000004
#define SSE2_FEATURE           0x00000008
876
#define AMD_3DNOW_FEATURE      0x00000010
877 878 879 880 881 882 883
#define AMD_3DNOW_PLUS_FEATURE 0x00000020
#define IA64_FEATURE           0x00000040
#define MP_CAPABLE             0x00000080
#define HYPERTHREAD_FEATURE    0x00000100
#define SERIALNUMBER_FEATURE   0x00000200
#define APIC_FEATURE           0x00000400
#define SSE_FP_FEATURE         0x00000800
884
#define SSE_MMX_FEATURE        0x00001000
885 886
#define CMOV_FEATURE           0x00002000
#define MTRR_FEATURE           0x00004000
887 888 889
#define L1CACHE_FEATURE        0x00008000
#define L2CACHE_FEATURE        0x00010000
#define L3CACHE_FEATURE        0x00020000
890 891 892 893 894
#define ACPI_FEATURE           0x00040000
#define THERMALMONITOR_FEATURE 0x00080000
#define TEMPSENSEDIODE_FEATURE 0x00100000
#define FREQUENCYID_FEATURE    0x00200000
#define VOLTAGEID_FREQUENCY    0x00400000
895 896 897 898 899 900 901 902 903

// Status Flag
#define HT_NOT_CAPABLE           0
#define HT_ENABLED               1
#define HT_DISABLED              2
#define HT_SUPPORTED_NOT_ENABLED 3
#define HT_CANNOT_DETECT         4

// EDX[28]  Bit 28 is set if HT is supported
904
#define HT_BIT             0x10000000
905 906 907

// EAX[11:8] Bit 8-11 contains family processor ID.
#define FAMILY_ID          0x0F00
908
#define PENTIUM4_ID        0x0F00
909
// EAX[23:20] Bit 20-23 contains extended family processor ID
910
#define EXT_FAMILY_ID      0x0F00000
911
// EBX[23:16] Bit 16-23 in ebx contains the number of logical
912 913
#define NUM_LOGICAL_BITS   0x00FF0000
// processors per physical processor when execute cpuid with
914
// eax set to 1
915 916
// EBX[31:24] Bits 24-31 (8 bits) return the 8-bit unique
#define INITIAL_APIC_ID_BITS  0xFF000000
917 918 919
// initial APIC ID for the processor this code is running on.
// Default value = 0xff if HT is not supported

920 921
// Hide implementation details in an anonymous namespace.
namespace {
922
// *****************************************************************************
923
#if defined(__linux) || defined(__APPLE__)
924
int LoadLines(
925
      FILE *file,
926 927 928 929 930 931
      kwsys_stl::vector<kwsys_stl::string> &lines)
{
  // Load each line in the given file into a the vector.
  int nRead=0;
  const int bufSize=1024;
  char buf[bufSize]={'\0'};
932 933 934 935 936 937 938 939 940 941 942
  while (!feof(file) && !ferror(file))
    {
    errno=0;
    if (fgets(buf,bufSize,file) == 0)
      {
      if (ferror(file) && (errno==EINTR))
        {
        clearerr(file);
        }
      continue;
      }
943 944 945 946 947 948
    char *pBuf=buf;
    while(*pBuf)
      {
      if (*pBuf=='\n') *pBuf='\0';
      pBuf+=1;
      }
949 950 951 952
    lines.push_back(buf);
    ++nRead;
    }
  if (ferror(file))
953 954 955
    {
    return 0;
    }
956 957 958
  return nRead;
}

959
# if defined(__linux)
960 961 962 963 964 965 966
// *****************************************************************************
int LoadLines(
      const char *fileName,
      kwsys_stl::vector<kwsys_stl::string> &lines)
{
  FILE *file=fopen(fileName,"r");
  if (file==0)
967
    {
968
    return 0;
969
    }
970 971
  int nRead=LoadLines(file,lines);
  fclose(file);
972 973
  return nRead;
}
974
# endif
975 976 977 978 979 980 981 982 983 984

// ****************************************************************************
template<typename T>
int NameValue(
      kwsys_stl::vector<kwsys_stl::string> &lines,
      kwsys_stl::string name, T &value)
{
  size_t nLines=lines.size();
  for (size_t i=0; i<nLines; ++i)
    {
985 986
    size_t at=lines[i].find(name);
    if (at==kwsys_stl::string::npos)
987
      {
988
      continue;
989
      }
990
    kwsys_ios::istringstream is(lines[i].substr(at+name.size()));
991 992
    is >> value;
    return 0;
993 994 995
    }
  return -1;
}
996
#endif
997

998
#if defined(__linux)
999 1000 1001 1002 1003 1004
// ****************************************************************************
template<typename T>
int GetFieldsFromFile(
      const char *fileName,
      const char **fieldNames,
      T *values)
1005 1006 1007 1008 1009 1010
{
  kwsys_stl::vector<kwsys_stl::string> fields;
  if (!LoadLines(fileName,fields))
    {
    return -1;
    }
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
  int i=0;
  while (fieldNames[i]!=NULL)
    {
    int ierr=NameValue(fields,fieldNames[i],values[i]);
    if (ierr)
      {
      return -(i+2);
      }
    i+=1;
    }
  return 0;
}

// ****************************************************************************
template<typename T>
1026 1027
int GetFieldFromFile(
      const char *fileName,
1028 1029 1030
      const char *fieldName,
      T &value)
{
1031
  const char *fieldNames[2]={fieldName,NULL};
1032
  T values[1]={T(0)};
1033
  int ierr=GetFieldsFromFile(fileName,fieldNames,values);
1034 1035
  if (ierr)
    {
1036 1037 1038 1039 1040
    return ierr;
    }
  value=values[0];
  return 0;
}
1041
#endif
1042 1043

// ****************************************************************************
1044
#if defined(__APPLE__)
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
template<typename T>
int GetFieldsFromCommand(
      const char *command,
      const char **fieldNames,
      T *values)
{
  FILE *file=popen(command,"r");
  if (file==0)
    {
    return -1;
    }
  kwsys_stl::vector<kwsys_stl::string> fields;
  int nl=LoadLines(file,fields);
  pclose(file);
  if (nl==0)
    {
    return -1;
    }
  int i=0;
  while (fieldNames[i]!=NULL)
    {
    int ierr=NameValue(fields,fieldNames[i],values[i]);
    if (ierr)
      {
      return -(i+2);
      }
    i+=1;
1072 1073 1074
    }
  return 0;
}
1075
#endif
1076

1077
// ****************************************************************************
1078
#if !defined(_WIN32) && !defined(__MINGW32__) && !defined(__CYGWIN__)
1079 1080 1081 1082 1083 1084
void StacktraceSignalHandler(
      int sigNo,
      siginfo_t *sigInfo,
      void * /*sigContext*/)
{
#if defined(__linux) || defined(__APPLE__)
1085 1086
  kwsys_ios::ostringstream oss;
  oss
1087
     << kwsys_ios::endl
1088 1089
     << "=========================================================" << kwsys_ios::endl
     << "Process id " << getpid() << " ";
1090 1091
  switch (sigNo)
    {
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    case SIGINT:
      oss << "Caught SIGINT";
      break;

    case SIGTERM:
      oss << "Caught SIGTERM";
      break;

    case SIGABRT:
      oss << "Caught SIGABRT";
      break;

1104
    case SIGFPE:
1105 1106 1107 1108 1109
      oss
        << "Caught SIGFPE at "
        << (sigInfo->si_addr==0?"0x":"")
        << sigInfo->si_addr
        <<  " ";
1110 1111
      switch (sigInfo->si_code)
        {
1112
# if defined(FPE_INTDIV)
1113
        case FPE_INTDIV:
1114
          oss << "integer division by zero";
1115
          break;
1116
# endif
1117

1118
# if defined(FPE_INTOVF)
1119
        case FPE_INTOVF:
1120
          oss << "integer overflow";
1121
          break;
1122
# endif
1123 1124

        case FPE_FLTDIV:
1125
          oss << "floating point divide by zero";
1126 1127 1128
          break;

        case FPE_FLTOVF:
1129
          oss << "floating point overflow";
1130 1131 1132
          break;

        case FPE_FLTUND:
1133
          oss << "floating point underflow";
1134 1135 1136
          break;

        case FPE_FLTRES:
1137
          oss << "floating point inexact result";
1138 1139 1140
          break;

        case FPE_FLTINV:
1141
          oss << "floating point invalid operation";
1142 1143
          break;

1144
#if defined(FPE_FLTSUB)
1145
        case FPE_FLTSUB:
1146
          oss << "floating point subscript out of range";
1147
          break;
1148
#endif
1149 1150

        default:
1151
          oss << "code " << sigInfo->si_code;
1152 1153 1154 1155 1156
          break;
        }
      break;

    case SIGSEGV:
1157 1158 1159 1160 1161
      oss
        << "Caught SIGSEGV at "
        << (sigInfo->si_addr==0?"0x":"")
        << sigInfo->si_addr
        <<  " ";
1162 1163 1164
      switch (sigInfo->si_code)
        {
        case SEGV_MAPERR:
1165
          oss << "address not mapped to object";
1166 1167 1168
          break;

        case SEGV_ACCERR:
1169
          oss << "invalid permission for mapped object";
1170 1171 1172
          break;

        default:
1173
          oss << "code " << sigInfo->si_code;
1174 1175 1176 1177 1178
          break;
        }
      break;

    case SIGBUS:
1179 1180 1181 1182 1183
      oss
        << "Caught SIGBUS at "
        << (sigInfo->si_addr==0?"0x":"")
        << sigInfo->si_addr
        <<  " ";
1184 1185 1186
      switch (sigInfo->si_code)
        {
        case BUS_ADRALN:
1187
          oss << "invalid address alignment";
1188 1189
          break;

1190
# if defined(BUS_ADRERR)
1191
        case BUS_ADRERR:
1192
          oss << "nonexistent physical address";
1193
          break;
1194
# endif
1195

1196
# if defined(BUS_OBJERR)
1197
        case BUS_OBJERR:
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
          oss << "object-specific hardware error";
          break;
# endif

# if defined(BUS_MCEERR_AR)
        case BUS_MCEERR_AR:
          oss << "Hardware memory error consumed on a machine check; action required.";
          break;
# endif

# if defined(BUS_MCEERR_AO)
        case BUS_MCEERR_AO:
          oss << "Hardware memory error detected in process but not consumed; action optional.";
1211
          break;
1212
# endif
1213 1214

        default:
1215
          oss << "code " << sigInfo->si_code;
1216 1217 1218 1219 1220
          break;
        }
      break;

    case SIGILL:
1221 1222 1223 1224 1225
      oss
        << "Caught SIGILL at "
        << (sigInfo->si_addr==0?"0x":"")
        << sigInfo->si_addr
        <<  " ";
1226 1227 1228
      switch (sigInfo->si_code)
        {
        case ILL_ILLOPC:
1229
          oss << "illegal opcode";
1230 1231
          break;

1232
# if defined(ILL_ILLOPN)
1233
        case ILL_ILLOPN:
1234
          oss << "illegal operand";
1235
          break;
1236
# endif
1237

1238
# if defined(ILL_ILLADR)
1239
        case ILL_ILLADR:
1240
          oss << "illegal addressing mode.";
1241
          break;
1242
# endif
1243 1244

        case ILL_ILLTRP:
1245
          oss << "illegal trap";
1246 1247

        case ILL_PRVOPC:
1248
          oss << "privileged opcode";
1249 1250
          break;

1251
# if defined(ILL_PRVREG)
1252
        case ILL_PRVREG:
1253
          oss << "privileged register";
1254
          break;
1255
# endif
1256

1257
# if defined(ILL_COPROC)
1258
        case ILL_COPROC:
1259
          oss << "co-processor error";
1260
          break;
1261
# endif
1262

1263
# if defined(ILL_BADSTK)
1264
        case ILL_BADSTK:
1265
          oss << "internal stack error";
1266
          break;
1267
# endif
1268 1269

        default:
1270
          oss << "code " << sigInfo->si_code;
1271 1272 1273 1274 1275
          break;
        }
      break;

    default:
1276
      oss << "Caught " << sigNo << " code " << sigInfo->si_code;
1277 1278
      break;
    }
1279
  oss
1280 1281 1282 1283
    << kwsys_ios::endl
    << "Program Stack:" << kwsys_ios::endl
    << SystemInformationImplementation::GetProgramStack(2,0)
    << "=========================================================" << kwsys_ios::endl;
1284
  kwsys_ios::cerr << oss.str() << kwsys_ios::endl;
1285 1286 1287 1288

  // restore the previously registered handlers
  // and abort
  SystemInformationImplementation::SetStackTraceOnError(0);
1289 1290 1291 1292 1293 1294 1295
  abort();
#else
  // avoid warning C4100
  (void)sigNo;
  (void)sigInfo;
#endif
}
1296
#endif