Re: [OT] 'volatile' in userspace

Theodore Tso
2006-07-10T03:42:59Z

On Sun, Jul 09, 2006 at 10:40:06PM +0200, Rutger Nijlunsing wrote:
> > So if a userspace progam ever uses volatile, it's almost certainly a
> > bug, one way or another.
>
> Without 'volatile' and disabling optimizations altogether, how do we
> prevent gcc from optimizing away pointers? As can be seen on
> http://wiki.rubygarden.org/Ruby/page/show/GCAndExtensions (at
> 'Compiler over-optimisations and "volatile"'), volatile is used to
> prevent a specific type of optimization. This is because of the
> garbage collector, which scans the stack and registers to find
> referenced objects. So you don't want local variables containing
> references to objects optimized away.

Well, if you look at the Wiki, it admits that this is a bug:

(Warning: This section is not strictly correct. volatile
instructs the C compiler that it should not do certain
optimisations to code that accesses the variable - the value
cannot be stored in a register and must be read from memory
each time it is accessed. It is still perfectly legal for the
compiler to overwrite the VALUE's stack location with other
data, if the compiler decides there are no further uses of the
VALUE. Fortunately, a side effect of volatile in common C
compilers like GCC and Visual Studio is to prevent the
dangerous optimisation described above. The Ruby source itself
uses volatile for this purpose, so it is an "accepted hack"
for Ruby C extensions.)

"Accepted hack" is basically another way of saying bug. Some day GCC
will be made smart enough to optimize the use of str on the stack, and
then the Ruby will be screwed. (Mental note to self: don't use Ruby
in any future project.)

This is really an architectural bug. RSTRING() should have explicitly
bumped a use pointer, which the C code should have then explicitly
decremented, to protect the underlying pointer from getting GC'ed
unexpectedly. It would have made RSTRING() more difficult to use, but
that's the price you pay when you try to graft a garbage-collected
paradigm into C code, since the C language really was never designed
for it.

So this would tend to confirm the rule of thumb: use of "volatile" in
a userspace progam tends to indicate a bug.

- Ted