Skip to contentSkip to conversation

SAFE_READLINK() should return zero-terminated target buffer

PATCH New Helge Deller 2 participants 2 messages May 9, 2017 – May 10, 2017 Library code

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 SAFE_READLINK() should return zero-terminated target buffer

According to the man(2) page of readlink(), a null byte is not appended to the target buffer. So applications need to make sure that the target buffer is zero-initialized, otherwise random bytes at the end of the returned string may exist.

Currently all users of SAFE_READLINK() get it wrong. This include the openat03, getcwd03 and open14 testcases which pass a temporary, un-initialized on-stack buffer to readlink().

This patch fixes SAFE_READLINK to always return a zero-terminated string and thus fixes the the failure of getcwd03 on the hppa/parisc architecture (and probably others).

--
Changes in v2 patch:
- dron't append NUL when tst_brkm() will be called later on.
- changed setting NUL from 0 to '\0'

lib/safe_macros.c +7 -0
index bffc5a1..a6b4ff7 100644
@@ -411,6 +411,13 @@ ssize_t safe_readlink(const char *file, const int lineno,
 		tst_brkm(TBROK | TERRNO, cleanup_fn,
 			 "%s:%d: readlink(%s,%p,%zu) failed",
 			 file, lineno, path, buf, bufsize);
+	} else {
+		/* readlink does not append a NUL byte to the buffer.
+		 * Add it now. */
+		if ((size_t) rval < bufsize)
+			buf[rval] = '\0';
+		else
+			buf[bufsize-1] = '\0';
 	}
 
 	return rval;