jcs's openbsd hax
openbsd
1/* $OpenBSD: xmalloc.c,v 1.38 2025/05/23 00:40:45 deraadt Exp $ */
2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * Versions of malloc and friends that check their results, and never return
7 * failure (they call fatal if they encounter an error).
8 *
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
14 */
15
16#include <stdarg.h>
17#include <stdint.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <string.h>
21
22#include "xmalloc.h"
23#include "log.h"
24
25const char * const malloc_options = "S";
26
27void *
28xmalloc(size_t size)
29{
30 void *ptr;
31
32 if (size == 0)
33 fatal("xmalloc: zero size");
34 ptr = malloc(size);
35 if (ptr == NULL)
36 fatal("xmalloc: out of memory (allocating %zu bytes)", size);
37 return ptr;
38}
39
40void *
41xcalloc(size_t nmemb, size_t size)
42{
43 void *ptr;
44
45 if (size == 0 || nmemb == 0)
46 fatal("xcalloc: zero size");
47 if (SIZE_MAX / nmemb < size)
48 fatal("xcalloc: nmemb * size > SIZE_MAX");
49 ptr = calloc(nmemb, size);
50 if (ptr == NULL)
51 fatal("xcalloc: out of memory (allocating %zu bytes)",
52 size * nmemb);
53 return ptr;
54}
55
56void *
57xreallocarray(void *ptr, size_t nmemb, size_t size)
58{
59 void *new_ptr;
60
61 new_ptr = reallocarray(ptr, nmemb, size);
62 if (new_ptr == NULL)
63 fatal("xreallocarray: out of memory (%zu elements of %zu bytes)",
64 nmemb, size);
65 return new_ptr;
66}
67
68void *
69xrecallocarray(void *ptr, size_t onmemb, size_t nmemb, size_t size)
70{
71 void *new_ptr;
72
73 new_ptr = recallocarray(ptr, onmemb, nmemb, size);
74 if (new_ptr == NULL)
75 fatal("xrecallocarray: out of memory (%zu elements of %zu bytes)",
76 nmemb, size);
77 return new_ptr;
78}
79
80char *
81xstrdup(const char *str)
82{
83 size_t len;
84 char *cp;
85
86 len = strlen(str) + 1;
87 cp = xmalloc(len);
88 return memcpy(cp, str, len);
89}
90
91int
92xvasprintf(char **ret, const char *fmt, va_list ap)
93{
94 int i;
95
96 i = vasprintf(ret, fmt, ap);
97 if (i < 0 || *ret == NULL)
98 fatal("xvasprintf: could not allocate memory");
99 return i;
100}
101
102int
103xasprintf(char **ret, const char *fmt, ...)
104{
105 va_list ap;
106 int i;
107
108 va_start(ap, fmt);
109 i = xvasprintf(ret, fmt, ap);
110 va_end(ap);
111 return i;
112}