c++macos-catalinadriverkitmacos-system-extension

Can `new` and `delete` be used in a DriverKit driver?


DriverKit provides IONewZero and IOSafeDeleteNULL. Those does not call any constructor or destructor.

Let's say that I would like to have some class in the ivars structure. The class does not need to inherit from OSObject nor IOService. How should I construct this object? If I have it as a member in the ivars struct the constructor of my class is not called. If I keep a pointer to my class in the ivars structure I need to allocate and call the constructor of the class. Can I use new / delete for this?


Solution

  • The default operator new is indeed implemented in the DriverKit runtime. I've used it successfully to allocate and initialise my …_IVars objects themselves. (the PIMPL type that's automatically forward-declared by the header generated by iig for any classes defined in .iig files)

    So, I actually do this in MyDriver::init():

        this->ivars = new MyDriver_IVars();
    

    and then in MyDriver::free():

        if (this->ivars != nullptr)
        {
            // … some extra cleanup …
    
            delete this->ivars;
            this->ivars = nullptr;
        }
    

    In my opinion this is about the cleanest approach achievable given the constraints forced upon us by the iig system.

    I strongly suspect operator new is implemented with the same back-end as in regular macOS user space, though I've not actually gone and checked yet as I've not encountered any issues with it at all so far. Obviously, the corresponding delete works too.

    OSTypeAlloc is for OSObject-derived types and should definitely be used for those, but won't work for other types.