As part of the core MediaScript project, we end up revealing some pointers from behind the scenes C code to the client programmer, who is programming in Scheme. For example, we may give the client a pointer to a GtkTextBuffer, so that she can write things like
(gtk-text-buffer-append LOG-BUFFER "Hello")
Within Scheme, the pointers get treated as integers.
One problem with this approach is that the client programmer can type in
any integer and we need to figure out whether or not it's a reasonable integer. (Yeah, that's a good excuse for doing some sensible wrapping, but, hey, I"m lazy.) For example, the client might write
(gtk-text-buffer-append 23 "Hello")
So, we need a way (in C) to check whether this integer value can reasonably be interpreted as a pointer to a particular type of datum. The second half of the predicate isn't bad, because GObjects typically provide reasonable predicates, such as
GTK_IS_TEXT_BUFFER. Unfortunately, these only work correctly if they are given valid pointers (that is, things that can be safely dereferenced).
So, I was asking myself
How do I determine if a pointer can be safely dereferenced? As far as I can tell, there are a few basic options:
- Write your own memory management system, and use the information from that system to determine whether something you've allocated is still allocated.
- Determine the layout of memory, and check whether the value falls in the heap or on the stack. There are some tips for doing this somewhere on the Web, but they generally require that you run code at the start of a program.
- Try dereferencing the pointer, and set up a SIGSEG handler.
As you can guess, I went for the third option. Of course, it's supposed to be dangerous to restart after a SIGSEG, but, hey, this seems to be a pretty safe one. The best part was finding a way to return false (0) after the SIGSEG, but that's what gotos are for.
So, here's what I've come up with.
/**
* pointer-hack.c
* A hack that we use to determine whether a pointer can be safely
* dereferenced.
*
* Background: At times, we have something that *appears* to be a pointer,
* but which may not be a pointer. Most typically, this happens when
* we've converted a pointer to an integer for sending to a language
* module (e.g., Scheme), and the language can potentially pass back
* something else. If we have a valid pointer, in many cases, we can
* use the GObject type predicates to check that it's the right type.
* However, those predicates will cause a segfault if the pointer cannot
* be dereferenced. This module provides one procedure,
* gpointer_can_deref (gpointer p),
* that checks whether we can safely derefence the pointer.
*
* Copyright (c) 2008-2009 Samuel A. Rebelsky
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
// +-------+----------------------------------------------------------
// | Notes |
// +-------+
/*
There are a few possible strategies that one can use to determine whether
a pointer can be safely dereferenced. One is to figure out the structure
of memory - anything on the stack or the heap can be derefenced.
This code takes a more straightforward, but potentially dangerous, approach:
It sets up a signal handler for a segmentation fault, tries to dereference the
pointer, and, if it gets a segmentation fault, reports that the pointer cannot
be dereferenced.
Unfortunately, the signal handling standard suggests that it can be dangerous
to continue executing after a segmentation fault. Since we've tried to limit
the effects of the segfault, things *should* be safe.
Note that we recover from the segmentation fault by using setjmp/longjmp. That
is, prior to the attempt to dereference, we set a goto point with setjmp. The
segfault signal handler then does a longjmp back to that point (otherwise, we
seem to get into a loop of segfaults).
*/
// +---------+--------------------------------------------------------
// | Headers |
// +---------+
#include <signal.h>
#include <setjmp.h>
#include <gtk/gtk.h>
// +---------+--------------------------------------------------------
// | Globals |
// +---------+
/**
* A stored location for setjmp/longjmp.
*/
static jmp_buf jmploc;
/**
* A pointer, converted to an integer. (Exists mostly so that
* the optimizer won't attempt to elide the dereference.)
*/
int dereferenced;
// +-----------------+------------------------------------------------
// | Local Functions |
// +-----------------+
/**
* A signal handler for a segmentation fault.
*/
static void
temp_segv_handler (int i)
{
longjmp (jmploc, i);
} // temp_segv_handler
// +--------------------+---------------------------------------------
// | Exported Functions |
// +--------------------+
/**
* Determine if it is safe to dereference a pointer (that is,
* it doesn't throw a SIGSEGV when we dereference it).
*/
gboolean
gpointer_can_deref (gpointer ptr)
{
// Assume we can dereference the pointer
gboolean ok = TRUE;
// Temporary replace the segfault handler.
gpointer segv_handler = signal (SIGSEGV, temp_segv_handler);
// Prepare for error handling
if (! setjmp (jmploc))
{
// Attempt to dereference the pointer.
dereferenced = *((int *) ptr);
}
else
{
// Whoops! We go here through the longjmp in the segv handler.
// That means the dereference failed.
ok = FALSE;
}
// Restore the segfault handler
signal (SIGSEGV, segv_handler);
// And we're done
return ok;
} // gpointer_can_deref
Beautiful, isn't it? Well, I like it.