blob: 251633d786505f01b6d9654f82592a74d73e179f [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 Phillipsa493fe42023-01-19 12:47:22 -080039#include "gwp_asan/crash_handler.h"
Mitch Phillipsf3968e82020-01-31 19:57:04 -080040#include "gwp_asan/guarded_pool_allocator.h"
41#include "gwp_asan/options.h"
Mitch Phillipse6997d52020-11-30 15:04:14 -080042#include "gwp_asan_wrappers.h"
Mitch Phillipsf3968e82020-01-31 19:57:04 -080043#include "malloc_common.h"
Mitch Phillipse6997d52020-11-30 15:04:14 -080044#include "platform/bionic/android_unsafe_frame_pointer_chase.h"
Mitch Phillips9634c362022-06-23 11:07:00 -070045#include "platform/bionic/macros.h"
Mitch Phillipse6997d52020-11-30 15:04:14 -080046#include "platform/bionic/malloc.h"
47#include "private/bionic_arc4random.h"
48#include "private/bionic_globals.h"
49#include "private/bionic_malloc_dispatch.h"
50#include "sys/system_properties.h"
51#include "sysprop_helpers.h"
Mitch Phillipsf3968e82020-01-31 19:57:04 -080052
53#ifndef LIBC_STATIC
54#include "bionic/malloc_common_dynamic.h"
55#endif // LIBC_STATIC
56
57static gwp_asan::GuardedPoolAllocator GuardedAlloc;
58static const MallocDispatch* prev_dispatch;
59
Mitch Phillipse6997d52020-11-30 15:04:14 -080060using Action = android_mallopt_gwp_asan_options_t::Action;
Mitch Phillipsf3968e82020-01-31 19:57:04 -080061using Options = gwp_asan::options::Options;
62
Mitch Phillipse6997d52020-11-30 15:04:14 -080063// basename() is a mess, see the manpage. Let's be explicit what handling we
64// want (don't touch my string!).
65extern "C" const char* __gnu_basename(const char* path);
Mitch Phillipsf3968e82020-01-31 19:57:04 -080066
Mitch Phillipse6997d52020-11-30 15:04:14 -080067namespace {
Mitch Phillipsf3968e82020-01-31 19:57:04 -080068
69// ============================================================================
70// Implementation of GWP-ASan malloc wrappers.
71// ============================================================================
72
73void* gwp_asan_calloc(size_t n_elements, size_t elem_size) {
74 if (__predict_false(GuardedAlloc.shouldSample())) {
75 size_t bytes;
76 if (!__builtin_mul_overflow(n_elements, elem_size, &bytes)) {
77 if (void* result = GuardedAlloc.allocate(bytes)) {
78 return result;
79 }
80 }
81 }
82 return prev_dispatch->calloc(n_elements, elem_size);
83}
84
85void gwp_asan_free(void* mem) {
86 if (__predict_false(GuardedAlloc.pointerIsMine(mem))) {
87 GuardedAlloc.deallocate(mem);
88 return;
89 }
90 prev_dispatch->free(mem);
91}
92
93void* gwp_asan_malloc(size_t bytes) {
94 if (__predict_false(GuardedAlloc.shouldSample())) {
95 if (void* result = GuardedAlloc.allocate(bytes)) {
96 return result;
97 }
98 }
99 return prev_dispatch->malloc(bytes);
100}
101
102size_t gwp_asan_malloc_usable_size(const void* mem) {
103 if (__predict_false(GuardedAlloc.pointerIsMine(mem))) {
104 return GuardedAlloc.getSize(mem);
105 }
106 return prev_dispatch->malloc_usable_size(mem);
107}
108
109void* gwp_asan_realloc(void* old_mem, size_t bytes) {
Mitch Phillipsc70311c2022-04-11 13:22:01 -0700110 // GPA::pointerIsMine(p) always returns false where `p == nullptr` (and thus
111 // malloc(bytes) is requested). We always fall back to the backing allocator,
112 // technically missing some coverage, but reducing an extra conditional
113 // branch.
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800114 if (__predict_false(GuardedAlloc.pointerIsMine(old_mem))) {
Mitch Phillipsc70311c2022-04-11 13:22:01 -0700115 if (__predict_false(bytes == 0)) {
116 GuardedAlloc.deallocate(old_mem);
117 return nullptr;
118 }
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800119 void* new_ptr = gwp_asan_malloc(bytes);
Mitch Phillipsc70311c2022-04-11 13:22:01 -0700120 // If malloc() fails, then don't destroy the old memory.
121 if (__predict_false(new_ptr == nullptr)) return nullptr;
122
123 size_t old_size = GuardedAlloc.getSize(old_mem);
124 memcpy(new_ptr, old_mem, (bytes < old_size) ? bytes : old_size);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800125 GuardedAlloc.deallocate(old_mem);
126 return new_ptr;
127 }
128 return prev_dispatch->realloc(old_mem, bytes);
129}
130
131int gwp_asan_malloc_iterate(uintptr_t base, size_t size,
132 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
133 if (__predict_false(GuardedAlloc.pointerIsMine(reinterpret_cast<void*>(base)))) {
134 // TODO(mitchp): GPA::iterate() returns void, but should return int.
135 // TODO(mitchp): GPA::iterate() should take uintptr_t, not void*.
136 GuardedAlloc.iterate(reinterpret_cast<void*>(base), size, callback, arg);
137 return 0;
138 }
139 return prev_dispatch->malloc_iterate(base, size, callback, arg);
140}
141
142void gwp_asan_malloc_disable() {
143 GuardedAlloc.disable();
144 prev_dispatch->malloc_disable();
145}
146
147void gwp_asan_malloc_enable() {
148 GuardedAlloc.enable();
149 prev_dispatch->malloc_enable();
150}
151
Mitch Phillipse6997d52020-11-30 15:04:14 -0800152const MallocDispatch gwp_asan_dispatch __attribute__((unused)) = {
153 gwp_asan_calloc,
154 gwp_asan_free,
155 Malloc(mallinfo),
156 gwp_asan_malloc,
157 gwp_asan_malloc_usable_size,
158 Malloc(memalign),
159 Malloc(posix_memalign),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800160#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Mitch Phillipse6997d52020-11-30 15:04:14 -0800161 Malloc(pvalloc),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800162#endif
Mitch Phillipse6997d52020-11-30 15:04:14 -0800163 gwp_asan_realloc,
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800164#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Mitch Phillipse6997d52020-11-30 15:04:14 -0800165 Malloc(valloc),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800166#endif
Mitch Phillipse6997d52020-11-30 15:04:14 -0800167 gwp_asan_malloc_iterate,
168 gwp_asan_malloc_disable,
169 gwp_asan_malloc_enable,
170 Malloc(mallopt),
171 Malloc(aligned_alloc),
172 Malloc(malloc_info),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800173};
174
Mitch Phillipse6997d52020-11-30 15:04:14 -0800175bool isPowerOfTwo(uint64_t x) {
176 assert(x != 0);
177 return (x & (x - 1)) == 0;
178}
Mitch Phillips0083b0f2020-02-13 17:37:11 -0800179
Mitch Phillipse6997d52020-11-30 15:04:14 -0800180bool ShouldGwpAsanSampleProcess(unsigned sample_rate) {
181 if (!isPowerOfTwo(sample_rate)) {
182 warning_log(
183 "GWP-ASan process sampling rate of %u is not a power-of-two, and so modulo bias occurs.",
184 sample_rate);
185 }
186
Mitch Phillips0083b0f2020-02-13 17:37:11 -0800187 uint8_t random_number;
188 __libc_safe_arc4random_buf(&random_number, sizeof(random_number));
Mitch Phillipse6997d52020-11-30 15:04:14 -0800189 return random_number % sample_rate == 0;
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800190}
191
Mitch Phillipse6997d52020-11-30 15:04:14 -0800192bool GwpAsanInitialized = false;
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800193bool GwpAsanRecoverable = false;
Mitch Phillipse6997d52020-11-30 15:04:14 -0800194
195// The probability (1 / SampleRate) that an allocation gets chosen to be put
196// into the special GWP-ASan pool.
197using SampleRate_t = typeof(gwp_asan::options::Options::SampleRate);
198constexpr SampleRate_t kDefaultSampleRate = 2500;
199static const char* kSampleRateSystemSysprop = "libc.debug.gwp_asan.sample_rate.system_default";
200static const char* kSampleRateAppSysprop = "libc.debug.gwp_asan.sample_rate.app_default";
201static const char* kSampleRateTargetedSyspropPrefix = "libc.debug.gwp_asan.sample_rate.";
202static const char* kSampleRateEnvVar = "GWP_ASAN_SAMPLE_RATE";
203
204// The probability (1 / ProcessSampling) that a process will be randomly
205// selected for sampling, for system apps and system processes. The process
206// sampling rate should always be a power of two to avoid modulo bias.
207constexpr unsigned kDefaultProcessSampling = 128;
208static const char* kProcessSamplingSystemSysprop =
209 "libc.debug.gwp_asan.process_sampling.system_default";
210static const char* kProcessSamplingAppSysprop = "libc.debug.gwp_asan.process_sampling.app_default";
211static const char* kProcessSamplingTargetedSyspropPrefix = "libc.debug.gwp_asan.process_sampling.";
212static const char* kProcessSamplingEnvVar = "GWP_ASAN_PROCESS_SAMPLING";
213
214// The upper limit of simultaneous allocations supported by GWP-ASan. Any
215// allocations in excess of this limit will be passed to the backing allocator
216// and can't be sampled. This value, if unspecified, will be automatically
217// calculated to keep the same ratio as the default (2500 sampling : 32 allocs).
218// So, if you specify GWP_ASAN_SAMPLE_RATE=1250 (i.e. twice as frequent), we'll
219// automatically calculate that we need double the slots (64).
220using SimultaneousAllocations_t = typeof(gwp_asan::options::Options::MaxSimultaneousAllocations);
221constexpr SimultaneousAllocations_t kDefaultMaxAllocs = 32;
222static const char* kMaxAllocsSystemSysprop = "libc.debug.gwp_asan.max_allocs.system_default";
223static const char* kMaxAllocsAppSysprop = "libc.debug.gwp_asan.max_allocs.app_default";
224static const char* kMaxAllocsTargetedSyspropPrefix = "libc.debug.gwp_asan.max_allocs.";
225static const char* kMaxAllocsEnvVar = "GWP_ASAN_MAX_ALLOCS";
226
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800227static const char* kRecoverableSystemSysprop = "libc.debug.gwp_asan.recoverable.system_default";
228static const char* kRecoverableAppSysprop = "libc.debug.gwp_asan.recoverable.app_default";
229static const char* kRecoverableTargetedSyspropPrefix = "libc.debug.gwp_asan.recoverable.";
230static const char* kRecoverableEnvVar = "GWP_ASAN_RECOVERABLE";
231
Mitch Phillips9634c362022-06-23 11:07:00 -0700232static const char kPersistPrefix[] = "persist.";
233
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800234bool NeedsGwpAsanRecovery(void* fault_ptr) {
235 fault_ptr = untag_address(fault_ptr);
236 return GwpAsanInitialized && GwpAsanRecoverable &&
237 __gwp_asan_error_is_mine(GuardedAlloc.getAllocatorState(),
238 reinterpret_cast<uintptr_t>(fault_ptr));
239}
240
241void GwpAsanPreCrashHandler(void* fault_ptr) {
242 fault_ptr = untag_address(fault_ptr);
243 if (!NeedsGwpAsanRecovery(fault_ptr)) return;
244 GuardedAlloc.preCrashReport(fault_ptr);
245}
246
247void GwpAsanPostCrashHandler(void* fault_ptr) {
248 fault_ptr = untag_address(fault_ptr);
249 if (!NeedsGwpAsanRecovery(fault_ptr)) return;
250 GuardedAlloc.postCrashReportRecoverableOnly(fault_ptr);
251}
252
Mitch Phillipse6997d52020-11-30 15:04:14 -0800253void SetDefaultGwpAsanOptions(Options* options, unsigned* process_sample_rate,
254 const android_mallopt_gwp_asan_options_t& mallopt_options) {
255 options->Enabled = true;
256 options->InstallSignalHandlers = false;
257 options->InstallForkHandlers = true;
258 options->Backtrace = android_unsafe_frame_pointer_chase;
259 options->SampleRate = kDefaultSampleRate;
260 options->MaxSimultaneousAllocations = kDefaultMaxAllocs;
261
262 *process_sample_rate = 1;
263 if (mallopt_options.desire == Action::TURN_ON_WITH_SAMPLING) {
264 *process_sample_rate = kDefaultProcessSampling;
Mitch Phillips2480f492023-01-26 13:59:56 -0800265 } else if (mallopt_options.desire == Action::TURN_ON_FOR_APP_SAMPLED_NON_CRASHING) {
266 *process_sample_rate = kDefaultProcessSampling;
267 options->Recoverable = true;
268 GwpAsanRecoverable = true;
Mitch Phillipse6997d52020-11-30 15:04:14 -0800269 }
270}
271
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800272bool GetGwpAsanOptionImpl(char* value_out,
273 const android_mallopt_gwp_asan_options_t& mallopt_options,
274 const char* system_sysprop, const char* app_sysprop,
275 const char* targeted_sysprop_prefix, const char* env_var) {
Mitch Phillipse6997d52020-11-30 15:04:14 -0800276 const char* basename = "";
277 if (mallopt_options.program_name) basename = __gnu_basename(mallopt_options.program_name);
278
Mitch Phillips9634c362022-06-23 11:07:00 -0700279 constexpr size_t kSyspropMaxLen = 512;
280 char program_specific_sysprop[kSyspropMaxLen] = {};
281 char persist_program_specific_sysprop[kSyspropMaxLen] = {};
282 char persist_default_sysprop[kSyspropMaxLen] = {};
283 const char* sysprop_names[4] = {};
Mitch Phillipse6997d52020-11-30 15:04:14 -0800284 // Tests use a blank program name to specify that system properties should not
285 // be used. Tests still continue to use the environment variable though.
286 if (*basename != '\0') {
Mitch Phillips9634c362022-06-23 11:07:00 -0700287 const char* default_sysprop = system_sysprop;
Mitch Phillipse6997d52020-11-30 15:04:14 -0800288 if (mallopt_options.desire == Action::TURN_ON_FOR_APP) {
Mitch Phillips9634c362022-06-23 11:07:00 -0700289 default_sysprop = app_sysprop;
Mitch Phillipse6997d52020-11-30 15:04:14 -0800290 }
Mitch Phillips9634c362022-06-23 11:07:00 -0700291 async_safe_format_buffer(&program_specific_sysprop[0], kSyspropMaxLen, "%s%s",
292 targeted_sysprop_prefix, basename);
293 async_safe_format_buffer(&persist_program_specific_sysprop[0], kSyspropMaxLen, "%s%s",
294 kPersistPrefix, program_specific_sysprop);
295 async_safe_format_buffer(&persist_default_sysprop[0], kSyspropMaxLen, "%s%s", kPersistPrefix,
296 default_sysprop);
297
298 // In order of precedence, always take the program-specific sysprop (e.g.
299 // '[persist.]libc.debug.gwp_asan.sample_rate.cameraserver') over the
300 // generic sysprop (e.g.
301 // '[persist.]libc.debug.gwp_asan.(system_default|app_default)'). In
302 // addition, always take the non-persistent option over the persistent
303 // option.
304 sysprop_names[0] = program_specific_sysprop;
305 sysprop_names[1] = persist_program_specific_sysprop;
306 sysprop_names[2] = default_sysprop;
307 sysprop_names[3] = persist_default_sysprop;
Mitch Phillipse6997d52020-11-30 15:04:14 -0800308 }
309
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800310 return get_config_from_env_or_sysprops(env_var, sysprop_names, arraysize(sysprop_names),
Florian Mayerdd443782023-05-17 20:59:14 +0000311 value_out, PROP_VALUE_MAX);
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800312}
313
314bool GetGwpAsanIntegerOption(unsigned long long* result,
315 const android_mallopt_gwp_asan_options_t& mallopt_options,
316 const char* system_sysprop, const char* app_sysprop,
317 const char* targeted_sysprop_prefix, const char* env_var,
318 const char* descriptive_name) {
319 char buffer[PROP_VALUE_MAX];
320 if (!GetGwpAsanOptionImpl(buffer, mallopt_options, system_sysprop, app_sysprop,
321 targeted_sysprop_prefix, env_var)) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800322 return false;
323 }
Mitch Phillipse6997d52020-11-30 15:04:14 -0800324 char* end;
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800325 unsigned long long value = strtoull(buffer, &end, 10);
Mitch Phillipse6997d52020-11-30 15:04:14 -0800326 if (value == ULLONG_MAX || *end != '\0') {
327 warning_log("Invalid GWP-ASan %s: \"%s\". Using default value instead.", descriptive_name,
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800328 buffer);
Mitch Phillipse6997d52020-11-30 15:04:14 -0800329 return false;
330 }
331
332 *result = value;
333 return true;
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800334}
335
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800336bool GetGwpAsanBoolOption(bool* result, const android_mallopt_gwp_asan_options_t& mallopt_options,
337 const char* system_sysprop, const char* app_sysprop,
338 const char* targeted_sysprop_prefix, const char* env_var,
339 const char* descriptive_name) {
340 char buffer[PROP_VALUE_MAX] = {};
341 if (!GetGwpAsanOptionImpl(buffer, mallopt_options, system_sysprop, app_sysprop,
342 targeted_sysprop_prefix, env_var)) {
343 return false;
344 }
345
346 if (strncasecmp(buffer, "1", PROP_VALUE_MAX) == 0 ||
347 strncasecmp(buffer, "true", PROP_VALUE_MAX) == 0) {
348 *result = true;
349 return true;
350 } else if (strncasecmp(buffer, "0", PROP_VALUE_MAX) == 0 ||
351 strncasecmp(buffer, "false", PROP_VALUE_MAX) == 0) {
352 *result = false;
353 return true;
354 }
355
356 warning_log(
357 "Invalid GWP-ASan %s: \"%s\". Using default value \"%s\" instead. Valid values are \"true\", "
358 "\"1\", \"false\", or \"0\".",
359 descriptive_name, buffer, *result ? "true" : "false");
360 return false;
361}
362
Mitch Phillipse6997d52020-11-30 15:04:14 -0800363// Initialize the GWP-ASan options structure in *options, taking into account whether someone has
364// asked for specific GWP-ASan settings. The order of priority is:
365// 1. Environment variables.
366// 2. Process-specific system properties.
367// 3. Global system properties.
368// If any of these overrides are found, we return true. Otherwise, use the default values, and
369// return false.
370bool GetGwpAsanOptions(Options* options, unsigned* process_sample_rate,
371 const android_mallopt_gwp_asan_options_t& mallopt_options) {
372 SetDefaultGwpAsanOptions(options, process_sample_rate, mallopt_options);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800373
Mitch Phillipse6997d52020-11-30 15:04:14 -0800374 bool had_overrides = false;
375
376 unsigned long long buf;
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800377 if (GetGwpAsanIntegerOption(&buf, mallopt_options, kSampleRateSystemSysprop,
378 kSampleRateAppSysprop, kSampleRateTargetedSyspropPrefix,
379 kSampleRateEnvVar, "sample rate")) {
Mitch Phillipse6997d52020-11-30 15:04:14 -0800380 options->SampleRate = buf;
381 had_overrides = true;
382 }
383
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800384 if (GetGwpAsanIntegerOption(&buf, mallopt_options, kProcessSamplingSystemSysprop,
385 kProcessSamplingAppSysprop, kProcessSamplingTargetedSyspropPrefix,
386 kProcessSamplingEnvVar, "process sampling rate")) {
Mitch Phillipse6997d52020-11-30 15:04:14 -0800387 *process_sample_rate = buf;
388 had_overrides = true;
389 }
390
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800391 if (GetGwpAsanIntegerOption(&buf, mallopt_options, kMaxAllocsSystemSysprop, kMaxAllocsAppSysprop,
392 kMaxAllocsTargetedSyspropPrefix, kMaxAllocsEnvVar,
393 "maximum simultaneous allocations")) {
Mitch Phillipse6997d52020-11-30 15:04:14 -0800394 options->MaxSimultaneousAllocations = buf;
395 had_overrides = true;
396 } else if (had_overrides) {
397 // Multiply the number of slots available, such that the ratio between
398 // sampling rate and slots is kept the same as the default. For example, a
399 // sampling rate of 1000 is 2.5x more frequent than default, and so
400 // requires 80 slots (32 * 2.5).
401 float frequency_multiplier = static_cast<float>(options->SampleRate) / kDefaultSampleRate;
402 options->MaxSimultaneousAllocations =
403 /* default */ kDefaultMaxAllocs / frequency_multiplier;
404 }
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800405
406 bool recoverable = false;
407 if (GetGwpAsanBoolOption(&recoverable, mallopt_options, kRecoverableSystemSysprop,
408 kRecoverableAppSysprop, kRecoverableTargetedSyspropPrefix,
409 kRecoverableEnvVar, "recoverable")) {
410 options->Recoverable = recoverable;
411 GwpAsanRecoverable = recoverable;
412 had_overrides = true;
413 }
414
Mitch Phillipse6997d52020-11-30 15:04:14 -0800415 return had_overrides;
416}
417
418bool MaybeInitGwpAsan(libc_globals* globals,
419 const android_mallopt_gwp_asan_options_t& mallopt_options) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800420 if (GwpAsanInitialized) {
421 error_log("GWP-ASan was already initialized for this process.");
422 return false;
423 }
424
Mitch Phillipse6997d52020-11-30 15:04:14 -0800425 Options options;
426 unsigned process_sample_rate = kDefaultProcessSampling;
427 if (!GetGwpAsanOptions(&options, &process_sample_rate, mallopt_options) &&
428 mallopt_options.desire == Action::DONT_TURN_ON_UNLESS_OVERRIDDEN) {
429 return false;
430 }
431
432 if (options.SampleRate == 0 || process_sample_rate == 0 ||
433 options.MaxSimultaneousAllocations == 0) {
434 return false;
435 }
436
437 if (!ShouldGwpAsanSampleProcess(process_sample_rate)) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800438 return false;
439 }
440
441 // GWP-ASan is compatible with heapprofd/malloc_debug/malloc_hooks iff
442 // GWP-ASan was installed first. If one of these other libraries was already
443 // installed, we don't enable GWP-ASan. These libraries are normally enabled
444 // in libc_init after GWP-ASan, but if the new process is a zygote child and
445 // trying to initialize GWP-ASan through mallopt(), one of these libraries may
446 // be installed. It may be possible to change this in future by modifying the
447 // internal dispatch pointers of these libraries at this point in time, but
448 // given that they're all debug-only, we don't really mind for now.
449 if (GetDefaultDispatchTable() != nullptr) {
450 // Something else is installed.
451 return false;
452 }
453
454 // GWP-ASan's initialization is always called in a single-threaded context, so
455 // we can initialize lock-free.
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800456 // Set GWP-ASan as the malloc dispatch table.
457 globals->malloc_dispatch_table = gwp_asan_dispatch;
458 atomic_store(&globals->default_dispatch_table, &gwp_asan_dispatch);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800459
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800460 // If malloc_limit isn't installed, we can skip the default_dispatch_table
461 // lookup.
462 if (GetDispatchTable() == nullptr) {
463 atomic_store(&globals->current_dispatch_table, &gwp_asan_dispatch);
464 }
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800465
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800466 GwpAsanInitialized = true;
467
Mitch Phillipse6997d52020-11-30 15:04:14 -0800468 prev_dispatch = NativeAllocatorDispatch();
469
470 GuardedAlloc.init(options);
471
472 __libc_shared_globals()->gwp_asan_state = GuardedAlloc.getAllocatorState();
473 __libc_shared_globals()->gwp_asan_metadata = GuardedAlloc.getMetadataRegion();
Mitch Phillipsa493fe42023-01-19 12:47:22 -0800474 __libc_shared_globals()->debuggerd_needs_gwp_asan_recovery = NeedsGwpAsanRecovery;
475 __libc_shared_globals()->debuggerd_gwp_asan_pre_crash_report = GwpAsanPreCrashHandler;
476 __libc_shared_globals()->debuggerd_gwp_asan_post_crash_report = GwpAsanPostCrashHandler;
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800477
478 return true;
479}
Mitch Phillipse6997d52020-11-30 15:04:14 -0800480}; // anonymous namespace
481
482bool MaybeInitGwpAsanFromLibc(libc_globals* globals) {
483 // Never initialize the Zygote here. A Zygote chosen for sampling would also
484 // have all of its children sampled. Instead, the Zygote child will choose
485 // whether it samples or not just after the Zygote forks. Note that the Zygote
486 // changes its name after it's started, at this point it's still called
487 // "app_process" or "app_process64".
488 static const char kAppProcessNamePrefix[] = "app_process";
489 const char* progname = getprogname();
490 if (strncmp(progname, kAppProcessNamePrefix, sizeof(kAppProcessNamePrefix) - 1) == 0)
491 return false;
492
493 android_mallopt_gwp_asan_options_t mallopt_options;
494 mallopt_options.program_name = progname;
495 mallopt_options.desire = Action::TURN_ON_WITH_SAMPLING;
496
497 return MaybeInitGwpAsan(globals, mallopt_options);
498}
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800499
500bool DispatchIsGwpAsan(const MallocDispatch* dispatch) {
501 return dispatch == &gwp_asan_dispatch;
502}
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700503
Mitch Phillipse6997d52020-11-30 15:04:14 -0800504bool EnableGwpAsan(const android_mallopt_gwp_asan_options_t& options) {
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700505 if (GwpAsanInitialized) {
506 return true;
507 }
508
509 bool ret_value;
510 __libc_globals.mutate(
Mitch Phillipse6997d52020-11-30 15:04:14 -0800511 [&](libc_globals* globals) { ret_value = MaybeInitGwpAsan(globals, options); });
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700512 return ret_value;
513}