Program Listing for File gpa-singleton.h

Return to documentation for file (include\instrumentation\gpa-singleton.h)

/******************************************************************************
Copyright (c) 2023 Intel Corporation.

This software and the related documents are Intel copyrighted materials,
and your use of them is governed by the express license under which they
were provided to you ("License"). Unless the License provides otherwise,
you may not use, modify, copy, publish, distribute, disclose or transmit
this software or the related documents without Intel's prior written
permission.


 This software and the related documents are provided as is, with no express
or implied warranties, other than those that are expressly stated in the
License.

******************************************************************************/

#pragma once

#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

#include <stdlib.h>
#include "instrumentation/gpa-secure.h"
#include <cstdint>

namespace gpa {

//Since environment is shared across all the process, we can piggyback on it to store "key/value" pairs for intra-process sharing
struct ProcessWideSingletonRegistry
{
    static uint32_t GetPid()
    {
#ifdef _WIN32
        static auto pid = GetCurrentProcessId();
#else
        static auto pid = getpid();
#endif
        return (uint32_t)pid;
    }

    static void* Get(const char* name, void* fallback = nullptr)  //Gets item by name
    {
        char prefix[256] = {};
        GPA_SPRINTF(prefix, sizeof(prefix), "GPA:%x:%s", GetPid(), name);
        unsigned long long addr = 0;
#ifdef _WIN32
        char val[256] = {};
        size_t res = 0;
        if (0 != getenv_s(&res, val, sizeof(val), prefix) || !res)
            return fallback;
        sscanf_s(val, "%llx", &addr);
#else
        const char* val = getenv(prefix);
        if (!val) return fallback;
        sscanf(val, "%llx", &addr);
#endif
        return (void*)addr;
    }

    static bool Set(const char* name, const void* ptr)  //Stores item by name. ATTENTION: must set to nullptr before previously set object is destroyed!
    {
        char env[256] = {};
        GPA_SPRINTF(env, sizeof(env), "GPA:%x:%s=%llx", GetPid(), name, (unsigned long long)ptr);
#ifdef _WIN32
        return 0 == _putenv(env);
#else
        return 0 == putenv(env);
#endif
    }
};

}  // namespace gpa