[Bug 281953] The fmemopen() function in libc/stdio opens a stream for writing even if the stream is specified as read-only

From: <bugzilla-noreply_at_freebsd.org>
Date: Wed, 09 Oct 2024 12:06:42 UTC
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=281953

            Bug ID: 281953
           Summary: The fmemopen() function in libc/stdio opens a stream
                    for writing even if the stream is specified as
                    read-only
           Product: Base System
           Version: 14.1-RELEASE
          Hardware: amd64
                OS: Any
            Status: New
          Severity: Affects Some People
          Priority: ---
         Component: bin
          Assignee: bugs@FreeBSD.org
          Reporter: erkki.moorits@mail.ee
 Attachment #254107 text/plain
         mime type:

Created attachment 254107
  --> https://bugs.freebsd.org/bugzilla/attachment.cgi?id=254107&action=edit
Test code for fmemopen(.., .., "r")

When memory buffer is opened in read-only mode with the fmemopen(.., .., "r")
function, then the stream opened in read-write mode.

Attached test code with this issue report.

Expected result is (this compiled and run on Ubuntu Linux):
buffer before:  'Hello123'
buffer after:   'Hello123'
fprintf result: -1

Test code, compiled and run on FreeBSD 14.1, give following output:
buffer before:  'Hello123'
buffer after:   'test:1'
fprintf result: 6 

Possible cause of this issue are on following lines:
https://cgit.freebsd.org/src/tree/lib/libc/stdio/fmemopen.c#n139

f = funopen(ck,
            flags & O_WRONLY ? NULL : fmemopen_read, 
            flags & O_RDONLY ? NULL : fmemopen_write,
            fmemopen_seek, fmemopen_close);

where 'flags & O_RDONLY' give always result 0; 

But it should be like this (needs testing):
f = funopen(ck,
            (flags & O_ACCMODE) == O_WRONLY ? NULL : fmemopen_read, 
            (flags & O_ACCMODE) == O_RDONLY ? NULL : fmemopen_write,
            fmemopen_seek, fmemopen_close);

Or this (needs testing):
f = funopen(ck,
            rc & __SWR ? NULL : fmemopen_read, 
            rc & __SRD ? NULL : fmemopen_write,
            fmemopen_seek, fmemopen_close);

-- 
You are receiving this mail because:
You are the assignee for the bug.