1 /*
   2  * This file and its contents are supplied under the terms of the
   3  * Common Development and Distribution License ("CDDL"), version 1.0.
   4  * You may only use this file in accordance with the terms of version
   5  * 1.0 of the CDDL.
   6  *
   7  * A full copy of the text of the CDDL should have accompanied this
   8  * source.  A copy of the CDDL is also available via the Internet at
   9  * http://www.illumos.org/license/CDDL.
  10  */
  11 
  12 /*
  13  * Copyright 2017 Jason King
  14  */
  15 
  16 #include <sys/debug.h>
  17 #include <stdlib.h>
  18 #include <string.h>
  19 #include "sysdemangle.h"
  20 #include "sysdemangle_int.h"
  21 
  22 void *
  23 zalloc(sysdem_ops_t *ops, size_t len)
  24 {
  25         void *p = ops->alloc(len);
  26 
  27         if (p != NULL)
  28                 (void) memset(p, 0, len);
  29 
  30 #ifdef DEBUG
  31         /*
  32          * In normal operation, we should never exhaust memory.  Either
  33          * something's wrong, or the system is so hosed that aborting
  34          * shouldn't hurt anything, and it gives us a more useful stack
  35          * trace.
  36          */
  37         if (p == NULL)
  38                 abort();
  39 #endif
  40 
  41         return (p);
  42 }
  43 
  44 void
  45 xfree(sysdem_ops_t *ops, void *p, size_t len)
  46 {
  47         if (p == NULL || len == 0)
  48                 return;
  49 
  50         ops->free(p, len);
  51 }
  52 
  53 void *
  54 xrealloc(sysdem_ops_t *ops, void *p, size_t oldsz, size_t newsz)
  55 {
  56         if (newsz == oldsz)
  57                 return (p);
  58 
  59         ASSERT3U(newsz, >, oldsz);
  60 
  61         void *temp = zalloc(ops, newsz);
  62 
  63         if (temp == NULL)
  64                 return (NULL);
  65 
  66         if (oldsz > 0) {
  67                 (void) memcpy(temp, p, oldsz);
  68                 xfree(ops, p, oldsz);
  69         }
  70 
  71         return (temp);
  72 }
  73 
  74 /*ARGSUSED*/
  75 static void
  76 def_free(void *p, size_t len)
  77 {
  78         free(p);
  79 }
  80 
  81 /* BEGIN CSTYLED */
  82 sysdem_ops_t *sysdem_ops_default = &(sysdem_ops_t){
  83         .alloc = malloc,
  84         .free = def_free
  85 };
  86 /* END CSTYLED */