| 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 |
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 |
|
| 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 |
|
| 47 |
void gpr_free(void* p) { free(p); } |
| 48 |
|
| 49 |
void* gpr_realloc(void* p, size_t size) { |
| 50 |
if ((size == 0) && (p == nullptr)) return nullptr; |
| 51 |
p = realloc(p, size); |
| 52 |
if (!p) { |
| 53 |
abort(); |
| 54 |
} |
| 55 |
return p; |
| 56 |
} |
| 57 |
|
| 58 |
void* gpr_malloc_aligned(size_t size, size_t alignment) { |
| 59 |
GPR_ASSERT(((alignment - 1) & alignment) == 0); // Must be power of 2. |
| 60 |
size_t extra = alignment - 1 + sizeof(void*); |
| 61 |
void* p = gpr_malloc(size + extra); |
| 62 |
void** ret = reinterpret_cast<void**>( |
| 63 |
(reinterpret_cast<uintptr_t>(p) + extra) & ~(alignment - 1)); |
| 64 |
ret[-1] = p; |
| 65 |
return ret; |
| 66 |
} |
| 67 |
|
| 68 |
void gpr_free_aligned(void* ptr) { gpr_free((static_cast<void**>(ptr))[-1]); } |