Re: How to check if a custom class has a private object set?

Mihai Dobrescu <[email protected]> Fri, 16 Dec 2016 00:09:50 -0800 (PST)
Newsgroups gmane.comp.mozilla.devel.jseng
Message-ID <[email protected]>
On Friday, December 16, 2016 at 9:38:38 AM UTC+2, Boris Zbarsky wrote:
> On 12/16/16 2:02 AM, Mihai Dobrescu wrote:
> > Provided JS_GetPrivate returns some known-typed private object and JS_ObjectIsFunction checks if some specific class instance is there, how could I check if simply some object instance is present, regardless the class type?
> 
> JS_GetPrivate returns a void*.  It can be used (with JS_SetPrivate) to 
> store some non-spidermonkey-related data on your object.  So I'm not 
> sure where JS_ObjectIsFunction comes into this.
> 
> In general, if JS_GetPrivate returned something nonzero, that means 
> something was stored with JS_SetPrivate.  I'm not sure whether that 
> answers the question you're trying to ask, though, because I'm not sure 
> what that question is.
> 
> -Boris

Well, I have a case, a custom object. The API it manages has static and instance functions. Sometimes, I need to check if there is an instance or not present in the custom class instance. That's because if I call JS_GetPrivate on a class with JSCLASS_HAS_PRIVATE that has not an instance set (for calling static functions), an assertion fails and breaks the execution in debug, in NativeObject.h:

    inline void*& privateRef(uint32_t nfixed) const { /* XXX should be private, not protected! */
        /*
         * The private pointer of an object can hold any word sized value.
         * Private pointers are stored immediately after the last fixed slot of
         * the object.
         */
        MOZ_ASSERT(nfixed == numFixedSlots());
        MOZ_ASSERT(hasPrivate()); << FAILS HERE
        HeapSlot* end = &fixedSlots()[nfixed];
        return *reinterpret_cast<void**>(end);
    }

I have expected JS_GetPrivate to return as you've said, it probably does in release version, but in debug it fails.

What can I do?