1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/process/memory.h"
6
7 #include <stddef.h>
8
9 #include <new>
10
11 #include "base/allocator/allocator_shim.h"
12 #include "base/allocator/features.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_util.h"
15 #include "base/logging.h"
16 #include "base/process/internal_linux.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "build/build_config.h"
19
20 #if defined(USE_TCMALLOC)
21 #include "third_party/tcmalloc/chromium/src/gperftools/tcmalloc.h"
22 #endif
23
24 namespace base {
25
26 size_t g_oom_size = 0U;
27
28 namespace {
29
OnNoMemorySize(size_t size)30 void OnNoMemorySize(size_t size) {
31 g_oom_size = size;
32
33 if (size != 0)
34 LOG(FATAL) << "Out of memory, size = " << size;
35 LOG(FATAL) << "Out of memory.";
36 }
37
OnNoMemory()38 void OnNoMemory() {
39 OnNoMemorySize(0);
40 }
41
42 } // namespace
43
44 // TODO(primiano): Once the unified shim is on by default (crbug.com/550886)
45 // get rid of the code in this entire #if section. The whole termination-on-OOM
46 // logic is implemented in the shim.
47 #if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
48 !defined(THREAD_SANITIZER) && !defined(LEAK_SANITIZER) && \
49 !BUILDFLAG(USE_EXPERIMENTAL_ALLOCATOR_SHIM)
50
51 #if defined(LIBC_GLIBC) && !defined(USE_TCMALLOC)
52
53 extern "C" {
54 void* __libc_malloc(size_t size);
55 void* __libc_realloc(void* ptr, size_t size);
56 void* __libc_calloc(size_t nmemb, size_t size);
57 void* __libc_valloc(size_t size);
58 #if PVALLOC_AVAILABLE == 1
59 void* __libc_pvalloc(size_t size);
60 #endif
61 void* __libc_memalign(size_t alignment, size_t size);
62
63 // Overriding the system memory allocation functions:
64 //
65 // For security reasons, we want malloc failures to be fatal. Too much code
66 // doesn't check for a NULL return value from malloc and unconditionally uses
67 // the resulting pointer. If the first offset that they try to access is
68 // attacker controlled, then the attacker can direct the code to access any
69 // part of memory.
70 //
71 // Thus, we define all the standard malloc functions here and mark them as
72 // visibility 'default'. This means that they replace the malloc functions for
73 // all Chromium code and also for all code in shared libraries. There are tests
74 // for this in process_util_unittest.cc.
75 //
76 // If we are using tcmalloc, then the problem is moot since tcmalloc handles
77 // this for us. Thus this code is in a !defined(USE_TCMALLOC) block.
78 //
79 // If we are testing the binary with AddressSanitizer, we should not
80 // redefine malloc and let AddressSanitizer do it instead.
81 //
82 // We call the real libc functions in this code by using __libc_malloc etc.
83 // Previously we tried using dlsym(RTLD_NEXT, ...) but that failed depending on
84 // the link order. Since ld.so needs calloc during symbol resolution, it
85 // defines its own versions of several of these functions in dl-minimal.c.
86 // Depending on the runtime library order, dlsym ended up giving us those
87 // functions and bad things happened. See crbug.com/31809
88 //
89 // This means that any code which calls __libc_* gets the raw libc versions of
90 // these functions.
91
92 #define DIE_ON_OOM_1(function_name) \
93 void* function_name(size_t) __attribute__ ((visibility("default"))); \
94 \
95 void* function_name(size_t size) { \
96 void* ret = __libc_##function_name(size); \
97 if (ret == NULL && size != 0) \
98 OnNoMemorySize(size); \
99 return ret; \
100 }
101
102 #define DIE_ON_OOM_2(function_name, arg1_type) \
103 void* function_name(arg1_type, size_t) \
104 __attribute__ ((visibility("default"))); \
105 \
106 void* function_name(arg1_type arg1, size_t size) { \
107 void* ret = __libc_##function_name(arg1, size); \
108 if (ret == NULL && size != 0) \
109 OnNoMemorySize(size); \
110 return ret; \
111 }
112
113 DIE_ON_OOM_1(malloc)
114 DIE_ON_OOM_1(valloc)
115 #if PVALLOC_AVAILABLE == 1
116 DIE_ON_OOM_1(pvalloc)
117 #endif
118
119 DIE_ON_OOM_2(calloc, size_t)
120 DIE_ON_OOM_2(realloc, void*)
121 DIE_ON_OOM_2(memalign, size_t)
122
123 // posix_memalign has a unique signature and doesn't have a __libc_ variant.
124 int posix_memalign(void** ptr, size_t alignment, size_t size)
125 __attribute__ ((visibility("default")));
126
posix_memalign(void ** ptr,size_t alignment,size_t size)127 int posix_memalign(void** ptr, size_t alignment, size_t size) {
128 // This will use the safe version of memalign, above.
129 *ptr = memalign(alignment, size);
130 return 0;
131 }
132
133 } // extern C
134
135 #else
136
137 // TODO(mostynb@opera.com): dlsym dance
138
139 #endif // LIBC_GLIBC && !USE_TCMALLOC
140
141 #endif // !*_SANITIZER
142
EnableTerminationOnHeapCorruption()143 void EnableTerminationOnHeapCorruption() {
144 // On Linux, there nothing to do AFAIK.
145 }
146
EnableTerminationOnOutOfMemory()147 void EnableTerminationOnOutOfMemory() {
148 // Set the new-out of memory handler.
149 std::set_new_handler(&OnNoMemory);
150 // If we're using glibc's allocator, the above functions will override
151 // malloc and friends and make them die on out of memory.
152
153 #if BUILDFLAG(USE_EXPERIMENTAL_ALLOCATOR_SHIM)
154 allocator::SetCallNewHandlerOnMallocFailure(true);
155 #elif defined(USE_TCMALLOC)
156 // For tcmalloc, we need to tell it to behave like new.
157 tc_set_new_mode(1);
158 #endif
159 }
160
161 // NOTE: This is not the only version of this function in the source:
162 // the setuid sandbox (in process_util_linux.c, in the sandbox source)
163 // also has its own C version.
AdjustOOMScore(ProcessId process,int score)164 bool AdjustOOMScore(ProcessId process, int score) {
165 if (score < 0 || score > kMaxOomScore)
166 return false;
167
168 FilePath oom_path(internal::GetProcPidDir(process));
169
170 // Attempt to write the newer oom_score_adj file first.
171 FilePath oom_file = oom_path.AppendASCII("oom_score_adj");
172 if (PathExists(oom_file)) {
173 std::string score_str = IntToString(score);
174 DVLOG(1) << "Adjusting oom_score_adj of " << process << " to "
175 << score_str;
176 int score_len = static_cast<int>(score_str.length());
177 return (score_len == WriteFile(oom_file, score_str.c_str(), score_len));
178 }
179
180 // If the oom_score_adj file doesn't exist, then we write the old
181 // style file and translate the oom_adj score to the range 0-15.
182 oom_file = oom_path.AppendASCII("oom_adj");
183 if (PathExists(oom_file)) {
184 // Max score for the old oom_adj range. Used for conversion of new
185 // values to old values.
186 const int kMaxOldOomScore = 15;
187
188 int converted_score = score * kMaxOldOomScore / kMaxOomScore;
189 std::string score_str = IntToString(converted_score);
190 DVLOG(1) << "Adjusting oom_adj of " << process << " to " << score_str;
191 int score_len = static_cast<int>(score_str.length());
192 return (score_len == WriteFile(oom_file, score_str.c_str(), score_len));
193 }
194
195 return false;
196 }
197
UncheckedMalloc(size_t size,void ** result)198 bool UncheckedMalloc(size_t size, void** result) {
199 #if BUILDFLAG(USE_EXPERIMENTAL_ALLOCATOR_SHIM)
200 *result = allocator::UncheckedAlloc(size);
201 #elif defined(MEMORY_TOOL_REPLACES_ALLOCATOR) || \
202 (!defined(LIBC_GLIBC) && !defined(USE_TCMALLOC))
203 *result = malloc(size);
204 #elif defined(LIBC_GLIBC) && !defined(USE_TCMALLOC)
205 *result = __libc_malloc(size);
206 #elif defined(USE_TCMALLOC)
207 *result = tc_malloc_skip_new_handler(size);
208 #endif
209 return *result != NULL;
210 }
211
212 } // namespace base
213