1

As is mentioned in https://www.kernel.org/doc/htmldocs/filesystems/API-d-path.html, the function d_path converts a dentry into an ASCII path name and callers should use the returned pointer.

And I'm trying to resolve the user space filename by the following code (credits to https://stackoverflow.com/a/61504960/10591104):

static inline char* resolve_path(const char __user *filename, int flag) {
    struct path path;
    int dfd = AT_FDCWD;
    char *ret_ptr = NULL;
    int error = -EINVAL;
    unsigned int lookup_flags = 0;
    char *tpath = kmalloc(1024, GFP_KERNEL);
    if ((flag & ~(AT_SYMLINK_NOFOLLOW | AT_NO_AUTOMOUNT)) != 0) {
        goto out;
    }   
    if (!(flag & AT_SYMLINK_NOFOLLOW)) {
        lookup_flags |= LOOKUP_FOLLOW;
    }   

    error = user_path_at(dfd, filename, lookup_flags, &path);
    if (error) {
        goto out;
    }   
    ret_ptr = d_path(&path, tpath, 1024);
    if (IS_ERR(ret_ptr)) {
        goto out;
    }   
    kfree(tpath);
    return ret_ptr;
out:
    kfree(tpath);
    return NULL;
}

My question is, should I free the returned pointer by d_path (i.e. the ret_ptr in the code)? Where is the pointed memory stored? It causes error when I kfree(ret_ptr), so I'm assuming there's no need to free it by myself?

  • 4
    The doc you linked to says that the pointer returned by `d_path` is the pointer to _some_ location within the buffer passed to this function. So, you should not free that pointer, but should free the buffer (if it was allocated dynamically, as it is in your case). But it looks like your code is freeing the buffer prematurely. – tromgy Oct 25 '21 at 16:41
  • @tromgy Oh thanks for the help. It seems you're right. I didn't realize it was stored in the same buffer even if I had read the doc, cause I'm so bad at English XD. And surprisingly the code works with flaw in my case haha. – Porcupine Andrew Oct 25 '21 at 17:01
  • yes the code _might_ work fine until that buffer is suddenly reallocated – tromgy Oct 25 '21 at 17:44

0 Answers0