[LTP] [PATCH v2 1/2] lib: Validate sysconf() return values in the safe wrapper

Wenyuan Li 2063309626@qq.com
Wed Nov 4 12:00:20 CET 2026


sysconf() returns -1 either on error (with errno set) or to signal that
the queried option has no definite limit. Any value below -1 is not a
legal return value, so report it as a test environment error instead of
handing it back to the caller unchecked.

For _SC_PAGESIZE also reject values that cannot describe a page size:
-1 without errno (this name has no "indeterminate limit" semantics), 0,
and values that are not a power of two. The generic -1 && !errno path is
deliberately left as TINFO because it is valid for other names such as
_SC_OPEN_MAX.

Audited all 49 SAFE_SYSCONF() call sites in the tree:

  _SC_PAGESIZE            32
  _SC_PAGE_SIZE            7   (glibc alias of _SC_PAGESIZE)
  _SC_CLK_TCK              4
  _SC_OPEN_MAX             3
  _SC_NPROCESSORS_CONF     2
  _SC_NPROCESSORS_ONLN     1

None of them relies on a value below -1 and none expects _SC_PAGESIZE
to be indeterminate, so the new checks only fire on a broken test
environment. The three _SC_OPEN_MAX callers, e.g. the loop bound in
tst_ns_create.c, are exactly why the generic -1 && !errno branch must
stay untouched.

Suggested-by: Cyril Hrubis <chrubis@suse.cz>
Signed-off-by: Wenyuan Li <2063309626@qq.com>
---
 lib/safe_macros.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/lib/safe_macros.c b/lib/safe_macros.c
index 187550041..40c5f292f 100644
--- a/lib/safe_macros.c
+++ b/lib/safe_macros.c
@@ -700,6 +700,26 @@ long safe_sysconf(const char *file, const int lineno,
 		}
 	}
 
+	if (rval < -1)
+		tst_brkm_(file, lineno, TBROK, cleanup_fn,
+			"sysconf(%d) returned invalid value %ld", name, rval);
+
+	if (name == _SC_PAGESIZE) {
+		/* A -1 with errno set was already reported above. */
+		if (rval == -1)
+			tst_brkm_(file, lineno, TBROK, cleanup_fn,
+				"sysconf(_SC_PAGESIZE) returned -1 without errno");
+
+		if (!rval)
+			tst_brkm_(file, lineno, TBROK, cleanup_fn,
+				"sysconf(_SC_PAGESIZE) returned 0");
+
+		if (rval > 0 && (rval & (rval - 1)))
+			tst_brkm_(file, lineno, TBROK, cleanup_fn,
+				"sysconf(_SC_PAGESIZE) returned %ld, expected a power of two",
+				rval);
+	}
+
 	return rval;
 }
 
-- 
2.43.0



More information about the ltp mailing list