Tim Williams
Tim Williams

Reputation: 1

Equivalent pointer probe from MSVC to GCC in a library

First, let me say I'm primarily a Windows developer.

I'm looking at porting some existing code C++ code from Windows+MSVC to Ubuntu+GCC. Part of what I'm porting includes an MSFT-only idiom that I'm not sure how (or if) one can support on GCC. Here is MSVC pseudo-code, simplified and ignoring things like a compiler complaining about initialized-but-not-used variables, or optimizers removing irrelevant code:

bool ProbeIntPointer( int * p )
{
    bool fValid = TRUE;

    __try {
      int x = *p;
    }
    __except( ExecuteHandlerForMemoryAccessFailure() )
    {
        fValid = FALSE;
    }

    return fValid;
}

This works via structured exception handling, an MSVC extension. The deref of *p might fail, but if it does, it generates an exception that is caught and handled by the __except block.

The code being ported is going to be a library, either a static library or a shared object, not sure what's required yet. Therefore, I'm guessing that installing my own signal handler for segfault/bus-error is not really allowed; I think I have to leave that alone for the program that's using my library to control.

Is there any way to do this under these constraints?

Upvotes: 0

Views: 117

Answers (1)

Marcus Müller
Marcus Müller

Reputation: 36319

The code being ported is going to be a library, either a static library or a shared object,

Here's where the buck stops. While other platforms also have handling of segmentation faults, a library can never assume it has the right to install the handler for that. That might (and will) clash with what the application wants to do!

So, nope, this is by design not portable.

Also, if your code needs this, you need to sanitize your code statically, I'd say: you should never end up in a situation where you're not sure whether a pointer is (still? already?) valid!

Upvotes: 1

Related Questions