--- stdlib/canonicalize.c	2018-01-05 07:28:38.000000000 +0000
+++ stdlib/canonicalize.c	2018-01-05 14:06:22.000000000 +0000
@@ -91,6 +91,11 @@
 	  goto error;
 	}
       dest = __rawmemchr (rpath, '\0');
+/* If path is empty, kernel failed in some ugly way. Realpath
+has no error code for that, so die here. Otherwise search later
+on would cause an underrun when getcwd() returns an empty string.
+Thanks Willy Tarreau for pointing that out. */
+      assert (dest != rpath);
     }
   else
     {
@@ -118,8 +123,17 @@
       else if (end - start == 2 && start[0] == '.' && start[1] == '.')
 	{
 	  /* Back up to previous component, ignore if at root already.  */
-	  if (dest > rpath + 1)
-	    while ((--dest)[-1] != '/');
+	  dest--;
+	  while ((dest != rpath) && (*--dest != '/'));
+	  if ((dest == rpath) && (*dest != '/') {
+	    /* Return EACCES to stay compliant to current documentation:
+	    "Read or search permission was denied for a component of the
+	    path prefix." Unreachable root directories should not be
+	    accessed, see https://www.halfdog.net/Security/2017/LibcRealpathBufferUnderflow/ */
+	    __set_errno (EACCES);
+	    goto error;
+	  }
+	  dest++;
 	}
       else
 	{
