1 //
2 //
3 // Copyright 2015 gRPC authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 //
18 
19 #include <grpc/support/port_platform.h>
20 
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include <grpc/support/alloc.h>
25 #include <grpc/support/log.h>
26 
27 #include "src/core/lib/gprpp/crash.h"
28 
gpr_malloc(size_t size)29 void* gpr_malloc(size_t size) {
30   void* p;
31   if (size == 0) return nullptr;
32   p = malloc(size);
33   if (!p) {
34     abort();
35   }
36   return p;
37 }
38 
gpr_zalloc(size_t size)39 void* gpr_zalloc(size_t size) {
40   void* p;
41   if (size == 0) return nullptr;
42   p = calloc(size, 1);
43   if (!p) {
44     abort();
45   }
46   return p;
47 }
48 
gpr_free(void * p)49 void gpr_free(void* p) { free(p); }
50 
gpr_realloc(void * p,size_t size)51 void* gpr_realloc(void* p, size_t size) {
52   if ((size == 0) && (p == nullptr)) return nullptr;
53   p = realloc(p, size);
54   if (!p) {
55     abort();
56   }
57   return p;
58 }
59 
gpr_malloc_aligned(size_t size,size_t alignment)60 void* gpr_malloc_aligned(size_t size, size_t alignment) {
61   GPR_ASSERT(((alignment - 1) & alignment) == 0);  // Must be power of 2.
62   size_t extra = alignment - 1 + sizeof(void*);
63   void* p = gpr_malloc(size + extra);
64   void** ret = reinterpret_cast<void**>(
65       (reinterpret_cast<uintptr_t>(p) + extra) & ~(alignment - 1));
66   ret[-1] = p;
67   return ret;
68 }
69 
gpr_free_aligned(void * ptr)70 void gpr_free_aligned(void* ptr) { gpr_free((static_cast<void**>(ptr))[-1]); }
71