• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/alloc.h>
20 #include <grpc/support/port_platform.h>
21 #include <stdlib.h>
22 #include <string.h>
23 
24 #include "absl/log/check.h"
25 #include "src/core/util/crash.h"
26 
gpr_malloc(size_t size)27 void* gpr_malloc(size_t size) {
28   void* p;
29   if (size == 0) return nullptr;
30   p = malloc(size);
31   if (!p) {
32     abort();
33   }
34   return p;
35 }
36 
gpr_zalloc(size_t size)37 void* gpr_zalloc(size_t size) {
38   void* p;
39   if (size == 0) return nullptr;
40   p = calloc(size, 1);
41   if (!p) {
42     abort();
43   }
44   return p;
45 }
46 
gpr_free(void * p)47 void gpr_free(void* p) { free(p); }
48 
gpr_realloc(void * p,size_t size)49 void* gpr_realloc(void* p, size_t size) {
50   if ((size == 0) && (p == nullptr)) return nullptr;
51   // NOLINTNEXTLINE(bugprone-suspicious-realloc-usage)
52   p = realloc(p, size);
53   if (!p) {
54     abort();
55   }
56   return p;
57 }
58 
gpr_malloc_aligned(size_t size,size_t alignment)59 void* gpr_malloc_aligned(size_t size, size_t alignment) {
60   CHECK_EQ(((alignment - 1) & alignment), 0u);  // Must be power of 2.
61   size_t extra = alignment - 1 + sizeof(void*);
62   void* p = gpr_malloc(size + extra);
63   void** ret = reinterpret_cast<void**>(
64       (reinterpret_cast<uintptr_t>(p) + extra) & ~(alignment - 1));
65   ret[-1] = p;
66   return ret;
67 }
68 
gpr_free_aligned(void * ptr)69 void gpr_free_aligned(void* ptr) { gpr_free((static_cast<void**>(ptr))[-1]); }
70