1 | /* |
2 | * Copyright 2019 WebAssembly Community Group participants |
3 | * |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at |
7 | * |
8 | * http://www.apache.org/licenses/LICENSE-2.0 |
9 | * |
10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
13 | * See the License for the specific language governing permissions and |
14 | * limitations under the License. |
15 | */ |
16 | |
17 | // |
18 | // Allocation helpers |
19 | // |
20 | |
21 | #ifndef wasm_support_alloc_h |
22 | #define wasm_support_alloc_h |
23 | |
24 | #include <stdlib.h> |
25 | |
26 | #if defined(WIN32) || defined(_WIN32) |
27 | #include <malloc.h> |
28 | #endif |
29 | |
30 | namespace wasm { |
31 | |
32 | // An allocation of a specific size and a minimum alignment. Must be freed |
33 | // with aligned_free. Returns nullptr on failure. |
34 | inline void* aligned_malloc(size_t align, size_t size) { |
35 | #if defined(WIN32) || defined(_WIN32) |
36 | _set_errno(0); |
37 | void* ret = _aligned_malloc(size, align); |
38 | if (errno == ENOMEM) |
39 | ret = nullptr; |
40 | return ret; |
41 | #elif defined(__APPLE__) || !defined(_ISOC11_SOURCE) |
42 | void* ptr; |
43 | int result = posix_memalign(&ptr, align, size); |
44 | return result == 0 ? ptr : nullptr; |
45 | #else |
46 | return aligned_alloc(align, size); |
47 | #endif |
48 | } |
49 | |
50 | inline void aligned_free(void* ptr) { |
51 | #if defined(WIN32) || defined(_WIN32) |
52 | _aligned_free(ptr); |
53 | #else |
54 | free(ptr); |
55 | #endif |
56 | } |
57 | |
58 | } // namespace wasm |
59 | |
60 | #endif // wasm_support_alloc_h |
61 | |