blob: 7e19b311ecc8a74fbbe25d71c798a72e3355a354 [file] [log] [blame]
Mitch Phillipsf3968e82020-01-31 19:57:04 -08001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
Mitch Phillipse6997d52020-11-30 15:04:14 -080029#include <alloca.h>
30#include <assert.h>
31#include <ctype.h>
Mitch Phillipsf3968e82020-01-31 19:57:04 -080032#include <stddef.h>
33#include <stdint.h>
34#include <stdio.h>
Mitch Phillipse6997d52020-11-30 15:04:14 -080035#include <stdlib.h>
Mitch Phillipsf3968e82020-01-31 19:57:04 -080036#include <string.h>
37#include <sys/types.h>
38
Mitch Phillipsf3968e82020-01-31 19:57:04 -080039#include "gwp_asan/guarded_pool_allocator.h"
40#include "gwp_asan/options.h"
Mitch Phillipse6997d52020-11-30 15:04:14 -080041#include "gwp_asan_wrappers.h"
Mitch Phillipsf3968e82020-01-31 19:57:04 -080042#include "malloc_common.h"
Mitch Phillipse6997d52020-11-30 15:04:14 -080043#include "platform/bionic/android_unsafe_frame_pointer_chase.h"
44#include "platform/bionic/malloc.h"
45#include "private/bionic_arc4random.h"
46#include "private/bionic_globals.h"
47#include "private/bionic_malloc_dispatch.h"
48#include "sys/system_properties.h"
49#include "sysprop_helpers.h"
Mitch Phillipsf3968e82020-01-31 19:57:04 -080050
51#ifndef LIBC_STATIC
52#include "bionic/malloc_common_dynamic.h"
53#endif // LIBC_STATIC
54
55static gwp_asan::GuardedPoolAllocator GuardedAlloc;
56static const MallocDispatch* prev_dispatch;
57
Mitch Phillipse6997d52020-11-30 15:04:14 -080058using Action = android_mallopt_gwp_asan_options_t::Action;
Mitch Phillipsf3968e82020-01-31 19:57:04 -080059using Options = gwp_asan::options::Options;
60
Mitch Phillipse6997d52020-11-30 15:04:14 -080061// basename() is a mess, see the manpage. Let's be explicit what handling we
62// want (don't touch my string!).
63extern "C" const char* __gnu_basename(const char* path);
Mitch Phillipsf3968e82020-01-31 19:57:04 -080064
Mitch Phillipse6997d52020-11-30 15:04:14 -080065namespace {
Mitch Phillipsf3968e82020-01-31 19:57:04 -080066
67// ============================================================================
68// Implementation of GWP-ASan malloc wrappers.
69// ============================================================================
70
71void* gwp_asan_calloc(size_t n_elements, size_t elem_size) {
72 if (__predict_false(GuardedAlloc.shouldSample())) {
73 size_t bytes;
74 if (!__builtin_mul_overflow(n_elements, elem_size, &bytes)) {
75 if (void* result = GuardedAlloc.allocate(bytes)) {
76 return result;
77 }
78 }
79 }
80 return prev_dispatch->calloc(n_elements, elem_size);
81}
82
83void gwp_asan_free(void* mem) {
84 if (__predict_false(GuardedAlloc.pointerIsMine(mem))) {
85 GuardedAlloc.deallocate(mem);
86 return;
87 }
88 prev_dispatch->free(mem);
89}
90
91void* gwp_asan_malloc(size_t bytes) {
92 if (__predict_false(GuardedAlloc.shouldSample())) {
93 if (void* result = GuardedAlloc.allocate(bytes)) {
94 return result;
95 }
96 }
97 return prev_dispatch->malloc(bytes);
98}
99
100size_t gwp_asan_malloc_usable_size(const void* mem) {
101 if (__predict_false(GuardedAlloc.pointerIsMine(mem))) {
102 return GuardedAlloc.getSize(mem);
103 }
104 return prev_dispatch->malloc_usable_size(mem);
105}
106
107void* gwp_asan_realloc(void* old_mem, size_t bytes) {
Mitch Phillipsc70311c2022-04-11 13:22:01 -0700108 // GPA::pointerIsMine(p) always returns false where `p == nullptr` (and thus
109 // malloc(bytes) is requested). We always fall back to the backing allocator,
110 // technically missing some coverage, but reducing an extra conditional
111 // branch.
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800112 if (__predict_false(GuardedAlloc.pointerIsMine(old_mem))) {
Mitch Phillipsc70311c2022-04-11 13:22:01 -0700113 if (__predict_false(bytes == 0)) {
114 GuardedAlloc.deallocate(old_mem);
115 return nullptr;
116 }
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800117 void* new_ptr = gwp_asan_malloc(bytes);
Mitch Phillipsc70311c2022-04-11 13:22:01 -0700118 // If malloc() fails, then don't destroy the old memory.
119 if (__predict_false(new_ptr == nullptr)) return nullptr;
120
121 size_t old_size = GuardedAlloc.getSize(old_mem);
122 memcpy(new_ptr, old_mem, (bytes < old_size) ? bytes : old_size);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800123 GuardedAlloc.deallocate(old_mem);
124 return new_ptr;
125 }
126 return prev_dispatch->realloc(old_mem, bytes);
127}
128
129int gwp_asan_malloc_iterate(uintptr_t base, size_t size,
130 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
131 if (__predict_false(GuardedAlloc.pointerIsMine(reinterpret_cast<void*>(base)))) {
132 // TODO(mitchp): GPA::iterate() returns void, but should return int.
133 // TODO(mitchp): GPA::iterate() should take uintptr_t, not void*.
134 GuardedAlloc.iterate(reinterpret_cast<void*>(base), size, callback, arg);
135 return 0;
136 }
137 return prev_dispatch->malloc_iterate(base, size, callback, arg);
138}
139
140void gwp_asan_malloc_disable() {
141 GuardedAlloc.disable();
142 prev_dispatch->malloc_disable();
143}
144
145void gwp_asan_malloc_enable() {
146 GuardedAlloc.enable();
147 prev_dispatch->malloc_enable();
148}
149
Mitch Phillipse6997d52020-11-30 15:04:14 -0800150const MallocDispatch gwp_asan_dispatch __attribute__((unused)) = {
151 gwp_asan_calloc,
152 gwp_asan_free,
153 Malloc(mallinfo),
154 gwp_asan_malloc,
155 gwp_asan_malloc_usable_size,
156 Malloc(memalign),
157 Malloc(posix_memalign),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800158#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Mitch Phillipse6997d52020-11-30 15:04:14 -0800159 Malloc(pvalloc),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800160#endif
Mitch Phillipse6997d52020-11-30 15:04:14 -0800161 gwp_asan_realloc,
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800162#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Mitch Phillipse6997d52020-11-30 15:04:14 -0800163 Malloc(valloc),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800164#endif
Mitch Phillipse6997d52020-11-30 15:04:14 -0800165 gwp_asan_malloc_iterate,
166 gwp_asan_malloc_disable,
167 gwp_asan_malloc_enable,
168 Malloc(mallopt),
169 Malloc(aligned_alloc),
170 Malloc(malloc_info),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800171};
172
Mitch Phillipse6997d52020-11-30 15:04:14 -0800173bool isPowerOfTwo(uint64_t x) {
174 assert(x != 0);
175 return (x & (x - 1)) == 0;
176}
Mitch Phillips0083b0f2020-02-13 17:37:11 -0800177
Mitch Phillipse6997d52020-11-30 15:04:14 -0800178bool ShouldGwpAsanSampleProcess(unsigned sample_rate) {
179 if (!isPowerOfTwo(sample_rate)) {
180 warning_log(
181 "GWP-ASan process sampling rate of %u is not a power-of-two, and so modulo bias occurs.",
182 sample_rate);
183 }
184
Mitch Phillips0083b0f2020-02-13 17:37:11 -0800185 uint8_t random_number;
186 __libc_safe_arc4random_buf(&random_number, sizeof(random_number));
Mitch Phillipse6997d52020-11-30 15:04:14 -0800187 return random_number % sample_rate == 0;
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800188}
189
Mitch Phillipse6997d52020-11-30 15:04:14 -0800190bool GwpAsanInitialized = false;
191
192// The probability (1 / SampleRate) that an allocation gets chosen to be put
193// into the special GWP-ASan pool.
194using SampleRate_t = typeof(gwp_asan::options::Options::SampleRate);
195constexpr SampleRate_t kDefaultSampleRate = 2500;
196static const char* kSampleRateSystemSysprop = "libc.debug.gwp_asan.sample_rate.system_default";
197static const char* kSampleRateAppSysprop = "libc.debug.gwp_asan.sample_rate.app_default";
198static const char* kSampleRateTargetedSyspropPrefix = "libc.debug.gwp_asan.sample_rate.";
199static const char* kSampleRateEnvVar = "GWP_ASAN_SAMPLE_RATE";
200
201// The probability (1 / ProcessSampling) that a process will be randomly
202// selected for sampling, for system apps and system processes. The process
203// sampling rate should always be a power of two to avoid modulo bias.
204constexpr unsigned kDefaultProcessSampling = 128;
205static const char* kProcessSamplingSystemSysprop =
206 "libc.debug.gwp_asan.process_sampling.system_default";
207static const char* kProcessSamplingAppSysprop = "libc.debug.gwp_asan.process_sampling.app_default";
208static const char* kProcessSamplingTargetedSyspropPrefix = "libc.debug.gwp_asan.process_sampling.";
209static const char* kProcessSamplingEnvVar = "GWP_ASAN_PROCESS_SAMPLING";
210
211// The upper limit of simultaneous allocations supported by GWP-ASan. Any
212// allocations in excess of this limit will be passed to the backing allocator
213// and can't be sampled. This value, if unspecified, will be automatically
214// calculated to keep the same ratio as the default (2500 sampling : 32 allocs).
215// So, if you specify GWP_ASAN_SAMPLE_RATE=1250 (i.e. twice as frequent), we'll
216// automatically calculate that we need double the slots (64).
217using SimultaneousAllocations_t = typeof(gwp_asan::options::Options::MaxSimultaneousAllocations);
218constexpr SimultaneousAllocations_t kDefaultMaxAllocs = 32;
219static const char* kMaxAllocsSystemSysprop = "libc.debug.gwp_asan.max_allocs.system_default";
220static const char* kMaxAllocsAppSysprop = "libc.debug.gwp_asan.max_allocs.app_default";
221static const char* kMaxAllocsTargetedSyspropPrefix = "libc.debug.gwp_asan.max_allocs.";
222static const char* kMaxAllocsEnvVar = "GWP_ASAN_MAX_ALLOCS";
223
224void SetDefaultGwpAsanOptions(Options* options, unsigned* process_sample_rate,
225 const android_mallopt_gwp_asan_options_t& mallopt_options) {
226 options->Enabled = true;
227 options->InstallSignalHandlers = false;
228 options->InstallForkHandlers = true;
229 options->Backtrace = android_unsafe_frame_pointer_chase;
230 options->SampleRate = kDefaultSampleRate;
231 options->MaxSimultaneousAllocations = kDefaultMaxAllocs;
232
233 *process_sample_rate = 1;
234 if (mallopt_options.desire == Action::TURN_ON_WITH_SAMPLING) {
235 *process_sample_rate = kDefaultProcessSampling;
236 }
237}
238
239bool GetGwpAsanOption(unsigned long long* result,
240 const android_mallopt_gwp_asan_options_t& mallopt_options,
241 const char* system_sysprop, const char* app_sysprop,
242 const char* targeted_sysprop_prefix, const char* env_var,
243 const char* descriptive_name) {
244 const char* basename = "";
245 if (mallopt_options.program_name) basename = __gnu_basename(mallopt_options.program_name);
246
247 size_t program_specific_sysprop_size = strlen(targeted_sysprop_prefix) + strlen(basename) + 1;
248 char* program_specific_sysprop_name = static_cast<char*>(alloca(program_specific_sysprop_size));
249 async_safe_format_buffer(program_specific_sysprop_name, program_specific_sysprop_size, "%s%s",
250 targeted_sysprop_prefix, basename);
251
252 const char* sysprop_names[2] = {nullptr, nullptr};
253 // Tests use a blank program name to specify that system properties should not
254 // be used. Tests still continue to use the environment variable though.
255 if (*basename != '\0') {
256 sysprop_names[0] = program_specific_sysprop_name;
257 if (mallopt_options.desire == Action::TURN_ON_FOR_APP) {
258 sysprop_names[1] = app_sysprop;
259 } else {
260 sysprop_names[1] = system_sysprop;
261 }
262 }
263
264 char settings_buf[PROP_VALUE_MAX];
265 if (!get_config_from_env_or_sysprops(env_var, sysprop_names,
266 /* sys_prop_names_size */ 2, settings_buf, PROP_VALUE_MAX)) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800267 return false;
268 }
Mitch Phillipse6997d52020-11-30 15:04:14 -0800269
270 char* end;
271 unsigned long long value = strtoull(settings_buf, &end, 10);
272 if (value == ULLONG_MAX || *end != '\0') {
273 warning_log("Invalid GWP-ASan %s: \"%s\". Using default value instead.", descriptive_name,
274 settings_buf);
275 return false;
276 }
277
278 *result = value;
279 return true;
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800280}
281
Mitch Phillipse6997d52020-11-30 15:04:14 -0800282// Initialize the GWP-ASan options structure in *options, taking into account whether someone has
283// asked for specific GWP-ASan settings. The order of priority is:
284// 1. Environment variables.
285// 2. Process-specific system properties.
286// 3. Global system properties.
287// If any of these overrides are found, we return true. Otherwise, use the default values, and
288// return false.
289bool GetGwpAsanOptions(Options* options, unsigned* process_sample_rate,
290 const android_mallopt_gwp_asan_options_t& mallopt_options) {
291 SetDefaultGwpAsanOptions(options, process_sample_rate, mallopt_options);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800292
Mitch Phillipse6997d52020-11-30 15:04:14 -0800293 bool had_overrides = false;
294
295 unsigned long long buf;
296 if (GetGwpAsanOption(&buf, mallopt_options, kSampleRateSystemSysprop, kSampleRateAppSysprop,
297 kSampleRateTargetedSyspropPrefix, kSampleRateEnvVar, "sample rate")) {
298 options->SampleRate = buf;
299 had_overrides = true;
300 }
301
302 if (GetGwpAsanOption(&buf, mallopt_options, kProcessSamplingSystemSysprop,
303 kProcessSamplingAppSysprop, kProcessSamplingTargetedSyspropPrefix,
304 kProcessSamplingEnvVar, "process sampling rate")) {
305 *process_sample_rate = buf;
306 had_overrides = true;
307 }
308
309 if (GetGwpAsanOption(&buf, mallopt_options, kMaxAllocsSystemSysprop, kMaxAllocsAppSysprop,
310 kMaxAllocsTargetedSyspropPrefix, kMaxAllocsEnvVar,
311 "maximum simultaneous allocations")) {
312 options->MaxSimultaneousAllocations = buf;
313 had_overrides = true;
314 } else if (had_overrides) {
315 // Multiply the number of slots available, such that the ratio between
316 // sampling rate and slots is kept the same as the default. For example, a
317 // sampling rate of 1000 is 2.5x more frequent than default, and so
318 // requires 80 slots (32 * 2.5).
319 float frequency_multiplier = static_cast<float>(options->SampleRate) / kDefaultSampleRate;
320 options->MaxSimultaneousAllocations =
321 /* default */ kDefaultMaxAllocs / frequency_multiplier;
322 }
323 return had_overrides;
324}
325
326bool MaybeInitGwpAsan(libc_globals* globals,
327 const android_mallopt_gwp_asan_options_t& mallopt_options) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800328 if (GwpAsanInitialized) {
329 error_log("GWP-ASan was already initialized for this process.");
330 return false;
331 }
332
Mitch Phillipse6997d52020-11-30 15:04:14 -0800333 Options options;
334 unsigned process_sample_rate = kDefaultProcessSampling;
335 if (!GetGwpAsanOptions(&options, &process_sample_rate, mallopt_options) &&
336 mallopt_options.desire == Action::DONT_TURN_ON_UNLESS_OVERRIDDEN) {
337 return false;
338 }
339
340 if (options.SampleRate == 0 || process_sample_rate == 0 ||
341 options.MaxSimultaneousAllocations == 0) {
342 return false;
343 }
344
345 if (!ShouldGwpAsanSampleProcess(process_sample_rate)) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800346 return false;
347 }
348
349 // GWP-ASan is compatible with heapprofd/malloc_debug/malloc_hooks iff
350 // GWP-ASan was installed first. If one of these other libraries was already
351 // installed, we don't enable GWP-ASan. These libraries are normally enabled
352 // in libc_init after GWP-ASan, but if the new process is a zygote child and
353 // trying to initialize GWP-ASan through mallopt(), one of these libraries may
354 // be installed. It may be possible to change this in future by modifying the
355 // internal dispatch pointers of these libraries at this point in time, but
356 // given that they're all debug-only, we don't really mind for now.
357 if (GetDefaultDispatchTable() != nullptr) {
358 // Something else is installed.
359 return false;
360 }
361
362 // GWP-ASan's initialization is always called in a single-threaded context, so
363 // we can initialize lock-free.
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800364 // Set GWP-ASan as the malloc dispatch table.
365 globals->malloc_dispatch_table = gwp_asan_dispatch;
366 atomic_store(&globals->default_dispatch_table, &gwp_asan_dispatch);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800367
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800368 // If malloc_limit isn't installed, we can skip the default_dispatch_table
369 // lookup.
370 if (GetDispatchTable() == nullptr) {
371 atomic_store(&globals->current_dispatch_table, &gwp_asan_dispatch);
372 }
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800373
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800374 GwpAsanInitialized = true;
375
Mitch Phillipse6997d52020-11-30 15:04:14 -0800376 prev_dispatch = NativeAllocatorDispatch();
377
378 GuardedAlloc.init(options);
379
380 __libc_shared_globals()->gwp_asan_state = GuardedAlloc.getAllocatorState();
381 __libc_shared_globals()->gwp_asan_metadata = GuardedAlloc.getMetadataRegion();
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800382
383 return true;
384}
Mitch Phillipse6997d52020-11-30 15:04:14 -0800385}; // anonymous namespace
386
387bool MaybeInitGwpAsanFromLibc(libc_globals* globals) {
388 // Never initialize the Zygote here. A Zygote chosen for sampling would also
389 // have all of its children sampled. Instead, the Zygote child will choose
390 // whether it samples or not just after the Zygote forks. Note that the Zygote
391 // changes its name after it's started, at this point it's still called
392 // "app_process" or "app_process64".
393 static const char kAppProcessNamePrefix[] = "app_process";
394 const char* progname = getprogname();
395 if (strncmp(progname, kAppProcessNamePrefix, sizeof(kAppProcessNamePrefix) - 1) == 0)
396 return false;
397
398 android_mallopt_gwp_asan_options_t mallopt_options;
399 mallopt_options.program_name = progname;
400 mallopt_options.desire = Action::TURN_ON_WITH_SAMPLING;
401
402 return MaybeInitGwpAsan(globals, mallopt_options);
403}
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800404
405bool DispatchIsGwpAsan(const MallocDispatch* dispatch) {
406 return dispatch == &gwp_asan_dispatch;
407}
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700408
Mitch Phillipse6997d52020-11-30 15:04:14 -0800409bool EnableGwpAsan(const android_mallopt_gwp_asan_options_t& options) {
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700410 if (GwpAsanInitialized) {
411 return true;
412 }
413
414 bool ret_value;
415 __libc_globals.mutate(
Mitch Phillipse6997d52020-11-30 15:04:14 -0800416 [&](libc_globals* globals) { ret_value = MaybeInitGwpAsan(globals, options); });
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700417 return ret_value;
418}