Fix buffer overflow in print_result() function

From man page: "The functions snprintf() and vsnprintf() do not write
more than size bytes (including the terminating null byte ('\0')). If
the output was truncated due to this limit, then the return value is the
number of characters (excluding the terminating null byte) which would
have been written to the final string if enough space had been
available. Thus, a return value of `size` or more means that the output
was truncated."

The return value is not checked and blindly subtracted from available
space in the buffer which may cause negative values (which are then
converted to unsigned type size_t) in case the variables to print don't
fit into buffer. The pointer to buffer is also moved forward the same
amount, and writing into memory that is not allocated causes unexpected
failures of tests with segfaults.

This was discovered during rewriting of mtest06/mmap1 testcase to new
library where verbose output tried to print out memory contents longer
than space available in the buffer. The framework should be robust
enough to handle these situations.

Signed-off-by: Veronika Kabatova <vkabatov@redhat.com>
Signed-off-by: Cyril Hrubis <chrubis@suse.cz>
diff --git a/lib/tst_test.c b/lib/tst_test.c
index c8baf2a..e7b9cdd 100644
--- a/lib/tst_test.c
+++ b/lib/tst_test.c
@@ -180,7 +180,7 @@
 {
 	char buf[1024];
 	char *str = buf;
-	int ret, size = sizeof(buf);
+	int ret, size = sizeof(buf), ssize;
 	const char *str_errno = NULL;
 	const char *res;
 
@@ -226,14 +226,21 @@
 	str += ret;
 	size -= ret;
 
+	ssize = size - 2;
 	ret = vsnprintf(str, size, fmt, va);
-	str += ret;
-	size -= ret;
-
-	if (str_errno) {
+	str += MIN(ret, ssize);
+	size -= MIN(ret, ssize);
+	if (ret >= ssize) {
+		tst_res_(file, lineno, TWARN,
+				"Next message is too long and truncated:");
+	} else if (str_errno) {
+		ssize = size - 2;
 		ret = snprintf(str, size, ": %s", str_errno);
-		str += ret;
-		size -= ret;
+		str += MIN(ret, ssize);
+		size -= MIN(ret, ssize);
+		if (ret >= ssize)
+			tst_res_(file, lineno, TWARN,
+				"Next message is too long and truncated:");
 	}
 
 	snprintf(str, size, "\n");