Path: blob/main/sys/contrib/openzfs/lib/libuutil/uu_alloc.c
48378 views
// SPDX-License-Identifier: CDDL-1.01/*2* CDDL HEADER START3*4* The contents of this file are subject to the terms of the5* Common Development and Distribution License (the "License").6* You may not use this file except in compliance with the License.7*8* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE9* or https://opensource.org/licenses/CDDL-1.0.10* See the License for the specific language governing permissions11* and limitations under the License.12*13* When distributing Covered Code, include this CDDL HEADER in each14* file and include the License file at usr/src/OPENSOLARIS.LICENSE.15* If applicable, add the following below this CDDL HEADER, with the16* fields enclosed by brackets "[]" replaced with your own identifying17* information: Portions Copyright [yyyy] [name of copyright owner]18*19* CDDL HEADER END20*/21/*22* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.23*/2425#include "libuutil_common.h"2627#include <stdarg.h>28#include <stdio.h>29#include <stdlib.h>30#include <string.h>3132void *33uu_zalloc(size_t n)34{35void *p = malloc(n);3637if (p == NULL) {38uu_set_error(UU_ERROR_SYSTEM);39return (NULL);40}4142(void) memset(p, 0, n);4344return (p);45}4647void48uu_free(void *p)49{50free(p);51}5253char *54uu_strdup(const char *str)55{56char *buf = NULL;5758if (str != NULL) {59size_t sz;6061sz = strlen(str) + 1;62buf = uu_zalloc(sz);63if (buf != NULL)64(void) memcpy(buf, str, sz);65}66return (buf);67}6869/*70* Duplicate up to n bytes of a string. Kind of sort of like71* strdup(strlcpy(s, n)).72*/73char *74uu_strndup(const char *s, size_t n)75{76size_t len;77char *p;7879len = strnlen(s, n);80p = uu_zalloc(len + 1);81if (p == NULL)82return (NULL);8384if (len > 0)85(void) memcpy(p, s, len);86p[len] = '\0';8788return (p);89}9091/*92* Duplicate a block of memory. Combines malloc with memcpy, much as93* strdup combines malloc, strlen, and strcpy.94*/95void *96uu_memdup(const void *buf, size_t sz)97{98void *p;99100p = uu_zalloc(sz);101if (p == NULL)102return (NULL);103(void) memcpy(p, buf, sz);104return (p);105}106107char *108uu_msprintf(const char *format, ...)109{110va_list args;111char attic[1];112uint_t M, m;113char *b;114115va_start(args, format);116M = vsnprintf(attic, 1, format, args);117va_end(args);118119for (;;) {120m = M;121if ((b = uu_zalloc(m + 1)) == NULL)122return (NULL);123124va_start(args, format);125M = vsnprintf(b, m + 1, format, args);126va_end(args);127128if (M == m)129break; /* sizes match */130131uu_free(b);132}133134return (b);135}136137138