views:

37

answers:

1

Hi,

I've finished my NPAPI plug-in and it works great in Google Chrome but there's a strange problem. The problem is that I've coded a method in the plug-in that returns a string to the browser. In order to do so, you have to allocate a memory in the browser and copy the resulting string to it. Something like:

bool
ScriptablePluginObject::Invoke(NPIdentifier name, const NPVariant *args,
                               uint32_t argCount, NPVariant *result)
{
    if (name == sMethod_id) {
  ...

  //free the memory if it is already allocated
  if (m_pPtr) NPN_MemFree(m_pPtr);

  //allocate the string in the browser memory
  m_pPtr = (char*)NPN_MemAlloc(size+1);
  SecureZeroMemory(m_pPtr, size+1);
  memcpy(m_pATR, string, size);

  //send result to browser
  STRINGZ_TO_NPVARIANT(m_pPtr, *result);

  return true;
 }
  ...

}

Note that 'm_pPtr' is a data member of the class and is initialized to NULL upon construction. The problem occurs when I call this method twice from Google Chrome. The first time it works great. From the second time and so on, it returns a garbage value displayed 'X' in the browser. I've tested the same plug-in in Firefox and it works fine and returns the correct value no matter how many times I call the method. But when I close the page which loaded the plug-in, then Firefox crashes.

Any pointers to what happens in this strange situation is appreciated. I'm working on it and will update the thread once I reach any useful information.

Thanks, Saleh

+1  A: 

You need to remove the following line:

if (m_pPtr) NPN_MemFree(m_pPtr);

You are returning the string to the script and the caller (in this case the browsers JavaScript engine) owns it.

If you free it this leads to undefined behaviour as the memory could still be in use or already re-used or freed by the browser.

Georg Fritzsche
This is definitely the problem. For more info, read up on Memory Management in NPAPI: http://colonelpanic.net/2009/12/memory-management-in-npapi/
Taxilian