Index: stable/10/lib/libc/stdio/fmemopen.c =================================================================== --- stable/10/lib/libc/stdio/fmemopen.c (revision 277015) +++ stable/10/lib/libc/stdio/fmemopen.c (revision 277016) @@ -1,258 +1,259 @@ /*- * Copyright (C) 2013 Pietro Cerutti * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include "local.h" struct fmemopen_cookie { char *buf; /* pointer to the memory region */ bool own; /* did we allocate the buffer ourselves? */ char bin; /* is this a binary buffer? */ size_t size; /* buffer length in bytes */ size_t len; /* data length in bytes */ size_t off; /* current offset into the buffer */ }; static int fmemopen_read(void *cookie, char *buf, int nbytes); static int fmemopen_write(void *cookie, const char *buf, int nbytes); static fpos_t fmemopen_seek(void *cookie, fpos_t offset, int whence); static int fmemopen_close(void *cookie); FILE * fmemopen(void * __restrict buf, size_t size, const char * __restrict mode) { struct fmemopen_cookie *ck; FILE *f; int flags, rc; /* + * POSIX says we shall return EINVAL if size is 0. + */ + if (size == 0) { + errno = EINVAL; + return (NULL); + } + + /* * Retrieve the flags as used by open(2) from the mode argument, and * validate them. */ rc = __sflags(mode, &flags); if (rc == 0) { errno = EINVAL; return (NULL); } /* * There's no point in requiring an automatically allocated buffer * in write-only mode. */ if (!(flags & O_RDWR) && buf == NULL) { errno = EINVAL; return (NULL); } ck = malloc(sizeof(struct fmemopen_cookie)); if (ck == NULL) { return (NULL); } ck->off = 0; ck->size = size; /* Check whether we have to allocate the buffer ourselves. */ ck->own = ((ck->buf = buf) == NULL); if (ck->own) { ck->buf = malloc(size); if (ck->buf == NULL) { free(ck); return (NULL); } } /* * POSIX distinguishes between w+ and r+, in that w+ is supposed to * truncate the buffer. */ if (ck->own || mode[0] == 'w') { ck->buf[0] = '\0'; } /* Check for binary mode. */ ck->bin = strchr(mode, 'b') != NULL; /* * The size of the current buffer contents is set depending on the * mode: * * for append (text-mode), the position of the first NULL byte, or the * size of the buffer if none is found * * for append (binary-mode), the size of the buffer * * for read, the size of the buffer * * for write, 0 */ switch (mode[0]) { case 'a': - if (ck->bin) { - /* - * This isn't useful, since the buffer isn't allowed - * to grow. - */ - ck->off = ck->len = size; - } else - ck->off = ck->len = strnlen(ck->buf, ck->size); + ck->off = ck->len = strnlen(ck->buf, ck->size); break; case 'r': ck->len = size; break; case 'w': ck->len = 0; break; } f = funopen(ck, flags & O_WRONLY ? NULL : fmemopen_read, flags & O_RDONLY ? NULL : fmemopen_write, fmemopen_seek, fmemopen_close); if (f == NULL) { if (ck->own) free(ck->buf); free(ck); return (NULL); } /* * Turn off buffering, so a write past the end of the buffer * correctly returns a short object count. */ setvbuf(f, NULL, _IONBF, 0); return (f); } static int fmemopen_read(void *cookie, char *buf, int nbytes) { struct fmemopen_cookie *ck = cookie; if (nbytes > ck->len - ck->off) nbytes = ck->len - ck->off; if (nbytes == 0) return (0); memcpy(buf, ck->buf + ck->off, nbytes); ck->off += nbytes; return (nbytes); } static int fmemopen_write(void *cookie, const char *buf, int nbytes) { struct fmemopen_cookie *ck = cookie; if (nbytes > ck->size - ck->off) nbytes = ck->size - ck->off; if (nbytes == 0) return (0); memcpy(ck->buf + ck->off, buf, nbytes); ck->off += nbytes; if (ck->off > ck->len) ck->len = ck->off; /* * We append a NULL byte if all these conditions are met: * - the buffer is not binary * - the buffer is not full * - the data just written doesn't already end with a NULL byte */ if (!ck->bin && ck->off < ck->size && ck->buf[ck->off - 1] != '\0') ck->buf[ck->off] = '\0'; return (nbytes); } static fpos_t fmemopen_seek(void *cookie, fpos_t offset, int whence) { struct fmemopen_cookie *ck = cookie; switch (whence) { case SEEK_SET: if (offset > ck->size) { errno = EINVAL; return (-1); } ck->off = offset; break; case SEEK_CUR: if (ck->off + offset > ck->size) { errno = EINVAL; return (-1); } ck->off += offset; break; case SEEK_END: if (offset > 0 || -offset > ck->len) { errno = EINVAL; return (-1); } ck->off = ck->len + offset; break; default: errno = EINVAL; return (-1); } return (ck->off); } static int fmemopen_close(void *cookie) { struct fmemopen_cookie *ck = cookie; if (ck->own) free(ck->buf); free(ck); return (0); } Index: stable/10/lib/libc/stdio/fopen.3 =================================================================== --- stable/10/lib/libc/stdio/fopen.3 (revision 277015) +++ stable/10/lib/libc/stdio/fopen.3 (revision 277016) @@ -1,338 +1,347 @@ .\" Copyright (c) 1990, 1991, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" This code is derived from software contributed to Berkeley by .\" Chris Torek and the American National Standards Committee X3, .\" on Information Processing Systems. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 4. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" @(#)fopen.3 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" .Dd January 30, 2013 .Dt FOPEN 3 .Os .Sh NAME .Nm fopen , .Nm fdopen , .Nm freopen , .Nm fmemopen .Nd stream open functions .Sh LIBRARY .Lb libc .Sh SYNOPSIS .In stdio.h .Ft FILE * .Fn fopen "const char * restrict path" "const char * restrict mode" .Ft FILE * .Fn fdopen "int fildes" "const char *mode" .Ft FILE * .Fn freopen "const char *path" "const char *mode" "FILE *stream" .Ft FILE * .Fn fmemopen "void *restrict *buf" "size_t size" "const char * restrict mode" .Sh DESCRIPTION The .Fn fopen function opens the file whose name is the string pointed to by .Fa path and associates a stream with it. .Pp The argument .Fa mode points to a string beginning with one of the following letters: .Bl -tag -width indent .It Dq Li r Open for reading. The stream is positioned at the beginning of the file. Fail if the file does not exist. .It Dq Li w Open for writing. The stream is positioned at the beginning of the file. Create the file if it does not exist. .It Dq Li a Open for writing. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening .Xr fseek 3 or similar. Create the file if it does not exist. .El .Pp An optional .Dq Li + following .Dq Li r , .Dq Li w , or .Dq Li a opens the file for both reading and writing. An optional .Dq Li x following .Dq Li w or .Dq Li w+ causes the .Fn fopen call to fail if the file already exists. An optional .Dq Li e following the above causes the .Fn fopen call to set the .Dv FD_CLOEXEC flag on the underlying file descriptor. .Pp The .Fa mode string can also include the letter .Dq Li b after either the .Dq Li + or the first letter. This is strictly for compatibility with .St -isoC and has effect only for .Fn fmemopen ; otherwise the ``b'' is ignored. .Pp Any created files will have mode .Do Dv S_IRUSR \&| .Dv S_IWUSR \&| .Dv S_IRGRP \&| .Dv S_IWGRP \&| .Dv S_IROTH \&| .Dv S_IWOTH Dc .Pq Li 0666 , as modified by the process' umask value (see .Xr umask 2 ) . .Pp Reads and writes may be intermixed on read/write streams in any order, and do not require an intermediate seek as in previous versions of .Em stdio . This is not portable to other systems, however; .Tn ANSI C requires that a file positioning function intervene between output and input, unless an input operation encounters end-of-file. .Pp The .Fn fdopen function associates a stream with the existing file descriptor, .Fa fildes . The mode of the stream must be compatible with the mode of the file descriptor. The .Dq Li x mode option is ignored. If the .Dq Li e mode option is present, the .Dv FD_CLOEXEC flag is set, otherwise it remains unchanged. When the stream is closed via .Xr fclose 3 , .Fa fildes is closed also. .Pp The .Fn freopen function opens the file whose name is the string pointed to by .Fa path and associates the stream pointed to by .Fa stream with it. The original stream (if it exists) is closed. The .Fa mode argument is used just as in the .Fn fopen function. .Pp If the .Fa path argument is .Dv NULL , .Fn freopen attempts to re-open the file associated with .Fa stream with a new mode. The new mode must be compatible with the mode that the stream was originally opened with: Streams open for reading can only be re-opened for reading, streams open for writing can only be re-opened for writing, and streams open for reading and writing can be re-opened in any mode. The .Dq Li x mode option is not meaningful in this context. .Pp The primary use of the .Fn freopen function is to change the file associated with a standard text stream .Dv ( stderr , stdin , or .Dv stdout ) . .Pp The .Fn fmemopen function associates the buffer given by the .Fa buf and .Fa size arguments with a stream. The .Fa buf argument is either a null pointer or point to a buffer that is at least .Fa size bytes long. If a null pointer is specified as the .Fa buf argument, .Fn fmemopen allocates .Fa size bytes of memory. This buffer is automatically freed when the stream is closed. Buffers can be opened in text-mode (default) or binary-mode (if ``b'' is present in the second or third position of the .Fa mode argument). Buffers opened in text-mode make sure that writes are terminated with a NULL byte, if the last write hasn't filled up the whole buffer. Buffers opened in binary-mode never append a NULL byte. .Sh RETURN VALUES Upon successful completion .Fn fopen , .Fn fdopen and .Fn freopen return a .Tn FILE pointer. Otherwise, .Dv NULL is returned and the global variable .Va errno is set to indicate the error. .Sh ERRORS .Bl -tag -width Er .It Bq Er EINVAL The .Fa mode argument to .Fn fopen , .Fn fdopen , .Fn freopen , or .Fn fmemopen was invalid. .El .Pp The .Fn fopen , .Fn fdopen , .Fn freopen and .Fn fmemopen functions may also fail and set .Va errno for any of the errors specified for the routine .Xr malloc 3 . .Pp The .Fn fopen function may also fail and set .Va errno for any of the errors specified for the routine .Xr open 2 . .Pp The .Fn fdopen function may also fail and set .Va errno for any of the errors specified for the routine .Xr fcntl 2 . .Pp The .Fn freopen function may also fail and set .Va errno for any of the errors specified for the routines .Xr open 2 , .Xr fclose 3 and .Xr fflush 3 . +.Pp +The +.Fn fmemopen +function +may also fail and set +.Va errno +if the +.Fa size +argument is 0. .Sh SEE ALSO .Xr open 2 , .Xr fclose 3 , .Xr fileno 3 , .Xr fseek 3 , .Xr funopen 3 .Sh STANDARDS The .Fn fopen and .Fn freopen functions conform to .St -isoC , with the exception of the .Dq Li x mode option which conforms to .St -isoC-2011 . The .Fn fdopen function conforms to .St -p1003.1-88 . The .Dq Li e mode option does not conform to any standard but is also supported by glibc. The .Fn fmemopen function conforms to .St -p1003.1-2008 . The ``b'' mode does not conform to any standard but is also supported by glibc. Index: stable/10/tools/regression/lib/libc/stdio/test-fmemopen.c =================================================================== --- stable/10/tools/regression/lib/libc/stdio/test-fmemopen.c (revision 277015) +++ stable/10/tools/regression/lib/libc/stdio/test-fmemopen.c (revision 277016) @@ -1,252 +1,299 @@ /*- Copyright (C) 2013 Pietro Cerutti Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * Test basic FILE * functions (fread, fwrite, fseek, fclose) against * a FILE * retrieved using fmemopen() */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include void test_preexisting() { /* * Use a pre-existing buffer. */ char buf[512]; char buf2[512]; char str[] = "Test writing some stuff"; char str2[] = "AAAAAAAAA"; char str3[] = "AAAA writing some stuff"; FILE *fp; size_t nofw, nofr; int rc; /* Open a FILE * using fmemopen. */ fp = fmemopen(buf, sizeof(buf), "w"); assert(fp != NULL); /* Write to the buffer. */ nofw = fwrite(str, 1, sizeof(str), fp); assert(nofw == sizeof(str)); /* Close the FILE *. */ rc = fclose(fp); assert(rc == 0); /* Re-open the FILE * to read back the data. */ fp = fmemopen(buf, sizeof(buf), "r"); assert(fp != NULL); /* Read from the buffer. */ bzero(buf2, sizeof(buf2)); nofr = fread(buf2, 1, sizeof(buf2), fp); assert(nofr == sizeof(buf2)); /* * Since a write on a FILE * retrieved by fmemopen * will add a '\0' (if there's space), we can check * the strings for equality. */ assert(strcmp(str, buf2) == 0); /* Close the FILE *. */ rc = fclose(fp); assert(rc == 0); /* Now open a FILE * on the first 4 bytes of the string. */ fp = fmemopen(str, 4, "w"); assert(fp != NULL); /* * Try to write more bytes than we shoud, we'll get a short count (4). */ nofw = fwrite(str2, 1, sizeof(str2), fp); assert(nofw == 4); /* Close the FILE *. */ rc = fclose(fp); /* Check that the string was not modified after the first 4 bytes. */ assert(strcmp(str, str3) == 0); } void test_autoalloc() { /* * Let fmemopen allocate the buffer. */ char str[] = "A quick test"; FILE *fp; long pos; size_t nofw, nofr, i; int rc; /* Open a FILE * using fmemopen. */ fp = fmemopen(NULL, 512, "w+"); assert(fp != NULL); /* fill the buffer */ for (i = 0; i < 512; i++) { nofw = fwrite("a", 1, 1, fp); assert(nofw == 1); } /* Get the current position into the stream. */ pos = ftell(fp); assert(pos == 512); /* * Try to write past the end, we should get a short object count (0) */ nofw = fwrite("a", 1, 1, fp); assert(nofw == 0); /* Close the FILE *. */ rc = fclose(fp); assert(rc == 0); + + /* Open a FILE * using a wrong mode */ + fp = fmemopen(NULL, 512, "r"); + assert(fp == NULL); + + fp = fmemopen(NULL, 512, "w"); + assert(fp == NULL); } void test_data_length() { /* * Here we test that a read operation doesn't go past the end of the * data actually written, and that a SEEK_END seeks from the end of the * data, not of the whole buffer. */ FILE *fp; char buf[512] = {'\0'}; char str[] = "Test data length. "; char str2[] = "Do we have two sentences?"; char str3[sizeof(str) + sizeof(str2) -1]; long pos; size_t nofw, nofr; int rc; /* Open a FILE * for updating our buffer. */ fp = fmemopen(buf, sizeof(buf), "w+"); assert(fp != NULL); /* Write our string into the buffer. */ nofw = fwrite(str, 1, sizeof(str), fp); assert(nofw == sizeof(str)); /* * Now seek to the end and check that ftell * gives us sizeof(str). */ rc = fseek(fp, 0, SEEK_END); assert(rc == 0); pos = ftell(fp); assert(pos == sizeof(str)); /* Close the FILE *. */ rc = fclose(fp); assert(rc == 0); /* Reopen the buffer for appending. */ fp = fmemopen(buf, sizeof(buf), "a+"); assert(fp != NULL); /* We should now be writing after the first string. */ nofw = fwrite(str2, 1, sizeof(str2), fp); assert(nofw == sizeof(str2)); /* Rewind the FILE *. */ rc = fseek(fp, 0, SEEK_SET); assert(rc == 0); /* Make sure we're at the beginning. */ pos = ftell(fp); assert(pos == 0); /* Read the whole buffer. */ nofr = fread(str3, 1, sizeof(buf), fp); assert(nofr == sizeof(str3)); /* Make sure the two strings are there. */ assert(strncmp(str3, str, sizeof(str) - 1) == 0); assert(strncmp(str3 + sizeof(str) - 1, str2, sizeof(str2)) == 0); /* Close the FILE *. */ rc = fclose(fp); assert(rc == 0); } void test_binary() { /* * Make sure that NULL bytes are never appended when opening a buffer * in binary mode. */ FILE *fp; char buf[20]; char str[] = "Test"; size_t nofw; int rc, i; /* Pre-fill the buffer. */ memset(buf, 'A', sizeof(buf)); /* Open a FILE * in binary mode. */ fp = fmemopen(buf, sizeof(buf), "w+b"); assert(fp != NULL); /* Write some data into it. */ nofw = fwrite(str, 1, strlen(str), fp); assert(nofw == strlen(str)); /* Make sure that the buffer doesn't contain any NULL bytes. */ for (i = 0; i < sizeof(buf); i++) assert(buf[i] != '\0'); /* Close the FILE *. */ rc = fclose(fp); assert(rc == 0); } +void +test_append_binary_pos() +{ + /* + * For compatibility with other implementations (glibc), we set the + * position to 0 when opening an automatically allocated binary stream + * for appending. + */ + + FILE *fp; + + fp = fmemopen(NULL, 16, "ab+"); + assert(ftell(fp) == 0L); + fclose(fp); + + /* + * Make sure that a pre-allocated buffer behaves correctly. + */ + char buf[] = "Hello"; + fp = fmemopen(buf, sizeof(buf), "ab+"); + assert(ftell(fp) == 5); + fclose(fp); +} + +void +test_size_0() +{ + /* + * POSIX mandates that we return EINVAL if size is 0 + */ + + FILE *fp; + + fp = fmemopen(NULL, 0, "r+"); + assert(fp == NULL); + assert(errno == EINVAL); +} + int main(void) { test_autoalloc(); test_preexisting(); test_data_length(); test_binary(); + test_append_binary_pos(); + test_size_0(); return (0); } Index: stable/10 =================================================================== --- stable/10 (revision 277015) +++ stable/10 (revision 277016) Property changes on: stable/10 ___________________________________________________________________ Modified: svn:mergeinfo ## -0,0 +0,1 ## Merged /head:r266971