From ripley at stats.ox.ac.uk  Fri Nov 14 22:02:42 2003
From: ripley at stats.ox.ac.uk (Prof Brian Ripley)
Date: Fri Nov 14 22:01:57 2003
Subject: [Rd] writeChar potential buffer overrun (PR#5090)
In-Reply-To: <20031114193506.7F6C7F0A4@slim.kubism.ku.dk>
Message-ID: <Pine.LNX.4.44.0311142049240.26950-100000@gannet.stats>

Could you please give a reproducible example?

On Fri, 14 Nov 2003 mjw@celos.net wrote:

> Trying to copy the (binary) header of a input file directly
> to an output file, I've had repeatable seg faults.  The call:
> 
>   writeChar(hdr, outfh, nchars=6144)
> 
> when hdr just contains one empty string seems to be the
> culprit.  The stack traces weren't all that illuminating,
> with sig 11 in memory-related functions following this.  But
> in src/main/connections.c it looks like do_writechar doesn't
> check the length of strings when given an explicit nchars
> argument; so I think the strncpy() call will read too far.

All R strings should be null-terminated, so strncpy will only copy the
number of characters present (plus the null terminator) if less than n.

I can see that writeChars might write rubbish out, but not why it should 
segfault.  It is also unclear to me what to do in this case: flag a user 
error?

> [This happened because I didn't remember that R lets null
> terminate strings; so I did a readChar(infh, nchars=6144)
> through some nulls at the start of the header, and ended up
> with a much shorter string than I was expecting.  As far as
> I can tell do_readchar still behaves in these circumstances,
> and in any case I can produce the fault without it.]
> 
> Using readBin and writeBin with integer() and size=1 seems
> to be the solution for header copying, but the faults still
> seemed worth reporting.

It's certainly the documented way.

-- 
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595


[Rd] writeChar potential buffer overrun (PR#5090)
Prof Brian Ripley