/* $NetBSD: make_malloc.c,v 1.28 2025/06/29 09:37:58 rillig Exp $ */12/*3* Copyright (c) 2009 The NetBSD Foundation, Inc.4* All rights reserved.5*6* Redistribution and use in source and binary forms, with or without7* modification, are permitted provided that the following conditions8* are met:9* 1. Redistributions of source code must retain the above copyright10* notice, this list of conditions and the following disclaimer.11* 2. Redistributions in binary form must reproduce the above copyright12* notice, this list of conditions and the following disclaimer in the13* documentation and/or other materials provided with the distribution.14*15* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS16* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED17* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR18* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS19* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR20* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF21* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS22* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN23* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)24* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE25* POSSIBILITY OF SUCH DAMAGE.26*/2728#include <errno.h>2930#include "make.h"3132MAKE_RCSID("$NetBSD: make_malloc.c,v 1.28 2025/06/29 09:37:58 rillig Exp $");3334#ifndef USE_EMALLOC3536/* die when out of memory. */37static MAKE_ATTR_DEAD void38enomem(void)39{40(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));41exit(2);42}4344/* malloc, but die on error. */45void *46bmake_malloc(size_t len)47{48void *p;4950if ((p = malloc(len)) == NULL)51enomem();52#ifdef CLEANUP53memset(p, 'Z', len);54#endif55return p;56}5758/* strdup, but die on error. */59char *60bmake_strdup(const char *str)61{62size_t size;63char *p;6465size = strlen(str) + 1;66p = bmake_malloc(size);67return memcpy(p, str, size);68}6970/* Allocate a string starting from str with exactly len characters. */71char *72bmake_strldup(const char *str, size_t len)73{74char *p = bmake_malloc(len + 1);75memcpy(p, str, len);76p[len] = '\0';77return p;78}7980/* realloc, but die on error. */81void *82bmake_realloc(void *ptr, size_t size)83{84if ((ptr = realloc(ptr, size)) == NULL)85enomem();86return ptr;87}88#endif8990/* Allocate a string from start up to but excluding end. */91char *92bmake_strsedup(const char *start, const char *end)93{94return bmake_strldup(start, (size_t)(end - start));95}969798