On 2/8/15 2:54 AM, Johannes Pfau wrote:
Am Sat, 07 Feb 2015 15:50:53 -0800
schrieb Andrei Alexandrescu <seewebsiteforem...@erdani.org>:
@trusted int setvbuf(T)(FILE* stream, T[] buf, int mode)
if (is(T == char) || is(T == byte) || is(T == ubyte))
{
      return setvbuf(stream, cast(char*) buf.ptr, mode, buf.length);
}


This can still cause memory corruption if `buf` is GC-allocated. You'd
have to pin the buffer which might not be easy in such a low-level
wrapper. OTOH in a higher level wrapper (std.stdio.File) you can simply
keep a reference to the buffer.

Good point, thanks. Moving GCs didn't occur to me.

@trusted int stat(in char[] name, stat_t* p)
{
      if (isZeroTerminated(name)) return stat(name.ptr, p);

How would you implement `isZeroTerminated` in a memory safe way? We have
exactly the same problem in toStringz and nobody ever came up
with a really safe solution. The best you could do is using special
types for zero-terminated strings but that might be cumbersome to use.

I thought of a few things, nothing is 100% foolproof. But I'm not too worried - many of these functions issue system calls, and the cost of a malloc/free pulse is unlikely to be measurable. With opportunistic use of alloca it gets even better.

      auto t = cast(char*) malloc(name.length + 1);
      scope(exit) free(t);
      memcpy(t, name.ptr, name.length);
      t[name.length] = 0;
      return stat(t, p);
}

Such wrappers would allow safe code to use more C stdlib primitives.
The question is whether these wrappers are worth adding to
core.stdc.stdio.


That's the main question. There's only a limited amount of stdc
functions which can be wrapped in a safe way and std.stdio etc. are
already kind of a safe wrapper. And it's also important to get these
wrappers right and make sure they don't introduce memory safety bugs.

I see it as increased opportunity to rely on simple manually checkable low-level functions, both in Phobos and outside it. It seems there's merit in that.


Andrei

Reply via email to