blob: 918adb01aeb3271dbc5bb0f15f1ae598cdbf019a [file] [log] [blame]
Dmitriy Ivanov19656ce2015-03-10 17:48:27 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
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#include "linker_allocator.h"
18
19#include <stdlib.h>
Josh Gao9ccccc12017-02-09 10:54:44 -080020#include <sys/cdefs.h>
21#include <unistd.h>
22
23#include "private/libc_logging.h"
Dmitriy Ivanov19656ce2015-03-10 17:48:27 -070024
25static LinkerMemoryAllocator g_linker_allocator;
Josh Gao9ccccc12017-02-09 10:54:44 -080026static pid_t fallback_tid = 0;
27
28// Used by libdebuggerd_handler to switch allocators during a crash dump, in
29// case the linker heap is corrupted. Do not use this function.
30extern "C" void __linker_use_fallback_allocator() {
31 if (fallback_tid != 0) {
32 __libc_format_log(ANDROID_LOG_ERROR, "libc",
33 "attempted to set fallback allocator multiple times");
34 return;
35 }
36
37 fallback_tid = gettid();
38}
39
40static LinkerMemoryAllocator& get_fallback_allocator() {
41 static LinkerMemoryAllocator fallback_allocator;
42 return fallback_allocator;
43}
44
45static LinkerMemoryAllocator& get_allocator() {
46 if (__predict_false(fallback_tid) && __predict_false(gettid() == fallback_tid)) {
47 return get_fallback_allocator();
48 }
49 return g_linker_allocator;
50}
Dmitriy Ivanov19656ce2015-03-10 17:48:27 -070051
52void* malloc(size_t byte_count) {
Josh Gao9ccccc12017-02-09 10:54:44 -080053 return get_allocator().alloc(byte_count);
Dmitriy Ivanov19656ce2015-03-10 17:48:27 -070054}
55
56void* calloc(size_t item_count, size_t item_size) {
Josh Gao9ccccc12017-02-09 10:54:44 -080057 return get_allocator().alloc(item_count*item_size);
Dmitriy Ivanov19656ce2015-03-10 17:48:27 -070058}
59
60void* realloc(void* p, size_t byte_count) {
Josh Gao9ccccc12017-02-09 10:54:44 -080061 return get_allocator().realloc(p, byte_count);
Dmitriy Ivanov19656ce2015-03-10 17:48:27 -070062}
63
64void free(void* ptr) {
Josh Gao9ccccc12017-02-09 10:54:44 -080065 get_allocator().free(ptr);
Dmitriy Ivanov19656ce2015-03-10 17:48:27 -070066}
67