Subject: Re: [PATCH] test-lib.sh: Use GLIBC_TUNABLES instead of MALLOC_CHECK_ on glibc >= 2.34

From: Junio C Hamano <[email-masked]>
Date: Mon, 28 Feb 2022 11:13:40 -0800

Elia Pinto <[email-masked]> writes:

> In glibc >= 2.34 MALLOC_CHECK_ and MALLOC_PERTURB_ environment
> variables have been replaced by GLIBC_TUNABLES.  Also the new

Does it hurt to have these older environment variables?  If not,
we would prefer to see redundant but less deeply indented code,
I would imagine.

> +	if type -p getconf >/dev/null 2>&1; then
> +		_GLIBC_VERSION="$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{ print $2 }')"
> +		if [ -n "$_GLIBC_VERSION" -a $(expr "$_GLIBC_VERSION" \>= "2.34") ]; then
> +			_HAVE_GLIBC_234="yes"
> +		fi
> +	fi

Style.  We prefer "test ..." over "[ ... ]" and more importantly we
don't use "test X -a Y".

Do we absolutely need "test -p getconf" with an extra indentation?
I suspect we don't.

	if _GLIBC_VERSION=$(getconf GNU_LIBC_VERSION 2>/dev/null) &&
	   _GLIBC_VERSION=${_GLIBC_VERSION#"glibc "} &&
	   test 2.34 \<= "$_GLIBC_VERSION"
	then
		USE_GLIBC_TUNABLES=YesPlease
	fi

perhaps?  I am not sure if glibc 2.4 still matters, getconf reports
it as 2.04 or 2.4, for the above comparison to be OK, though.

In any case, HAVE_GLIBC_234 is a horrible variable name to use for
this purpose, as the primary thing the two use sites care about is
not the version but if they should use the GLIBC_TUNABLES mechanism,
so it would be better to name the variable after the feature.

>  	setup_malloc_check () {
> -		MALLOC_CHECK_=3	MALLOC_PERTURB_=165
> -		export MALLOC_CHECK_ MALLOC_PERTURB_
> +			if test "x$_HAVE_GLIBC_234" = xyes ; then
> +				LD_PRELOAD="libc_malloc_debug.so.0" GLIBC_TUNABLES="glibc.malloc.check=1:glibc.malloc.perturb=165"
> +				export LD_PRELOAD GLIBC_TUNABLES
> +			else
> +				MALLOC_CHECK_=3	MALLOC_PERTURB_=165
> +				export MALLOC_CHECK_ MALLOC_PERTURB_
> +			fi

Avoid overly long lines when you can easily do so.

		MALLOC_CHECK_=3	MALLOC_PERTURB_=165
		export MALLOC_CHECK_ MALLOC_PERTURB_
+		case "$USE_GLIBC_TUNABLES" in
+		YesPlease)
+			g=
+			LD_PRELOAD=libc_malloc_debug.so.0
+			for t in \
+				glibc.malloc.check=1 \
+				glibc.malloc.perturb=165 \
+			do
+				g="$g${g:+:}$t"
+			done
+			GLIBC_TUNABLES=$g
+			;;
+		esac

perhaps?

>  	}
>  	teardown_malloc_check () {
> -		unset MALLOC_CHECK_ MALLOC_PERTURB_
> +			if test "x$_HAVE_GLIBC_234" = xyes ; then
> +				unset LD_PRELOAD GLIBC_TUNABLES
> +			else
> +				unset MALLOC_CHECK_ MALLOC_PERTURB_
> +			fi

Similarly.

>  	}
>  fi