Anonymous avatar Anonymous committed e32690e

Add SimpleService and VMWareMetricLogger

Comments (0)

Files changed (50)

building/misc/SimpleService/SimpleService.c

+/*
+ * sc create "Simple Service" start= "delayed-auto" binPath= "D:\var\vcs\hg\draft\bwb\SimpleService\Debug\SimpleService.exe"
+ */
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <winsock2.h>
+#include <tchar.h>
+
+#pragma comment(lib, "advapi32.lib")
+
+#include "message.h"
+
+#define LOG_DEBUG       1
+#define LOG_INFO        2
+#define LOG_NOTICE      3
+#define LOG_WARNING     4
+#define LOG_ERR         5
+
+#define SVC_NAME        "Simple Service"
+
+static SERVICE_STATUS           gSvcStatus;
+static SERVICE_STATUS_HANDLE    gSvcStatusHandle;
+static HANDLE                   ghSvcStopEvent = NULL;
+static HANDLE                   hEventSource = NULL;
+
+VOID WINAPI SvcCtrlHandler(DWORD);
+VOID WINAPI SvcMain(DWORD, LPSTR *);
+VOID WINAPI ReportSvcStatus(DWORD, DWORD, DWORD);
+
+void log_message(int level, int error, int lasterror, char *format, ...)
+{
+    int n, len;
+    char buf[512];
+    const char *errarg[] = { buf };
+    const char *errsmall = "!!!-!!! log_message: buffer too small";
+    va_list ap;
+    WORD wType;
+    DWORD dwEventId;
+    SYSTEMTIME st;
+    TIME_ZONE_INFORMATION tzi;
+
+    GetTimeZoneInformation(&tzi);
+    GetLocalTime(&st);
+
+    len = _snprintf(buf, sizeof(buf), "[%04d-%02d-%02dT%02d:%02d:%02d.%03d%+03d00]",
+        st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds, -tzi.Bias / 60);
+    if (len < 0 || len >= sizeof(buf))
+        goto buffer_small;
+
+    if (error == 0 && lasterror == 0) {
+        n = _snprintf(buf + len, sizeof(buf) - len, "%s", " - ");
+        if (n < 0 || n >= (int) sizeof(buf) - len)
+            goto buffer_small;
+        len += n;
+    } else {
+        if (error != 0) {
+            n = _snprintf(buf + len, sizeof(buf) - len, " - [errno = %d, message = %s] - ", error, strerror(error));
+            if (n < 0 || n >= (int) sizeof(buf) - len)
+                goto buffer_small;
+            len += n;
+        }
+
+        if (lasterror != 0) {
+            n = _snprintf(buf + len, sizeof(buf) - len, " - [last error = %d, message = ", lasterror);
+            if (n < 0 || n >= (int) sizeof(buf) - len)
+                goto buffer_small;
+            len += n;
+            n = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, NULL, lasterror, 0, buf + len, sizeof(buf) - len, NULL);
+            if (n < 1 || n >= (int) sizeof(buf) - len)
+                goto buffer_small;
+            while(1) {
+                char c = buf[len + n - 1];
+                if (c == '\n' || c == '\r')
+                    n -= 1;
+                else
+                    break;
+                if (n < 1) break;
+            }
+            len += n;
+            n = _snprintf(buf + len, sizeof(buf) - len, "] - ");
+            if (n < 1 || n >= (int) sizeof(buf) - len)
+                goto buffer_small;
+            len += n;
+        }
+    }
+
+    va_start(ap, format);
+    n = vsnprintf(buf + len, sizeof(buf) - len, format, ap);
+    va_end(ap);
+
+    if (n == 0)
+        n = _snprintf(buf + len, sizeof(buf) - len, "%s", "[empty message]");
+
+    if (n < 0 || n >= (int) sizeof(buf) - len)
+        goto buffer_small;
+
+    len += n;
+
+report_event:
+    if (level <= LOG_INFO)
+        fprintf(stdout, "%s\n", errarg[0]);
+    else
+        fprintf(stderr, "%s\n", errarg[0]);
+
+    if (hEventSource == NULL)
+        return;
+
+    if (level <= LOG_INFO) {
+        wType = EVENTLOG_INFORMATION_TYPE;
+        dwEventId = MSG_ONE_FMT_INFO;
+    } else if (level <= LOG_WARNING) {
+        wType = EVENTLOG_WARNING_TYPE;
+        dwEventId = MSG_ONE_FMT_WARN;
+    } else {
+        wType = EVENTLOG_ERROR_TYPE;
+        dwEventId = MSG_ONE_FMT_ERR;
+    }
+
+    ReportEventA(hEventSource, wType, 0, dwEventId, NULL, 1, 0, errarg, NULL);
+    return;
+
+buffer_small:
+    do {
+        n = strlen(errsmall) + 1;
+        if (n >= sizeof(buf))
+            errarg[0] = errsmall;
+        else
+            memcpy(buf + (sizeof(buf) - n), errsmall, n);
+
+        goto report_event;
+    } while(0);
+}
+
+static void setup_event_source()
+{
+    HKEY key;
+    char msgfile[MAX_PATH];
+    DWORD dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
+
+    if (ERROR_SUCCESS != RegCreateKeyExA(HKEY_LOCAL_MACHINE,
+        "SYSTEM\\CurrentControlSet\\Services\\"
+        "EventLog\\Application\\"SVC_NAME,
+        0, NULL, REG_OPTION_NON_VOLATILE,
+        KEY_SET_VALUE, NULL, &key, NULL))
+    {
+        log_message(LOG_ERR, 0, GetLastError(), "RegCreateKeyExA failed");
+        return;
+    }
+
+    GetModuleFileNameA(NULL, msgfile, MAX_PATH);
+
+    RegSetValueExA(key, "EventMessageFile", 0, REG_EXPAND_SZ, (BYTE *)msgfile, strlen(msgfile) + 1);
+    RegSetValueExA(key, "TypesSupported",   0, REG_DWORD,    (BYTE *)&dwData, sizeof(dwData));
+
+    RegCloseKey(key);
+}
+
+VOID WINAPI SvcMain(DWORD dwArgc, LPSTR *lpszArgv)
+{
+    gSvcStatusHandle = RegisterServiceCtrlHandlerA(SVC_NAME, SvcCtrlHandler);
+    if (gSvcStatusHandle == NULL)
+        log_message(LOG_INFO, 0, GetLastError(), "RegisterServiceCtrlHandlerA failed");
+
+    gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
+    gSvcStatus.dwServiceSpecificExitCode = 0;
+
+    ReportSvcStatus(SERVICE_START_PENDING, NO_ERROR, 1000);
+
+    ghSvcStopEvent = CreateEvent(
+        NULL,    // default security attributes
+        TRUE,    // manual reset event
+        FALSE,   // not signaled
+        NULL);   // no name
+    if (ghSvcStopEvent == NULL)
+    {
+        log_message(LOG_INFO, 0, GetLastError(), "CreateEvent failed");
+        ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
+        return;
+    }
+
+    ReportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0);
+    log_message(LOG_INFO, 0, 0, "%s", SVC_NAME" stared");
+
+    while(1)
+    {
+        WaitForSingleObject(ghSvcStopEvent, INFINITE);
+        ReportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0);
+        log_message(LOG_INFO, 0, 0, "%s", SVC_NAME" stopped");
+        return;
+    }
+}
+
+VOID WINAPI SvcCtrlHandler(DWORD dwCtrl)
+{
+    switch(dwCtrl)
+    {
+    case SERVICE_CONTROL_STOP:
+        ReportSvcStatus(SERVICE_STOP_PENDING, NO_ERROR, 0);
+        SetEvent(ghSvcStopEvent);
+        ReportSvcStatus(gSvcStatus.dwCurrentState, NO_ERROR, 0);
+        break;
+
+    default:
+        break;
+    }
+}
+
+VOID WINAPI ReportSvcStatus(DWORD dwCurrentState,
+    DWORD dwWin32ExitCode,
+    DWORD dwWaitHint)
+{
+    static DWORD dwCheckPoint = 1;
+
+    gSvcStatus.dwCurrentState = dwCurrentState;
+    gSvcStatus.dwWin32ExitCode = dwWin32ExitCode;
+    gSvcStatus.dwWaitHint = dwWaitHint;
+
+    if (dwCurrentState == SERVICE_START_PENDING)
+        gSvcStatus.dwControlsAccepted = 0;
+    else
+        gSvcStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
+
+    if ((dwCurrentState == SERVICE_RUNNING) ||
+        (dwCurrentState == SERVICE_STOPPED))
+        gSvcStatus.dwCheckPoint = 0;
+    else
+        gSvcStatus.dwCheckPoint = dwCheckPoint++;
+
+    // Report the status of the service to the SCM.
+    SetServiceStatus(gSvcStatusHandle, &gSvcStatus);
+}
+
+int main(int argc, char *argv[])
+{
+    SERVICE_TABLE_ENTRYA DispatchTable[] =
+    {
+        { SVC_NAME, SvcMain },
+        { NULL, NULL }
+    };
+
+    hEventSource = RegisterEventSourceA(NULL, SVC_NAME);
+
+    setup_event_source();
+
+    /*
+    This call returns when the service has stopped.
+    The process should simply terminate when the call returns.
+    */
+    if (!StartServiceCtrlDispatcherA(DispatchTable))
+    {
+        log_message(LOG_ERR, 0, GetLastError(), "StartServiceCtrlDispatcherA failed");
+    }
+
+    DeregisterEventSource(hEventSource);
+
+    return 0;
+}

building/misc/SimpleService/SimpleService.rc

+#include <verrsrc.h>
+
+VS_VERSION_INFO VERSIONINFO
+ FILEVERSION 1,0,0,1
+ PRODUCTVERSION 1,0,0,1
+ FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
+#ifdef _DEBUG
+ FILEFLAGS VS_FF_DEBUG
+#else
+ FILEFLAGS 0x0L
+#endif
+ FILEOS VOS_NT_WINDOWS32
+ FILETYPE VFT_APP
+ FILESUBTYPE VFT2_UNKNOWN
+BEGIN
+    BLOCK "StringFileInfo"
+    BEGIN
+        BLOCK "040904b0"
+        BEGIN
+            VALUE "CompanyName", "Sweetheart"
+            VALUE "LegalCopyright", "Copyright (C) 2012"
+            VALUE "ProductName", "Simple Service"
+            VALUE "ProductVersion", "1.0.0.1"
+            VALUE "FileDescription", "Simple Service"
+            VALUE "FileVersion", "1.0.0.1"
+            VALUE "InternalName", "SimpleService.exe"
+            VALUE "OriginalFilename", "SimpleService.exe"
+        END
+    END
+    BLOCK "VarFileInfo"
+    BEGIN
+        VALUE "Translation", 0x409, 0x04b0
+    END
+END
+
+LANGUAGE 0x0,0x0
+1 11 "MSG0000.bin"

building/misc/SimpleService/SimpleService.sln

+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SimpleService", "SimpleService.vcxproj", "{E4D23C71-F61B-49C5-9A97-0D8704DF8036}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Win32 = Debug|Win32
+		Release|Win32 = Release|Win32
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{E4D23C71-F61B-49C5-9A97-0D8704DF8036}.Debug|Win32.ActiveCfg = Debug|Win32
+		{E4D23C71-F61B-49C5-9A97-0D8704DF8036}.Debug|Win32.Build.0 = Debug|Win32
+		{E4D23C71-F61B-49C5-9A97-0D8704DF8036}.Release|Win32.ActiveCfg = Release|Win32
+		{E4D23C71-F61B-49C5-9A97-0D8704DF8036}.Release|Win32.Build.0 = Release|Win32
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+EndGlobal

building/misc/SimpleService/SimpleService.vcxproj

+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <ItemGroup Label="ProjectConfigurations">
+    <ProjectConfiguration Include="Debug|Win32">
+      <Configuration>Debug</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+    <ProjectConfiguration Include="Release|Win32">
+      <Configuration>Release</Configuration>
+      <Platform>Win32</Platform>
+    </ProjectConfiguration>
+  </ItemGroup>
+  <PropertyGroup Label="Globals">
+    <ProjectGuid>{E4D23C71-F61B-49C5-9A97-0D8704DF8036}</ProjectGuid>
+    <Keyword>Win32Proj</Keyword>
+    <RootNamespace>SimpleService</RootNamespace>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>true</UseDebugLibraries>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
+    <ConfigurationType>Application</ConfigurationType>
+    <UseDebugLibraries>false</UseDebugLibraries>
+    <WholeProgramOptimization>true</WholeProgramOptimization>
+    <CharacterSet>Unicode</CharacterSet>
+  </PropertyGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
+  <ImportGroup Label="ExtensionSettings">
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
+  </ImportGroup>
+  <PropertyGroup Label="UserMacros" />
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <LinkIncremental>true</LinkIncremental>
+  </PropertyGroup>
+  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <LinkIncremental>false</LinkIncremental>
+  </PropertyGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
+    <ClCompile>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <WarningLevel>Level3</WarningLevel>
+      <Optimization>Disabled</Optimization>
+      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
+    <ClCompile>
+      <WarningLevel>Level3</WarningLevel>
+      <PrecompiledHeader>
+      </PrecompiledHeader>
+      <Optimization>MaxSpeed</Optimization>
+      <FunctionLevelLinking>true</FunctionLevelLinking>
+      <IntrinsicFunctions>true</IntrinsicFunctions>
+      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
+    </ClCompile>
+    <Link>
+      <SubSystem>Console</SubSystem>
+      <GenerateDebugInformation>true</GenerateDebugInformation>
+      <EnableCOMDATFolding>true</EnableCOMDATFolding>
+      <OptimizeReferences>true</OptimizeReferences>
+    </Link>
+  </ItemDefinitionGroup>
+  <ItemGroup>
+    <ClCompile Include="SimpleService.c" />
+  </ItemGroup>
+  <ItemGroup>
+    <ResourceCompile Include="SimpleService.rc" />
+  </ItemGroup>
+  <ItemGroup>
+    <CustomBuild Include="message.mc">
+      <FileType>Document</FileType>
+      <Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">mc %(FullPath)</Command>
+      <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename).rc;%(Filename).h;MSG0000.bin;%(Outputs)</Outputs>
+      <Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">mc %(FullPath)</Command>
+      <Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Filename).rc;%(Filename).h;MSG0000.bin;%(Outputs)</Outputs>
+    </CustomBuild>
+  </ItemGroup>
+  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+  <ImportGroup Label="ExtensionTargets">
+  </ImportGroup>
+</Project>

building/misc/SimpleService/message.mc

+LanguageNames=(Neutral=0x0000:MSG0000)
+
+MessageId=1
+SymbolicName=MSG_ONE_FMT_INFO
+Severity=Informational
+Language=Neutral
+%1
+.
+
+MessageId=2
+SymbolicName=MSG_ONE_FMT_WARN
+Severity=Warning
+Language=Neutral
+%1
+.
+
+MessageId=3
+SymbolicName=MSG_ONE_FMT_ERR
+Severity=Error
+Language=Neutral
+%1
+.

building/misc/VMWareMetricLogger/GuestSDK/include/vmGuestLib.h

+/* **********************************************************
+ * Copyright (c) 2003-2008 VMware, Inc.  All rights reserved. -- VMware Confidential
+ * **********************************************************/
+
+#ifndef _VM_GUEST_LIB_H_
+#define _VM_GUEST_LIB_H_
+
+
+#include "vm_basic_types.h"
+#include "vmSessionId.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*
+ * This is the VMware GuestLib, an API used for accessing various
+ * performance statistics pertaining to the VMware virtual environment
+ * from within a VMware Virtual Machine.
+ */
+
+
+/*
+ * Error codes returned by GuestLib functions.
+ *
+ * XXX These should be unified with Foundry's error codes.
+ */
+typedef enum {
+   VMGUESTLIB_ERROR_SUCCESS                = 0,  // No error
+   VMGUESTLIB_ERROR_OTHER,                       // Other error
+   VMGUESTLIB_ERROR_NOT_RUNNING_IN_VM,           // Not running in a VM
+   VMGUESTLIB_ERROR_NOT_ENABLED,                 // GuestLib not enabled on the host.
+   VMGUESTLIB_ERROR_NOT_AVAILABLE,               // This stat not available on this host.
+   VMGUESTLIB_ERROR_NO_INFO,                     // UpdateInfo() has never been called.
+   VMGUESTLIB_ERROR_MEMORY,                      // Not enough memory
+   VMGUESTLIB_ERROR_BUFFER_TOO_SMALL,            // Buffer too small
+   VMGUESTLIB_ERROR_INVALID_HANDLE,              // Handle is invalid
+   VMGUESTLIB_ERROR_INVALID_ARG,                 // One or more arguments were invalid
+   VMGUESTLIB_ERROR_UNSUPPORTED_VERSION          // The host doesn't support this request
+} VMGuestLibError;
+
+
+char const * VMGuestLib_GetErrorText(VMGuestLibError error); // IN
+
+/*
+ * GuestLib handle.
+ *
+ * This handle provides a context for accessing all GuestLib
+ * state. Use VMGuestLib_OpenHandle to get a handle for use with other
+ * GuestLib functions, and use VMGuestLib_CloseHandle to release a
+ * handle previously acquired with VMGuestLib_OpenHandle.
+ *
+ * All of the statistics and session state are maintained per GuestLib
+ * handle, so operating on one GuestLib handle will not affect the
+ * state of another handle.
+ */
+
+struct _VMGuestLibHandle;
+typedef struct _VMGuestLibHandle* VMGuestLibHandle;
+
+
+VMGuestLibError VMGuestLib_OpenHandle(VMGuestLibHandle *handle); // OUT
+VMGuestLibError VMGuestLib_CloseHandle(VMGuestLibHandle handle); // IN
+
+
+/*
+ * Update the info and session state for the given handle.
+ *
+ * Concurrency/thread safety: No locking is done internally around the
+ * access of a handle. If a calling program uses multiple threads then
+ * the caller must either ensure that each thread of execution is
+ * using a separate handle, or the caller must implement locking
+ * around calls to VMGuestLib_UpdateInfo() on a given handle to ensure
+ * that two threads do not update the handle concurrently.
+ *
+ * Because the state is maintained per handle and no two handles can
+ * be updated exactly simultaneously, the state of two handles may
+ * differ even if they are updated one immediately after the other.
+ *
+ * VMGuestLib_UpdateInfo() is a fairly heavyweight function; it should
+ * be viewed similar to a system call in terms of the computational
+ * cost and performance hit. For this reason, a user of the API who
+ * is concerned about performance will get best results by minimizing
+ * the number of calls to VMGuestLib_UpdateInfo().
+ */
+
+VMGuestLibError VMGuestLib_UpdateInfo(VMGuestLibHandle handle); // IN
+
+
+/*
+ * Session ID
+ * 
+ * This is used to detect changes in the "session" of a virtual
+ * machine. "Session" in this context refers to the particular running
+ * instance of this virtual machine on a given host. Moving a virtual
+ * machine to another host using VMotion will cause a change in
+ * session ID, as will suspending and resuming a virtual machine or
+ * reverting to a snapshot.
+ *
+ * Any of the events above (VMotion, suspend/resume, snapshot revert)
+ * are likely to render invalid any information previously retrieved
+ * through this API, so the intention of the session ID is to provide
+ * applications with a mechanism to detect those events and react
+ * accordingly, e.g. by refreshing and resetting any state that relies
+ * on validity of previously retrieved information.
+ *
+ * Use VMGuestLib_GetSessionId() to retrieve the ID for the current
+ * session after calling VMGuestLib_UpdateInfo(). After a VMotion or
+ * similar event, VMGuestLib_GetSessionId() will return a new value.
+ * See code example below for an example of how to use this.
+ *
+ * If VMGuestLib_UpdateInfo() has never been called,
+ * VMGUESTLIB_ERROR_NO_INFO is returned.
+ *
+ * The session ID should be considered opaque and cannot be compared
+ * in any meaningful way with the session IDs from any other virtual
+ * machine (e.g. to determine if two virtual machines are on the same
+ * host).
+ *
+ * Here is simple pseudo-code (with no error checking) showing a naive
+ * implementation of detecting stale information using the session ID.
+ *
+ * -----
+ *
+ * VMSessionId sid = 0;
+ * Bool done = FALSE;
+ *
+ * while (!done) {
+ *    VMSessionId tmp;
+ *
+ *    VMGuestLib_UpdateInfo();
+ *    VMGuestLib_GetSessionId(&tmp);
+ *    if (tmp != sid) {
+ *       ResetStats();
+ *       sid = tmp;
+ *    }
+ * }
+ *
+ * -----
+ */
+
+
+VMGuestLibError VMGuestLib_GetSessionId(VMGuestLibHandle handle,  // IN
+                                        VMSessionId *id);         // OUT
+
+
+/*
+ * Specific Stat accessors. The values returned by these accessor
+ * functions are up to date as of the last call to VMGuestLib_UpdateInfo().
+ *
+ * If VMGuestLib_UpdateInfo() has never been called,
+ * VMGUESTLIB_ERROR_NO_INFO is returned.
+ */
+
+
+/* CPU */
+
+/*
+ * Retrieves the minimum processing power in MHz available to the virtual
+ * machine. Assigning a cpuReservationMhz ensures that even as other virtual
+ * machines on a single host consume shared processing power, there is
+ * still a certain minimum amount for this virtual machine.
+ */
+VMGuestLibError VMGuestLib_GetCpuReservationMHz(VMGuestLibHandle handle,    // IN
+                                                uint32 *cpuReservationMHz); // OUT
+
+/*
+ * Retrieves the maximum processing power in MHz available to the virtual
+ * machine. Assigning a cpuLimitMHz ensures that this virtual machine never
+ * consumes more than a certain amount of the available processor power. By
+ * limiting the amount of processing power consumed, a portion of this
+ * shared resource is available to other virtual machines.
+ */
+VMGuestLibError VMGuestLib_GetCpuLimitMHz(VMGuestLibHandle handle, // IN
+                                          uint32 *cpuLimitMHz);    // OUT
+
+/*
+ * Retrieves the number of CPU shares allocated to the virtual machine.
+ */
+VMGuestLibError VMGuestLib_GetCpuShares(VMGuestLibHandle handle, // IN
+                                        uint32 *cpuShares);      // OUT
+
+/*
+ * Retrieves the number of milliseconds during which the virtual machine
+ * has been using the CPU. This value is always less than or equal to
+ * elapsedMS. This value, in conjunction with elapsedMS, can be used to
+ * estimate efective virtual machine CPU speed.
+ */
+VMGuestLibError VMGuestLib_GetCpuUsedMs(VMGuestLibHandle handle, // IN
+                                        uint64 *cpuUsedMs);      // OUT
+
+/*
+ * Host Processor speed. This can be used along with CpuUsedMs and
+ * elapsed time to estimate approximate effective VM CPU speed
+ * over a time interval. The following pseudocode illustrates how
+ * to make this calculation:
+ *
+ * ------------------------------------
+ *
+ * uint32 effectiveVMSpeed;
+ * uint32 hostMhz;
+ * uint64 elapsed1;
+ * uint64 elapsed2;
+ * uint64 used1;
+ * uint64 used2;
+ *
+ *
+ * VMGuestLib_UpdateInfo(handle);
+ * VMGuestLib_GetHostProcessorSpeed(handle, &hostMhz);
+ * VMGuestLib_GetElapsedMs(handle, &elapsed1);
+ * VMGuestLib_GetUsedMs(handle, &used1);
+ * ....
+ * VMGuestLib_UpdateInfo(handle);
+ * VMGuestLib_GetElapsedMs(handle, &elapsed2);
+ * VMGuestLib_GetUsedMs(handle, &used2);
+ *
+ * effectiveVMSpeed = hostMhz * ((used2 - used1) / (elapsed2 - elapsed1));
+ *
+ *
+ * ------------------------------------
+ *
+ * After this code executes, effectiveVMSpeed will be the approximate
+ * average effective speed of the VM's virtual CPU over the time period
+ * between the two calls to VMGuestLib_UpdateInfo().
+ *
+ */
+
+VMGuestLibError VMGuestLib_GetHostProcessorSpeed(VMGuestLibHandle handle, // IN
+                                                 uint32 *mhz);            // OUT
+
+
+/* Memory */
+
+/*
+ * Retrieves the minimum amount of memory that is available to the virtual
+ * machine. Assigning a cpuReservationMB ensures that even as other virtual
+ * machines on a single host consume memory, there is still a certain
+ * minimum amount for this virtual machine.
+ */
+VMGuestLibError VMGuestLib_GetMemReservationMB(VMGuestLibHandle handle,   // IN
+                                               uint32 *memReservationMB); // OUT
+
+/*
+ * Retrieves the maximum amount of memory that is available to the virtual
+ * machine. Assigning a cpuLimitMB ensures that this virtual machine never
+ * consumes more than a certain amount of the available processor power. By
+ * limiting the amount of processing power consumed, a portion of this
+ * shared resource is available to other virtual machines.
+ */
+VMGuestLibError VMGuestLib_GetMemLimitMB(VMGuestLibHandle handle, // IN
+                                         uint32 *memLimitMB);     // OUT
+
+/*
+ * Retrieves the number of memory shares allocated to the virtual machine.
+ */
+VMGuestLibError VMGuestLib_GetMemShares(VMGuestLibHandle handle, // IN
+                                        uint32 *memShares);      // OUT
+
+/*
+ * Retrieves the mapped memory size of this virtual machine. This
+ * is the current total amount of guest memory that is backed by
+ * physical memory. Note that this number may include pages of
+ * memory shared between multiple virtual machines and thus may be
+ * an overestimate of the amount of physical host memory "consumed"
+ * by this virtual machine.
+ */
+VMGuestLibError VMGuestLib_GetMemMappedMB(VMGuestLibHandle handle,  // IN
+                                          uint32 *memMappedSizeMB); // OUT
+
+/*
+ * Retrieves the estimated amount of memory the virtual machine is actively
+ * using. This method returns an estimated working set size for the virtual
+ * machine.
+ */
+VMGuestLibError VMGuestLib_GetMemActiveMB(VMGuestLibHandle handle, // IN
+                                          uint32 *memActiveMB);    // OUT
+
+/*
+ * Retrieves the amount of overhead memory associated with this virtual
+ * machine consumed on the host system.
+ */
+VMGuestLibError VMGuestLib_GetMemOverheadMB(VMGuestLibHandle handle, // IN
+                                            uint32 *memOverheadMB);  // OUT
+
+/*
+ * Retrieves the amount of memory that has been reclaimed from this virtual
+ * machine via the VMware Memory Balloon mechanism.
+ */
+VMGuestLibError VMGuestLib_GetMemBalloonedMB(VMGuestLibHandle handle, // IN
+                                             uint32 *memBalloonedMB); // OUT
+
+/*
+ * Retrieves the amount of memory associated with this virtual machine that
+ * has been swapped by the host system.
+ */
+VMGuestLibError VMGuestLib_GetMemSwappedMB(VMGuestLibHandle handle, // IN
+                                           uint32 *memSwappedMB);   // OUT
+
+/*
+ * Retrieves the amount of physical memory associated with this virtual
+ * machine that is copy-on-write (COW) shared on the host.
+ */
+VMGuestLibError VMGuestLib_GetMemSharedMB(VMGuestLibHandle handle, // IN
+                                          uint32 *memSharedMB);    // OUT
+
+/*
+ * Retrieves the estimated amount of physical memory on the host saved
+ * from copy-on-write (COW) shared guest physical memory.
+ */
+VMGuestLibError VMGuestLib_GetMemSharedSavedMB(VMGuestLibHandle handle,   // IN
+                                               uint32 *memSharedSavedMB); // OUT
+
+/*
+ * Retrieves the estimated amount of physical host memory currently
+ * consumed for this virtual machine's physical memory. This is the
+ * same as (mapped memory) - (sharedSaved memory).
+ */
+VMGuestLibError VMGuestLib_GetMemUsedMB(VMGuestLibHandle handle, // IN
+                                        uint32 *memUsedMB);      // OUT
+
+
+
+/* Elapsed Time */
+
+/*
+ * Retrieves the number of milliseconds that have passed in real time since
+ * the virtual machine started running on the current host system. The
+ * elapsed time counter is reset any time the virtual machine is powered
+ * on, resumed, or migrated via VMotion. This value, in conjunction with
+ * cpuUsedMS, can be used to estimate effective virtual machine CPU speed.
+ * The cpuUsedMS value is always less than or equal to this value.
+ */
+VMGuestLibError VMGuestLib_GetElapsedMs(VMGuestLibHandle handle, // IN
+                                        uint64 *elapsedMs);      // OUT
+
+/*
+ * Resource Pool Path.
+ *
+ * Retrieves a string representation of the path to this virtual machine in
+ * the resource pool namespace of the host system.
+ *
+ * pathBuffer is a pointer to a buffer that will receive the resource
+ * pool path string. bufferSize is a pointer to the size of the
+ * pathBuffer in bytes. If bufferSize is not large enough to
+ * accomodate the path and NUL terminator, then
+ * VMGUESTLIB_ERROR_BUFFER_TOO_SMALL is returned and bufferSize
+ * contains the amount of memory needed (in bytes).
+ */
+
+VMGuestLibError VMGuestLib_GetResourcePoolPath(VMGuestLibHandle handle, // IN
+                                               size_t *bufferSize,      // IN/OUT
+                                               char *pathBuffer);       // OUT
+
+/*
+ * CPU stolen time. The time (in ms) that the VM was runnable but not scheduled
+ * to run.
+ */
+
+VMGuestLibError VMGuestLib_GetCpuStolenMs(VMGuestLibHandle handle, // IN
+                                          uint64 *cpuStolenMs);    // OUT
+/*
+ * Memory Target Size.
+ */
+
+VMGuestLibError VMGuestLib_GetMemTargetSizeMB(VMGuestLibHandle handle,  // IN
+                                              uint64 *memTargetSizeMB); // OUT
+
+/*
+ * Number of physical CPU cores on the host machine.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostNumCpuCores(VMGuestLibHandle handle,   // IN
+                              uint32 *hostNumCpuCores);  // OUT
+
+/*
+ * Total CPU time used by host.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostCpuUsedMs(VMGuestLibHandle handle,  // IN
+                            uint64 *hostCpuUsedMs);   // OUT
+
+/*
+ * Total memory swapped out on the host.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostMemSwappedMB(VMGuestLibHandle handle,     // IN
+                               uint64 *hostMemSwappedMB);   // OUT
+
+/*
+ * Total COW (Copy-On-Write) memory on host.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostMemSharedMB(VMGuestLibHandle handle,   // IN
+                              uint64 *hostMemSharedMB);  // OUT
+
+/*
+ * Total consumed memory on host.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostMemUsedMB(VMGuestLibHandle handle,  // IN
+                            uint64 *hostMemUsedMB);   // OUT
+
+/*
+ * Total memory available to host OS kernel.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostMemPhysMB(VMGuestLibHandle handle,  // IN
+                            uint64 *hostMemPhysMB);   // OUT
+
+/*
+ * Total physical memory free on host.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostMemPhysFreeMB(VMGuestLibHandle handle,    // IN
+                                uint64 *hostMemPhysFreeMB); // OUT
+
+/*
+ * Total host kernel memory overhead.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostMemKernOvhdMB(VMGuestLibHandle handle,     // IN
+                                uint64 *hostMemKernOvhdMB);  // OUT
+
+/*
+ * Total mapped memory on host.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostMemMappedMB(VMGuestLibHandle handle,  // IN
+                              uint64 *hostMemMappedMB); // OUT
+
+/*
+ * Total unmapped memory on host.
+ */
+
+VMGuestLibError
+VMGuestLib_GetHostMemUnmappedMB(VMGuestLibHandle handle,    // IN
+                                uint64 *hostMemUnmappedMB); // OUT
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _VM_GUEST_LIB_H_ */

building/misc/VMWareMetricLogger/GuestSDK/include/vmSessionId.h

+/* **********************************************************
+ * Copyright 2006-2008 VMware, Inc.  All rights reserved. -- VMware Confidential
+ * **********************************************************/
+
+#ifndef _VM_SESSION_ID_H_
+#define _VM_SESSION_ID_H_
+
+
+#include "vm_basic_types.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef uint64 VMSessionId;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* _VM_SESSION_ID_H_ */

building/misc/VMWareMetricLogger/GuestSDK/include/vm_basic_types.h

+/* **********************************************************
+ * Copyright (c) 1998-2009 VMware, Inc.  All rights reserved. -- VMware Confidential
+ * **********************************************************/
+
+/*
+ *
+ * vm_basic_types.h --
+ *
+ *    basic data types.
+ */
+
+
+#ifndef _VM_BASIC_TYPES_H_
+#define _VM_BASIC_TYPES_H_
+
+#define INCLUDE_ALLOW_USERLEVEL
+
+#define INCLUDE_ALLOW_MODULE
+#define INCLUDE_ALLOW_VMMON
+#define INCLUDE_ALLOW_VMKERNEL
+#define INCLUDE_ALLOW_VMKDRIVERS
+#define INCLUDE_ALLOW_VMK_MODULE
+#define INCLUDE_ALLOW_DISTRIBUTE
+#define INCLUDE_ALLOW_VMCORE
+#define INCLUDE_ALLOW_VMIROM
+
+/* STRICT ANSI means the Xserver build and X defines Bool differently. */
+#if !defined(_XTYPEDEF_BOOL) && \
+    (!defined(__STRICT_ANSI__) || defined(__FreeBSD__) || defined(__MINGW32__))
+#define _XTYPEDEF_BOOL
+typedef char           Bool;
+#endif
+
+#ifndef FALSE
+#define FALSE          0
+#endif
+
+#ifndef TRUE
+#define TRUE           1
+#endif
+
+#define IsBool(x)      (((x) & ~1) == 0)
+#define IsBool2(x, y)  ((((x) | (y)) & ~1) == 0)
+
+/*
+ * Macros __i386__ and __ia64 are intrinsically defined by GCC
+ */
+#if defined _MSC_VER && defined _M_X64
+#  define __x86_64__
+#elif defined _MSC_VER && defined _M_IX86
+#  define __i386__
+#endif
+
+#ifdef __i386__
+#define VM_I386
+#endif
+
+#ifdef __x86_64__
+#define VM_X86_64
+#define VM_I386
+#define vm_x86_64 (1)
+#else
+#define vm_x86_64 (0)
+#endif
+
+
+#ifdef _MSC_VER
+
+#pragma warning (3 :4505) // unreferenced local function
+#pragma warning (disable :4018) // signed/unsigned mismatch
+#pragma warning (disable :4761) // integral size mismatch in argument; conversion supplied
+#pragma warning (disable :4305) // truncation from 'const int' to 'short'
+#pragma warning (disable :4244) // conversion from 'unsigned short' to 'unsigned char'
+#pragma warning (disable :4267) // truncation of 'size_t'
+#pragma warning (disable :4146) // unary minus operator applied to unsigned type, result still unsigned
+#pragma warning (disable :4142) // benign redefinition of type
+
+#endif
+
+#if defined(__APPLE__) || defined(HAVE_STDINT_H)
+
+/*
+ * TODO: This is a C99 standard header.  We should be able to test for
+ * #if __STDC_VERSION__ >= 199901L, but that breaks the Netware build
+ * (which doesn't have stdint.h).
+ */
+
+#include <stdint.h>
+
+typedef uint64_t    uint64;
+typedef  int64_t     int64;
+typedef uint32_t    uint32;
+typedef  int32_t     int32;
+typedef uint16_t    uint16;
+typedef  int16_t     int16;
+typedef  uint8_t    uint8;
+typedef   int8_t     int8;
+
+/*
+ * Note: C does not specify whether char is signed or unsigned, and
+ * both gcc and msvc implement processor-specific signedness.  With
+ * three types:
+ * typeof(char) != typeof(signed char) != typeof(unsigned char)
+ *
+ * Be careful here, because gcc (4.0.1 and others) likes to warn about
+ * conversions between signed char * and char *.
+ */
+
+#else /* !HAVE_STDINT_H */
+
+#ifdef _MSC_VER
+
+typedef unsigned __int64 uint64;
+typedef signed __int64 int64;
+
+#elif __GNUC__
+/* The Xserver source compiles with -ansi -pendantic */
+#   if !defined(__STRICT_ANSI__) || defined(__FreeBSD__)
+#      if defined(VM_X86_64)
+typedef unsigned long uint64;
+typedef long int64;
+#      else
+typedef unsigned long long uint64;
+typedef long long int64;
+#      endif
+#   endif
+#else
+#   error - Need compiler define for int64/uint64
+#endif /* _MSC_VER */
+
+typedef unsigned int       uint32;
+typedef unsigned short     uint16;
+typedef unsigned char      uint8;
+
+typedef int                int32;
+typedef short              int16;
+typedef signed char        int8;
+
+#endif /* HAVE_STDINT_H */
+
+/*
+ * FreeBSD (for the tools build) unconditionally defines these in
+ * sys/inttypes.h so don't redefine them if this file has already
+ * been included. [greg]
+ *
+ * This applies to Solaris as well.
+ */
+
+/*
+ * Before trying to do the includes based on OS defines, see if we can use
+ * feature-based defines to get as much functionality as possible
+ */
+
+#ifdef HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_INTTYPES_H
+#include <sys/inttypes.h>
+#endif
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+
+#ifdef __FreeBSD__
+#include <sys/param.h> /* For __FreeBSD_version */
+#endif
+
+#if !defined(USING_AUTOCONF)
+#   if defined(__FreeBSD__) || defined(sun)
+#      ifdef KLD_MODULE
+#         include <sys/types.h>
+#      else
+#         if __FreeBSD_version >= 500043
+#            if !defined(VMKERNEL)
+#               include <inttypes.h>
+#            endif
+#            include <sys/types.h>
+#         else
+#            include <sys/inttypes.h>
+#         endif
+#      endif
+#   elif defined __APPLE__
+#      if KERNEL
+#         include <sys/unistd.h>
+#         include <sys/types.h> /* mostly for size_t */
+#         include <stdint.h>
+#      else
+#         include <unistd.h>
+#         include <inttypes.h>
+#         include <stdlib.h>
+#         include <stdint.h>
+#      endif
+#   elif defined __ANDROID__
+#      include <stdint.h>
+#   else
+#      if !defined(__intptr_t_defined) && !defined(intptr_t)
+#         ifdef VM_I386
+#         define __intptr_t_defined
+#            ifdef VM_X86_64
+typedef int64     intptr_t;
+#            else
+typedef int32     intptr_t;
+#            endif
+#         elif defined(__arm__)
+typedef int32     intptr_t;
+#         endif
+#      endif
+
+#      ifndef _STDINT_H
+#         ifdef VM_I386
+#            ifdef VM_X86_64
+typedef uint64    uintptr_t;
+#            else
+typedef uint32    uintptr_t;
+#            endif
+#         elif defined(__arm__)
+typedef uint32    uintptr_t;
+#         endif
+#      endif
+#   endif
+#endif
+
+
+/*
+ * Time
+ * XXX These should be cleaned up.  -- edward
+ */
+
+typedef int64 VmTimeType;          /* Time in microseconds */
+typedef int64 VmTimeRealClock;     /* Real clock kept in microseconds */
+typedef int64 VmTimeVirtualClock;  /* Virtual Clock kept in CPU cycles */
+
+/*
+ * Printf format specifiers for size_t and 64-bit number.
+ * Use them like this:
+ *    printf("%"FMT64"d\n", big);
+ *
+ * FMTH is for handles/fds.
+ */
+
+#ifdef _MSC_VER
+   #define FMT64      "I64"
+   #ifdef VM_X86_64
+      #define FMTSZ      "I64"
+      #define FMTPD      "I64"
+      #define FMTH       "I64"
+   #else
+      #define FMTSZ      "I"
+      #define FMTPD      "I"
+      #define FMTH       "I"
+   #endif
+#elif defined __APPLE__
+   /* Mac OS hosts use the same formatters for 32- and 64-bit. */
+   #define FMT64 "ll"
+   #if KERNEL
+      #define FMTSZ "l"
+   #else
+      #define FMTSZ "z"
+   #endif
+   #define FMTPD "l"
+   #define FMTH ""
+#elif __GNUC__
+   #define FMTH ""
+   #if defined(N_PLAT_NLM) || defined(sun) || \
+       (defined(__FreeBSD__) && (__FreeBSD__ + 0) && ((__FreeBSD__ + 0) < 5))
+      /*
+       * Why (__FreeBSD__ + 0)?  See bug 141008.
+       * Yes, we really need to test both (__FreeBSD__ + 0) and
+       * ((__FreeBSD__ + 0) < 5).  No, we can't remove "+ 0" from
+       * ((__FreeBSD__ + 0) < 5).
+       */
+      #ifdef VM_X86_64
+         #define FMTSZ  "l"
+         #define FMTPD  "l"
+      #else
+         #define FMTSZ  ""
+         #define FMTPD  ""
+      #endif
+   #elif defined(__linux__) \
+      || (defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L) \
+      || (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) \
+      || (defined(_POSIX2_VERSION) && _POSIX2_VERSION >= 200112L)
+      /* BSD, Linux */
+      #define FMTSZ     "z"
+
+      #if defined(VM_X86_64)
+         #define FMTPD  "l"
+      #else
+         #define FMTPD  ""
+      #endif
+   #else
+      /* Systems with a pre-C99 libc */
+      #define FMTSZ     "Z"
+      #ifdef VM_X86_64
+         #define FMTPD  "l"
+      #else
+         #define FMTPD  ""
+      #endif
+   #endif
+   #ifdef VM_X86_64
+      #define FMT64     "l"
+   #elif defined(sun) || defined(__FreeBSD__)
+      #define FMT64     "ll"
+   #else
+      #define FMT64     "L"
+   #endif
+#else
+   #error - Need compiler define for FMT64 and FMTSZ
+#endif
+
+/*
+ * Suffix for 64-bit constants.  Use it like this:
+ *    CONST64(0x7fffffffffffffff) for signed or
+ *    CONST64U(0x7fffffffffffffff) for unsigned.
+ *
+ * 2004.08.30(thutt):
+ *   The vmcore/asm64/gen* programs are compiled as 32-bit
+ *   applications, but must handle 64 bit constants.  If the
+ *   64-bit-constant defining macros are already defined, the
+ *   definition will not be overwritten.
+ */
+
+#if !defined(CONST64) || !defined(CONST64U)
+#ifdef _MSC_VER
+#define CONST64(c) c##I64
+#define CONST64U(c) c##uI64
+#elif defined __APPLE__
+#define CONST64(c) c##LL
+#define CONST64U(c) c##uLL
+#elif __GNUC__
+#ifdef VM_X86_64
+#define CONST64(c) c##L
+#define CONST64U(c) c##uL
+#else
+#define CONST64(c) c##LL
+#define CONST64U(c) c##uLL
+#endif
+#else
+#error - Need compiler define for CONST64
+#endif
+#endif
+
+/*
+ * Use CONST3264/CONST3264U if you want a constant to be
+ * treated as a 32-bit number on 32-bit compiles and
+ * a 64-bit number on 64-bit compiles. Useful in the case
+ * of shifts, like (CONST3264U(1) << x), where x could be
+ * more than 31 on a 64-bit compile.
+ */
+
+#ifdef VM_X86_64
+    #define CONST3264(a) CONST64(a)
+    #define CONST3264U(a) CONST64U(a)
+#else
+    #define CONST3264(a) (a)
+    #define CONST3264U(a) (a)
+#endif
+
+#define MIN_INT8   ((int8)0x80)
+#define MAX_INT8   ((int8)0x7f)
+
+#define MIN_UINT8  ((uint8)0)
+#define MAX_UINT8  ((uint8)0xff)
+
+#define MIN_INT16  ((int16)0x8000)
+#define MAX_INT16  ((int16)0x7fff)
+
+#define MIN_UINT16 ((uint16)0)
+#define MAX_UINT16 ((uint16)0xffff)
+
+#define MIN_INT32  ((int32)0x80000000)
+#define MAX_INT32  ((int32)0x7fffffff)
+
+#define MIN_UINT32 ((uint32)0)
+#define MAX_UINT32 ((uint32)0xffffffff)
+
+#define MIN_INT64  (CONST64(0x8000000000000000))
+#define MAX_INT64  (CONST64(0x7fffffffffffffff))
+
+#define MIN_UINT64 (CONST64U(0))
+#define MAX_UINT64 (CONST64U(0xffffffffffffffff))
+
+typedef uint8 *TCA;  /* Pointer into TC (usually). */
+
+/*
+ * Type big enough to hold an integer between 0..100
+ */
+typedef uint8 Percent;
+#define AsPercent(v)	((Percent)(v))
+
+
+typedef uintptr_t VA;
+typedef uintptr_t VPN;
+
+typedef uint64    PA;
+typedef uint32    PPN;
+
+typedef uint64    PhysMemOff;
+typedef uint64    PhysMemSize;
+
+/* The Xserver source compiles with -ansi -pendantic */
+#ifndef __STRICT_ANSI__
+typedef uint64    BA;
+#endif
+typedef uint32    BPN;
+typedef uint32    PageNum;
+typedef unsigned      MemHandle;
+typedef unsigned int  IoHandle;
+typedef int32     World_ID;
+
+/* !! do not alter the definition of INVALID_WORLD_ID without ensuring
+ * that the values defined in both bora/public/vm_basic_types.h and
+ * lib/vprobe/vm_basic_types.h are the same.  Additionally, the definition
+ * of VMK_INVALID_WORLD_ID in vmkapi_world.h also must be defined with
+ * the same value
+ */
+
+#define INVALID_WORLD_ID ((World_ID)0)
+
+typedef World_ID User_CartelID;
+#define INVALID_CARTEL_ID INVALID_WORLD_ID
+
+typedef User_CartelID User_SessionID;
+#define INVALID_SESSION_ID INVALID_CARTEL_ID
+
+typedef User_CartelID User_CartelGroupID;
+#define INVALID_CARTELGROUP_ID INVALID_CARTEL_ID
+
+typedef uint32 Worldlet_ID;
+#define INVALID_WORLDLET_ID ((Worldlet_ID)-1)
+
+/* The Xserver source compiles with -ansi -pendantic */
+#ifndef __STRICT_ANSI__
+typedef uint64 MA;
+typedef uint32 MPN;
+#endif
+
+/*
+ * This type should be used for variables that contain sector
+ * position/quantity.
+ */
+typedef uint64 SectorType;
+
+/*
+ * Linear address
+ */
+
+typedef uintptr_t LA;
+typedef uintptr_t LPN;
+#define LA_2_LPN(_la)     ((_la) >> PAGE_SHIFT)
+#define LPN_2_LA(_lpn)    ((_lpn) << PAGE_SHIFT)
+
+#define LAST_LPN   ((((LA)  1) << (8 * sizeof(LA)   - PAGE_SHIFT)) - 1)
+#define LAST_LPN32 ((((LA32)1) << (8 * sizeof(LA32) - PAGE_SHIFT)) - 1)
+#define LAST_LPN64 ((((LA64)1) << (8 * sizeof(LA64) - PAGE_SHIFT)) - 1)
+
+/* Valid bits in a LPN. */
+#define LPN_MASK   LAST_LPN
+#define LPN_MASK32 LAST_LPN32
+#define LPN_MASK64 LAST_LPN64
+
+/*
+ * On 64 bit platform, address and page number types default
+ * to 64 bit. When we need to represent a 32 bit address, we use
+ * types defined below.
+ *
+ * On 32 bit platform, the following types are the same as the
+ * default types.
+ */
+typedef uint32 VA32;
+typedef uint32 VPN32;
+typedef uint32 LA32;
+typedef uint32 LPN32;
+typedef uint32 PA32;
+typedef uint32 PPN32;
+typedef uint32 MA32;
+typedef uint32 MPN32;
+
+/*
+ * On 64 bit platform, the following types are the same as the
+ * default types.
+ */
+typedef uint64 VA64;
+typedef uint64 VPN64;
+typedef uint64 LA64;
+typedef uint64 LPN64;
+typedef uint64 PA64;
+typedef uint64 PPN64;
+typedef uint64 MA64;
+typedef uint64 MPN64;
+
+/*
+ * VA typedefs for user world apps.
+ */
+typedef VA32 UserVA32;
+typedef VA64 UserVA64;
+typedef UserVA64 UserVAConst; /* Userspace ptr to data that we may only read. */
+typedef UserVA32 UserVA32Const; /* Userspace ptr to data that we may only read. */
+typedef UserVA64 UserVA64Const; /* Used by 64-bit syscalls until conversion is finished. */
+#ifdef VMKERNEL
+typedef UserVA64 UserVA;
+#else
+typedef void * UserVA;
+#endif
+
+
+/*
+ * Maximal possible PPN value (errors too) that PhysMem can handle.
+ * Must be at least as large as MAX_PPN which is the maximum PPN
+ * for any region other than buserror.
+ */
+#define PHYSMEM_MAX_PPN   ((PPN)0xffffffff)
+#define MAX_PPN           ((PPN)0x1fffffff) /* Maximal observable PPN value. */
+#define INVALID_PPN       ((PPN)0xffffffff)
+#define APIC_DISABLED_PPN ((PPN)0xfffffffe)
+
+#define INVALID_BPN       ((BPN)0x1fffffff)
+
+#define RESERVED_MPN      ((MPN) 0)
+#define INVALID_MPN       ((MPN)-1)
+#define MEMREF_MPN        ((MPN)-2)
+#define RELEASED_MPN      ((MPN)-3)
+#define MAX_MPN           ((MPN)0x7fffffff)  /* 43 bits of address space. */
+
+#define INVALID_LPN       ((LPN)-1)
+#define INVALID_VPN       ((VPN)-1)
+#define INVALID_LPN64     ((LPN64)-1)
+#define INVALID_PAGENUM   ((PageNum)-1)
+
+
+/*
+ * Format modifier for printing VA, LA, and VPN.
+ * Use them like this: Log("%#"FMTLA"x\n", laddr)
+ */
+
+#if defined(VMM) || defined(FROBOS64) || vm_x86_64 || defined __APPLE__
+#   define FMTLA "l"
+#   define FMTVA "l"
+#   define FMTVPN "l"
+#else
+#   define FMTLA ""
+#   define FMTVA ""
+#   define FMTVPN ""
+#endif
+
+#ifndef EXTERN
+#define EXTERN        extern
+#endif
+#define CONST         const
+
+
+#ifndef INLINE
+#   ifdef _MSC_VER
+#      define INLINE        __inline
+#   else
+#      define INLINE        inline
+#   endif
+#endif
+
+
+/*
+ * Annotation for data that may be exported into a DLL and used by other
+ * apps that load that DLL and import the data.
+ */
+#if defined(_WIN32) && defined(VMX86_IMPORT_DLLDATA)
+#  define VMX86_EXTERN_DATA       extern __declspec(dllimport)
+#else // !_WIN32
+#  define VMX86_EXTERN_DATA       extern
+#endif
+
+#if defined(_WIN32) && !defined(VMX86_NO_THREADS)
+#define THREADSPECIFIC __declspec(thread)
+#else
+#define THREADSPECIFIC
+#endif
+
+/*
+ * Due to the wonderful "registry redirection" feature introduced in
+ * 64-bit Windows, if you access any key under HKLM\Software in 64-bit
+ * code, you need to open/create/delete that key with
+ * VMKEY_WOW64_32KEY if you want a consistent view with 32-bit code.
+ */
+
+#ifdef _WIN32
+#ifdef _WIN64
+#define VMW_KEY_WOW64_32KEY KEY_WOW64_32KEY
+#else
+#define VMW_KEY_WOW64_32KEY 0x0
+#endif
+#endif
+
+
+/*
+ * At present, we effectively require a compiler that is at least
+ * gcc-3.3 (circa 2003).  Enforce this here, various things below
+ * this line depend upon it.
+ *
+ * In practice, most things presently compile with gcc-4.1 or gcc-4.4.
+ * The various linux kernel modules may use older (gcc-3.3) compilers.
+ */
+#if defined __GNUC__ && (__GNUC__ < 3 || (__GNUC__ == 3 && __GNUC_MINOR__ < 3))
+#error "gcc version is to old to compile assembly, need gcc-3.3 or better"
+#endif
+
+
+/*
+ * Consider the following reasons functions are inlined:
+ *
+ *  1) inlined for performance reasons
+ *  2) inlined because it's a single-use function
+ *
+ * Functions which meet only condition 2 should be marked with this
+ * inline macro; It is not critical to be inlined (but there is a
+ * code-space & runtime savings by doing so), so when other callers
+ * are added the inline-ness should be removed.
+ */
+
+#if defined __GNUC__
+/*
+ * Starting at version 3.3, gcc does not always inline functions marked
+ * 'inline' (it depends on their size and other factors). To force gcc
+ * to inline a function, one must use the __always_inline__ attribute.
+ * This attribute should be used sparingly and with care.  It is usually
+ * preferable to let gcc make its own inlining decisions
+ */
+#   define INLINE_ALWAYS INLINE __attribute__((__always_inline__))
+#else
+#   define INLINE_ALWAYS INLINE
+#endif
+#define INLINE_SINGLE_CALLER INLINE_ALWAYS
+
+/*
+ * Used when a hard guaranteed of no inlining is needed. Very few
+ * instances need this since the absence of INLINE is a good hint
+ * that gcc will not do inlining.
+ */
+
+#if defined(__GNUC__) && (defined(VMM) || defined (VMKERNEL))
+#define ABSOLUTELY_NOINLINE __attribute__((__noinline__))
+#endif
+
+/*
+ * Attributes placed on function declarations to tell the compiler
+ * that the function never returns.
+ */
+
+#ifdef _MSC_VER
+#define NORETURN __declspec(noreturn)
+#elif defined __GNUC__
+#define NORETURN __attribute__((__noreturn__))
+#else
+#define NORETURN
+#endif
+
+/*
+ * Branch prediction hints:
+ *     LIKELY(exp)   - Expression exp is likely TRUE.
+ *     UNLIKELY(exp) - Expression exp is likely FALSE.
+ *   Usage example:
+ *        if (LIKELY(excCode == EXC_NONE)) {
+ *               or
+ *        if (UNLIKELY(REAL_MODE(vc))) {
+ *
+ * We know how to predict branches on gcc3 and later (hopefully),
+ * all others we don't so we do nothing.
+ */
+
+#if defined __GNUC__
+/*
+ * gcc3 uses __builtin_expect() to inform the compiler of an expected value.
+ * We use this to inform the static branch predictor. The '!!' in LIKELY
+ * will convert any !=0 to a 1.
+ */
+#define LIKELY(_exp)     __builtin_expect(!!(_exp), 1)
+#define UNLIKELY(_exp)   __builtin_expect((_exp), 0)
+#else
+#define LIKELY(_exp)      (_exp)
+#define UNLIKELY(_exp)    (_exp)
+#endif
+
+/*
+ * GCC's argument checking for printf-like functions
+ * This is conditional until we have replaced all `"%x", void *'
+ * with `"0x%08x", (uint32) void *'. Note that %p prints different things
+ * on different platforms.  Argument checking is enabled for the
+ * vmkernel, which has already been cleansed.
+ *
+ * fmtPos is the position of the format string argument, beginning at 1
+ * varPos is the position of the variable argument, beginning at 1
+ */
+
+#if defined(__GNUC__)
+# define PRINTF_DECL(fmtPos, varPos) __attribute__((__format__(__printf__, fmtPos, varPos)))
+#else
+# define PRINTF_DECL(fmtPos, varPos)
+#endif
+
+#if defined(__GNUC__)
+# define SCANF_DECL(fmtPos, varPos) __attribute__((__format__(__scanf__, fmtPos, varPos)))
+#else
+# define SCANF_DECL(fmtPos, varPos)
+#endif
+
+/*
+ * UNUSED_PARAM should surround the parameter name and type declaration,
+ * e.g. "int MyFunction(int var1, UNUSED_PARAM(int var2))"
+ *
+ */
+
+#ifndef UNUSED_PARAM
+# if defined(__GNUC__)
+#  define UNUSED_PARAM(_parm) _parm  __attribute__((__unused__))
+# else
+#  define UNUSED_PARAM(_parm) _parm
+# endif
+#endif
+
+#ifndef UNUSED_VARIABLE
+// XXX is there a better way?
+#  define UNUSED_VARIABLE(_var) (void)_var
+#endif
+
+/*
+ * REGPARM defaults to REGPARM3; i.e., a request that gcc
+ * put the first three arguments in registers.  (It is fine
+ * if the function has fewer than three arguments.)  Gcc only.
+ * Syntactically, put REGPARM where you'd put INLINE or NORETURN.
+ *
+ * Note that 64-bit code already puts the first six arguments in
+ * registers, so these attributes are only useful for 32-bit code.
+ */
+
+#if defined(__GNUC__)
+# define REGPARM0 __attribute__((regparm(0)))
+# define REGPARM1 __attribute__((regparm(1)))
+# define REGPARM2 __attribute__((regparm(2)))
+# define REGPARM3 __attribute__((regparm(3)))
+# define REGPARM REGPARM3
+#else
+# define REGPARM0
+# define REGPARM1
+# define REGPARM2
+# define REGPARM3
+# define REGPARM
+#endif
+
+
+/*
+ * gcc can warn us if we're ignoring returns
+ */
+#if defined(__GNUC__)
+# define MUST_CHECK_RETURN __attribute__((warn_unused_result))
+#else
+# define MUST_CHECK_RETURN
+#endif
+
+/*
+ * ALIGNED specifies minimum alignment in "n" bytes.
+ */
+
+#ifdef __GNUC__
+#define ALIGNED(n) __attribute__((__aligned__(n)))
+#else
+#define ALIGNED(n)
+#endif
+
+/*
+ * Once upon a time, this was used to silence compiler warnings that
+ * get generated when the compiler thinks that a function returns
+ * when it is marked noreturn.  Don't do it.  Use NOT_REACHED().
+ */
+
+#define INFINITE_LOOP()           do { } while (1)
+
+/*
+ * On FreeBSD (for the tools build), size_t is typedef'd if _BSD_SIZE_T_
+ * is defined. Use the same logic here so we don't define it twice. [greg]
+ */
+#ifdef __FreeBSD__
+#   ifdef _BSD_SIZE_T_
+#      undef _BSD_SIZE_T_
+#      ifdef VM_I386
+#         ifdef VM_X86_64
+             typedef uint64 size_t;
+#         else
+             typedef uint32 size_t;
+#         endif
+#      endif /* VM_I386 */
+#   endif
+
+#   ifdef _BSD_SSIZE_T_
+#      undef _BSD_SSIZE_T_
+#      ifdef VM_I386
+#         ifdef VM_X86_64
+             typedef int64 ssize_t;
+#         else
+             typedef int32 ssize_t;
+#         endif
+#      endif /* VM_I386 */
+#   endif
+
+#else
+#   if !defined(_SIZE_T) && !defined(_SIZE_T_DEFINED)
+#      ifdef VM_I386
+#         define _SIZE_T
+#         ifdef VM_X86_64
+             typedef uint64 size_t;
+#         else
+             typedef uint32 size_t;
+#         endif
+#      elif defined(__arm__)
+#         define _SIZE_T
+          typedef uint32 size_t;
+#      endif
+#   endif
+
+#   if !defined(FROBOS) && !defined(_SSIZE_T) && !defined(_SSIZE_T_) && \
+       !defined(ssize_t) && !defined(__ssize_t_defined) && \
+       !defined(_SSIZE_T_DECLARED) && !defined(_SSIZE_T_DEFINED) && \
+       !defined(_SSIZE_T_DEFINED_)
+#      ifdef VM_I386
+#         define _SSIZE_T
+#         define __ssize_t_defined
+#         define _SSIZE_T_DECLARED
+#         ifdef VM_X86_64
+             typedef int64 ssize_t;
+#         else
+             typedef int32 ssize_t;
+#         endif
+#      elif defined(__arm__)
+#         define _SSIZE_T
+#         define __ssize_t_defined
+#         define _SSIZE_T_DECLARED
+             typedef int32 ssize_t;
+#      endif
+#   endif
+
+#endif
+
+/*
+ * Format modifier for printing pid_t.  On sun the pid_t is a ulong, but on
+ * Linux it's an int.
+ * Use this like this: printf("The pid is %"FMTPID".\n", pid);
+ */
+#ifdef sun
+#   ifdef VM_X86_64
+#      define FMTPID "d"
+#   else
+#      define FMTPID "lu"
+#   endif
+#else
+# define FMTPID "d"
+#endif
+
+/*
+ * Format modifier for printing uid_t.  On Solaris 10 and earlier, uid_t
+ * is a ulong, but on other platforms it's an unsigned int.
+ * Use this like this: printf("The uid is %"FMTUID".\n", uid);
+ */
+#if defined(sun) && !defined(SOL11)
+#   ifdef VM_X86_64
+#      define FMTUID "u"
+#   else
+#      define FMTUID "lu"
+#   endif
+#else
+# define FMTUID "u"
+#endif
+
+/*
+ * Format modifier for printing mode_t.  On sun the mode_t is a ulong, but on
+ * Linux it's an int.
+ * Use this like this: printf("The mode is %"FMTMODE".\n", mode);
+ */
+#ifdef sun
+#   ifdef VM_X86_64
+#      define FMTMODE "o"
+#   else
+#      define FMTMODE "lo"
+#   endif
+#else
+# define FMTMODE "o"
+#endif
+
+/*
+ * Format modifier for printing time_t. Most platforms define a time_t to be
+ * a long int, but on FreeBSD (as of 5.0, it seems), the time_t is a signed
+ * size quantity. Refer to the definition of FMTSZ to see why we need silly
+ * preprocessor arithmetic.
+ * Use this like this: printf("The mode is %"FMTTIME".\n", time);
+ */
+#if defined(__FreeBSD__) && (__FreeBSD__ + 0) && ((__FreeBSD__ + 0) >= 5)
+#   define FMTTIME FMTSZ"d"
+#else
+#   if defined(_MSC_VER)
+#      ifndef _SAFETIME_H_
+#         if (_MSC_VER < 1400) || defined(_USE_32BIT_TIME_T)
+#             define FMTTIME "ld"
+#         else
+#             define FMTTIME FMT64"d"
+#         endif
+#      else
+#         ifndef FMTTIME
+#            error "safetime.h did not define FMTTIME"
+#         endif
+#      endif
+#   else
+#      define FMTTIME "ld"
+#   endif
+#endif
+
+#ifdef __APPLE__
+/*
+ * Format specifier for all these annoying types such as {S,U}Int32
+ * which are 'long' in 32-bit builds
+ *       and  'int' in 64-bit builds.
+ */
+#   ifdef __LP64__
+#      define FMTLI ""
+#   else
+#      define FMTLI "l"
+#   endif
+
+/*
+ * Format specifier for all these annoying types such as NS[U]Integer
+ * which are  'int' in 32-bit builds
+ *       and 'long' in 64-bit builds.
+ */
+#   ifdef __LP64__
+#      define FMTIL "l"
+#   else
+#      define FMTIL ""
+#   endif
+#endif
+
+
+/*
+ * Define MXSemaHandle here so both vmmon and vmx see this definition.
+ */
+
+#ifdef _WIN32
+typedef uintptr_t MXSemaHandle;
+#else
+typedef int MXSemaHandle;
+#endif
+
+/*
+ * Define type for poll device handles.
+ */
+
+typedef int64 PollDevHandle;
+
+/*
+ * Define the utf16_t type.
+ */
+
+#if defined(_WIN32) && defined(_NATIVE_WCHAR_T_DEFINED)
+typedef wchar_t utf16_t;
+#else
+typedef uint16 utf16_t;
+#endif
+
+/*
+ * Define for point and rectangle types.  Defined here so they
+ * can be used by other externally facing headers in bora/public.
+ */
+
+typedef struct VMPoint {
+   int x, y;
+} VMPoint;
+
+#if defined _WIN32 && defined USERLEVEL