Thread (1 message) 1 message, 1 author, 2012-07-07

Re: readdir.3: don't just use pathconf in arithmetic!

From: Michael Kerrisk (man-pages) <hidden>
Date: 2012-07-07 05:44:54

Hello Jan,

(Please CC linux-man with notes such as this.)

On Tue, Jul 3, 2012 at 3:27 AM, Jan Engelhardt [off-list ref] wrote:
In man-pages-3.35's readdir_r(3), this example code is provided:

"""
 Since POSIX.1 does not specify the size of the d_name field, and  other
 nonstandard  fields may precede that field within the dirent structure,
 portable applications that use readdir_r() should allocate  the  buffer
 whose address is passed in entry as follows:

     len = offsetof(struct dirent, d_name) +
               pathconf(dirpath, _PC_NAME_MAX) + 1
     entryp = malloc(len);
"""

I have come to regard this as bad(ly implemented) advice. A project
naïvely copied this snippet and then ran into memory corruption.
I propose:

    long ret = pathconf(dirpath, _PC_NAME_MAX);
    if (ret < 0)
        abort();
    entryp = malloc(offsetof(struct dirent, d_name) +
                 ret + 1);

Because it so happened that the particular project (bindfs) used
a non-existing path and got -1 (with errno==ENOENT), thus
allocating way too few space.
Yes, the page could be better. I applied a somewhat different patch:

[[
--- a/man3/readdir.3
+++ b/man3/readdir.3
@@ -226,8 +226,10 @@ as follows:
 .in +4n
 .nf

-len = offsetof(struct dirent, d_name) +
-          pathconf(dirpath, _PC_NAME_MAX) + 1
+name_max = pathconf(dirpath, _PC_NAME_MAX);
+if (name_max == \-1)        /* Limit not defined, or error */
+    name_max = 255;         /* Take a guess */
+len = offsetof(struct dirent, d_name) + name_max + 1;
 entryp = malloc(len);

 .fi
]]

Okay?
NB: pathconf(3) could document some possible errors.
That's true. Want to send in a patch?

Thanks,

Michael

-- 
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
Author of "The Linux Programming Interface"; http://man7.org/tlpi/
--
To unsubscribe from this list: send the line "unsubscribe linux-man" in
the body of a message to majordomo-u79uwXL29TY76Z2rM5mHXA@public.gmane.org
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Keyboard shortcuts
hback out one level
jnext message in thread
kprevious message in thread
ldrill in
Escclose help / fold thread tree
?toggle this help