/***********************************************************************
*                                                                      *
*               This software is part of the ast package               *
*          Copyright (c) 1985-2011 AT&T Intellectual Property          *
*          Copyright (c) 2020-2023 Contributors to ksh 93u+m           *
*                      and is licensed under the                       *
*                 Eclipse Public License, Version 2.0                  *
*                                                                      *
*                A copy of the License is available at                 *
*      https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.html      *
*         (with md5 checksum 84283fa8859daf213bdda5a9f8d1be1d)         *
*                                                                      *
*                 Glenn Fowler <gsf@research.att.com>                  *
*                  David Korn <dgk@research.att.com>                   *
*                   Phong Vo <kpv@research.att.com>                    *
*                  Martijn Dekker <martijn@inlv.org>                   *
*            Johnothan King <johnothanking@protonmail.com>             *
*                                                                      *
***********************************************************************/

/*
 * install error message handler for fatal malloc exceptions
 */

#include <ast.h>
#include <error.h>
#include <vmalloc.h>

#include "FEATURE/vmalloc"

#if _std_malloc

void
memfatal(void)
{
}

#else

/*
 * print message and fail on VM_BADADDR,VM_NOMEM
 */

static int
nomalloc(Vmalloc_t* region, int type, void* obj, Vmdisc_t* disc)
{
	Vmstat_t	st;

	NoP(disc);
	switch (type)
	{
#ifdef VM_BADADDR
	case VM_BADADDR:
		error(ERROR_SYSTEM|ERROR_PANIC, "invalid pointer %p passed to free or realloc", obj);
		UNREACHABLE();
#endif
	case VM_NOMEM:
		vmstat(region, &st);
		error(ERROR_SYSTEM|ERROR_PANIC, "storage allocator out of memory on %lu byte request ( region %lu segments %lu busy %lu:%lu:%lu free %lu:%lu:%lu )", (size_t)obj, st.extent, st.n_seg, st.n_busy, st.s_busy, st.m_busy, st.n_free, st.s_free, st.m_free);
		UNREACHABLE();
	}
	return 0;
}

/*
 * initialize the malloc exception handler
 */

void
memfatal(void)
{
	Vmdisc_t*	disc;

	malloc(0);
	if (disc = vmdisc(Vmregion, NULL))
		disc->exceptf = nomalloc;
}

#endif
