//-----------------------------------------------------------------------------
/// InitCommunication
///
/// This function only needs to be called by wrapper plugins. It sets up the
/// inter-process communication between the wrapper (which is in the app's
/// process space) and the PerfServer.
//-----------------------------------------------------------------------------
bool InitCommunication(const char* strShortDescription, ProcessRequest_type pProcessRequestCallback)
{
    unsigned long pid = osGetCurrentProcessId();
#ifdef _WIN32
    sprintf_s(g_strSharedMemoryName, PS_MAX_PATH, "%lu/%s", pid, strShortDescription);
#else
    // the '/' character can't be used as a filename in Linux, so just use the plugin name as the shared memory name
    // (ignore the process ID)
    sprintf_s(g_strSharedMemoryName, PS_MAX_PATH, "%lu %s", pid, strShortDescription);
#endif

    if (smCreate(g_strSharedMemoryName, 100, sizeof(HTTPRequestHeader)) == false)
    {
        Log(logERROR, "InitCommunication: Can't open or create SharedMemory for %s.\n", strShortDescription);
        return false;
    }

    if (smOpen("PLUGINS_TO_GPS") == false)
    {
        smClose(g_strSharedMemoryName);
        Log(logERROR, "InitCommunication: Can't open SharedMemory for PLUGINS_TO_GPS.\n");
        return false;
    }

    // store a local pointer to the ProcessRequest function
    g_processRequest = pProcessRequestCallback;

    if (g_processRequest == NULL)
    {
        smClose(g_strSharedMemoryName);
        Log(logERROR, "InitCommunication: ProcessRequest is NULL\n");
        return false;
    }

    // protect the maps from being changed by other threads using the mutex
    ScopeLock lock(s_mutex);

    g_requestMap.clear();
    g_pBufferedResponse = NULL;
    g_uBufferedResponseSize = 0;

    return true;
}
//--------------------------------------------------------------
/// Create the shared memory needed to communicate between the
/// web server and the plugin
/// \return true if successful, false if error
//--------------------------------------------------------------
bool ProcessTracker::CreateSharedMemory()
{
#ifdef _WIN32

    if (smExists("GPS_TO_MDLL"))
    {
        if (smOpen("GPS_TO_MDLL"))
        {
            if (smLockGet("GPS_TO_MDLL"))
            {
                //the shared memory already exists, so we need to read everything from it, to make sure it's empty
                // closing and recreated the shared memory does not work because the MicroDLL has it open
                // so that it can inject into any spawned processes (via CreateProcess). If MicroDLL doesn't keep
                // a handle to the shared memory, it could be closed by everyone, get destroyed and then it wouldn't
                // be able to follow CreateProcess.
                char tmp[ PS_MAX_PATH ];

                while (smGet("GPS_TO_MDLL", NULL, 0) != 0)
                {
                    // the smGet call will clear the shared memory
                    smGet("GPS_TO_MDLL", tmp, PS_MAX_PATH);
                }

                smUnlockGet("GPS_TO_MDLL");
            }
        }
    }

    // now write the plugin info into the shared memory
    // Put wrapper info into a shared memory for micro DLL
    // make the shared memory big enough for all the wrappers that are known about
    // even though we're only going to write in the wrappers that are allowed
    if (smCreate("GPS_TO_MDLL", (unsigned long)GetWrapperMap().size() * 3, PS_MAX_PATH))
    {
        // lock the buffer if it has enough space for 3 strings for each of the allowed wrappers
        unsigned long ulNumBuffers = (unsigned long) g_allowedWrappersMap.size() * 3;

        if (smLockPut("GPS_TO_MDLL", ulNumBuffers * PS_MAX_PATH, ulNumBuffers))
        {
            char strPath[PS_MAX_PATH];
            char strName[PS_MAX_PATH];
            char strDlls[PS_MAX_PATH];

            for (WrapperMap::const_iterator iter = g_allowedWrappersMap.begin();
                 iter != g_allowedWrappersMap.end();
                 ++iter)
            {
                strcpy_s(strPath, PS_MAX_PATH, iter->second.strPluginPath.asCharArray());
                strcpy_s(strName, PS_MAX_PATH, iter->second.strPluginName.asCharArray());
                strcpy_s(strDlls, PS_MAX_PATH, iter->second.strWrappedDll.asCharArray());

                if (smPut("GPS_TO_MDLL", (void*) strPath, PS_MAX_PATH) == false ||
                    smPut("GPS_TO_MDLL", (void*) strName, PS_MAX_PATH) == false ||
                    smPut("GPS_TO_MDLL", (void*) strDlls, PS_MAX_PATH) == false)
                {
                    Log(logERROR, "Couldn't put wrapper info into shared memory.\n");
                    smUnlockPut("GPS_TO_MDLL");
                    return false;
                }
            }

            smUnlockPut("GPS_TO_MDLL");
        }
        else
        {
            Log(logERROR, "There is not enough space in the shared memory for the desired content.\n");
            return false;
        }
    }
    else
    {
        Log(logERROR, "Couldn't create shared memory to pass wrapper registration\n");
        return false;
    }

#else

    for (WrapperMap::const_iterator iter = g_allowedWrappersMap.begin();
         iter != g_allowedWrappersMap.end();
         ++iter)
    {
        // On Linux, Create the shared memory from the PerfStudio server so that
        // it is cleaned up properly.
        if (smCreate(iter->second.strPluginShortDesc.asCharArray(), 100, sizeof(HTTPRequestHeader)) == false)
        {
            Log(logERROR, "Couldn't create shared memory for plugin.\n");
            return false;
        }
    }

#endif // def _WIN32
    return true;
}