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