blob: 2f513e5a632e2fe3ef459e9d0cad85d467428fb5 [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) {
108 if (__predict_false(GuardedAlloc.pointerIsMine(old_mem))) {
109 size_t old_size = GuardedAlloc.getSize(old_mem);
110 void* new_ptr = gwp_asan_malloc(bytes);
111 if (new_ptr) memcpy(new_ptr, old_mem, (bytes < old_size) ? bytes : old_size);
112 GuardedAlloc.deallocate(old_mem);
113 return new_ptr;
114 }
115 return prev_dispatch->realloc(old_mem, bytes);
116}
117
118int gwp_asan_malloc_iterate(uintptr_t base, size_t size,
119 void (*callback)(uintptr_t base, size_t size, void* arg), void* arg) {
120 if (__predict_false(GuardedAlloc.pointerIsMine(reinterpret_cast<void*>(base)))) {
121 // TODO(mitchp): GPA::iterate() returns void, but should return int.
122 // TODO(mitchp): GPA::iterate() should take uintptr_t, not void*.
123 GuardedAlloc.iterate(reinterpret_cast<void*>(base), size, callback, arg);
124 return 0;
125 }
126 return prev_dispatch->malloc_iterate(base, size, callback, arg);
127}
128
129void gwp_asan_malloc_disable() {
130 GuardedAlloc.disable();
131 prev_dispatch->malloc_disable();
132}
133
134void gwp_asan_malloc_enable() {
135 GuardedAlloc.enable();
136 prev_dispatch->malloc_enable();
137}
138
Mitch Phillipse6997d52020-11-30 15:04:14 -0800139const MallocDispatch gwp_asan_dispatch __attribute__((unused)) = {
140 gwp_asan_calloc,
141 gwp_asan_free,
142 Malloc(mallinfo),
143 gwp_asan_malloc,
144 gwp_asan_malloc_usable_size,
145 Malloc(memalign),
146 Malloc(posix_memalign),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800147#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Mitch Phillipse6997d52020-11-30 15:04:14 -0800148 Malloc(pvalloc),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800149#endif
Mitch Phillipse6997d52020-11-30 15:04:14 -0800150 gwp_asan_realloc,
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800151#if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
Mitch Phillipse6997d52020-11-30 15:04:14 -0800152 Malloc(valloc),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800153#endif
Mitch Phillipse6997d52020-11-30 15:04:14 -0800154 gwp_asan_malloc_iterate,
155 gwp_asan_malloc_disable,
156 gwp_asan_malloc_enable,
157 Malloc(mallopt),
158 Malloc(aligned_alloc),
159 Malloc(malloc_info),
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800160};
161
Mitch Phillipse6997d52020-11-30 15:04:14 -0800162bool isPowerOfTwo(uint64_t x) {
163 assert(x != 0);
164 return (x & (x - 1)) == 0;
165}
Mitch Phillips0083b0f2020-02-13 17:37:11 -0800166
Mitch Phillipse6997d52020-11-30 15:04:14 -0800167bool ShouldGwpAsanSampleProcess(unsigned sample_rate) {
168 if (!isPowerOfTwo(sample_rate)) {
169 warning_log(
170 "GWP-ASan process sampling rate of %u is not a power-of-two, and so modulo bias occurs.",
171 sample_rate);
172 }
173
Mitch Phillips0083b0f2020-02-13 17:37:11 -0800174 uint8_t random_number;
175 __libc_safe_arc4random_buf(&random_number, sizeof(random_number));
Mitch Phillipse6997d52020-11-30 15:04:14 -0800176 return random_number % sample_rate == 0;
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800177}
178
Mitch Phillipse6997d52020-11-30 15:04:14 -0800179bool GwpAsanInitialized = false;
180
181// The probability (1 / SampleRate) that an allocation gets chosen to be put
182// into the special GWP-ASan pool.
183using SampleRate_t = typeof(gwp_asan::options::Options::SampleRate);
184constexpr SampleRate_t kDefaultSampleRate = 2500;
185static const char* kSampleRateSystemSysprop = "libc.debug.gwp_asan.sample_rate.system_default";
186static const char* kSampleRateAppSysprop = "libc.debug.gwp_asan.sample_rate.app_default";
187static const char* kSampleRateTargetedSyspropPrefix = "libc.debug.gwp_asan.sample_rate.";
188static const char* kSampleRateEnvVar = "GWP_ASAN_SAMPLE_RATE";
189
190// The probability (1 / ProcessSampling) that a process will be randomly
191// selected for sampling, for system apps and system processes. The process
192// sampling rate should always be a power of two to avoid modulo bias.
193constexpr unsigned kDefaultProcessSampling = 128;
194static const char* kProcessSamplingSystemSysprop =
195 "libc.debug.gwp_asan.process_sampling.system_default";
196static const char* kProcessSamplingAppSysprop = "libc.debug.gwp_asan.process_sampling.app_default";
197static const char* kProcessSamplingTargetedSyspropPrefix = "libc.debug.gwp_asan.process_sampling.";
198static const char* kProcessSamplingEnvVar = "GWP_ASAN_PROCESS_SAMPLING";
199
200// The upper limit of simultaneous allocations supported by GWP-ASan. Any
201// allocations in excess of this limit will be passed to the backing allocator
202// and can't be sampled. This value, if unspecified, will be automatically
203// calculated to keep the same ratio as the default (2500 sampling : 32 allocs).
204// So, if you specify GWP_ASAN_SAMPLE_RATE=1250 (i.e. twice as frequent), we'll
205// automatically calculate that we need double the slots (64).
206using SimultaneousAllocations_t = typeof(gwp_asan::options::Options::MaxSimultaneousAllocations);
207constexpr SimultaneousAllocations_t kDefaultMaxAllocs = 32;
208static const char* kMaxAllocsSystemSysprop = "libc.debug.gwp_asan.max_allocs.system_default";
209static const char* kMaxAllocsAppSysprop = "libc.debug.gwp_asan.max_allocs.app_default";
210static const char* kMaxAllocsTargetedSyspropPrefix = "libc.debug.gwp_asan.max_allocs.";
211static const char* kMaxAllocsEnvVar = "GWP_ASAN_MAX_ALLOCS";
212
213void SetDefaultGwpAsanOptions(Options* options, unsigned* process_sample_rate,
214 const android_mallopt_gwp_asan_options_t& mallopt_options) {
215 options->Enabled = true;
216 options->InstallSignalHandlers = false;
217 options->InstallForkHandlers = true;
218 options->Backtrace = android_unsafe_frame_pointer_chase;
219 options->SampleRate = kDefaultSampleRate;
220 options->MaxSimultaneousAllocations = kDefaultMaxAllocs;
221
222 *process_sample_rate = 1;
223 if (mallopt_options.desire == Action::TURN_ON_WITH_SAMPLING) {
224 *process_sample_rate = kDefaultProcessSampling;
225 }
226}
227
228bool GetGwpAsanOption(unsigned long long* result,
229 const android_mallopt_gwp_asan_options_t& mallopt_options,
230 const char* system_sysprop, const char* app_sysprop,
231 const char* targeted_sysprop_prefix, const char* env_var,
232 const char* descriptive_name) {
233 const char* basename = "";
234 if (mallopt_options.program_name) basename = __gnu_basename(mallopt_options.program_name);
235
236 size_t program_specific_sysprop_size = strlen(targeted_sysprop_prefix) + strlen(basename) + 1;
237 char* program_specific_sysprop_name = static_cast<char*>(alloca(program_specific_sysprop_size));
238 async_safe_format_buffer(program_specific_sysprop_name, program_specific_sysprop_size, "%s%s",
239 targeted_sysprop_prefix, basename);
240
241 const char* sysprop_names[2] = {nullptr, nullptr};
242 // Tests use a blank program name to specify that system properties should not
243 // be used. Tests still continue to use the environment variable though.
244 if (*basename != '\0') {
245 sysprop_names[0] = program_specific_sysprop_name;
246 if (mallopt_options.desire == Action::TURN_ON_FOR_APP) {
247 sysprop_names[1] = app_sysprop;
248 } else {
249 sysprop_names[1] = system_sysprop;
250 }
251 }
252
253 char settings_buf[PROP_VALUE_MAX];
254 if (!get_config_from_env_or_sysprops(env_var, sysprop_names,
255 /* sys_prop_names_size */ 2, settings_buf, PROP_VALUE_MAX)) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800256 return false;
257 }
Mitch Phillipse6997d52020-11-30 15:04:14 -0800258
259 char* end;
260 unsigned long long value = strtoull(settings_buf, &end, 10);
261 if (value == ULLONG_MAX || *end != '\0') {
262 warning_log("Invalid GWP-ASan %s: \"%s\". Using default value instead.", descriptive_name,
263 settings_buf);
264 return false;
265 }
266
267 *result = value;
268 return true;
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800269}
270
Mitch Phillipse6997d52020-11-30 15:04:14 -0800271// Initialize the GWP-ASan options structure in *options, taking into account whether someone has
272// asked for specific GWP-ASan settings. The order of priority is:
273// 1. Environment variables.
274// 2. Process-specific system properties.
275// 3. Global system properties.
276// If any of these overrides are found, we return true. Otherwise, use the default values, and
277// return false.
278bool GetGwpAsanOptions(Options* options, unsigned* process_sample_rate,
279 const android_mallopt_gwp_asan_options_t& mallopt_options) {
280 SetDefaultGwpAsanOptions(options, process_sample_rate, mallopt_options);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800281
Mitch Phillipse6997d52020-11-30 15:04:14 -0800282 bool had_overrides = false;
283
284 unsigned long long buf;
285 if (GetGwpAsanOption(&buf, mallopt_options, kSampleRateSystemSysprop, kSampleRateAppSysprop,
286 kSampleRateTargetedSyspropPrefix, kSampleRateEnvVar, "sample rate")) {
287 options->SampleRate = buf;
288 had_overrides = true;
289 }
290
291 if (GetGwpAsanOption(&buf, mallopt_options, kProcessSamplingSystemSysprop,
292 kProcessSamplingAppSysprop, kProcessSamplingTargetedSyspropPrefix,
293 kProcessSamplingEnvVar, "process sampling rate")) {
294 *process_sample_rate = buf;
295 had_overrides = true;
296 }
297
298 if (GetGwpAsanOption(&buf, mallopt_options, kMaxAllocsSystemSysprop, kMaxAllocsAppSysprop,
299 kMaxAllocsTargetedSyspropPrefix, kMaxAllocsEnvVar,
300 "maximum simultaneous allocations")) {
301 options->MaxSimultaneousAllocations = buf;
302 had_overrides = true;
303 } else if (had_overrides) {
304 // Multiply the number of slots available, such that the ratio between
305 // sampling rate and slots is kept the same as the default. For example, a
306 // sampling rate of 1000 is 2.5x more frequent than default, and so
307 // requires 80 slots (32 * 2.5).
308 float frequency_multiplier = static_cast<float>(options->SampleRate) / kDefaultSampleRate;
309 options->MaxSimultaneousAllocations =
310 /* default */ kDefaultMaxAllocs / frequency_multiplier;
311 }
312 return had_overrides;
313}
314
315bool MaybeInitGwpAsan(libc_globals* globals,
316 const android_mallopt_gwp_asan_options_t& mallopt_options) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800317 if (GwpAsanInitialized) {
318 error_log("GWP-ASan was already initialized for this process.");
319 return false;
320 }
321
Mitch Phillipse6997d52020-11-30 15:04:14 -0800322 Options options;
323 unsigned process_sample_rate = kDefaultProcessSampling;
324 if (!GetGwpAsanOptions(&options, &process_sample_rate, mallopt_options) &&
325 mallopt_options.desire == Action::DONT_TURN_ON_UNLESS_OVERRIDDEN) {
326 return false;
327 }
328
329 if (options.SampleRate == 0 || process_sample_rate == 0 ||
330 options.MaxSimultaneousAllocations == 0) {
331 return false;
332 }
333
334 if (!ShouldGwpAsanSampleProcess(process_sample_rate)) {
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800335 return false;
336 }
337
338 // GWP-ASan is compatible with heapprofd/malloc_debug/malloc_hooks iff
339 // GWP-ASan was installed first. If one of these other libraries was already
340 // installed, we don't enable GWP-ASan. These libraries are normally enabled
341 // in libc_init after GWP-ASan, but if the new process is a zygote child and
342 // trying to initialize GWP-ASan through mallopt(), one of these libraries may
343 // be installed. It may be possible to change this in future by modifying the
344 // internal dispatch pointers of these libraries at this point in time, but
345 // given that they're all debug-only, we don't really mind for now.
346 if (GetDefaultDispatchTable() != nullptr) {
347 // Something else is installed.
348 return false;
349 }
350
351 // GWP-ASan's initialization is always called in a single-threaded context, so
352 // we can initialize lock-free.
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800353 // Set GWP-ASan as the malloc dispatch table.
354 globals->malloc_dispatch_table = gwp_asan_dispatch;
355 atomic_store(&globals->default_dispatch_table, &gwp_asan_dispatch);
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800356
Mitch Phillipsbba80dc2020-02-11 14:42:14 -0800357 // If malloc_limit isn't installed, we can skip the default_dispatch_table
358 // lookup.
359 if (GetDispatchTable() == nullptr) {
360 atomic_store(&globals->current_dispatch_table, &gwp_asan_dispatch);
361 }
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800362
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800363 GwpAsanInitialized = true;
364
Mitch Phillipse6997d52020-11-30 15:04:14 -0800365 prev_dispatch = NativeAllocatorDispatch();
366
367 GuardedAlloc.init(options);
368
369 __libc_shared_globals()->gwp_asan_state = GuardedAlloc.getAllocatorState();
370 __libc_shared_globals()->gwp_asan_metadata = GuardedAlloc.getMetadataRegion();
Mitch Phillipsf3968e82020-01-31 19:57:04 -0800371
372 return true;
373}
Mitch Phillipse6997d52020-11-30 15:04:14 -0800374}; // anonymous namespace
375
376bool MaybeInitGwpAsanFromLibc(libc_globals* globals) {
377 // Never initialize the Zygote here. A Zygote chosen for sampling would also
378 // have all of its children sampled. Instead, the Zygote child will choose
379 // whether it samples or not just after the Zygote forks. Note that the Zygote
380 // changes its name after it's started, at this point it's still called
381 // "app_process" or "app_process64".
382 static const char kAppProcessNamePrefix[] = "app_process";
383 const char* progname = getprogname();
384 if (strncmp(progname, kAppProcessNamePrefix, sizeof(kAppProcessNamePrefix) - 1) == 0)
385 return false;
386
387 android_mallopt_gwp_asan_options_t mallopt_options;
388 mallopt_options.program_name = progname;
389 mallopt_options.desire = Action::TURN_ON_WITH_SAMPLING;
390
391 return MaybeInitGwpAsan(globals, mallopt_options);
392}
Mitch Phillipsc03856c2020-02-13 16:41:14 -0800393
394bool DispatchIsGwpAsan(const MallocDispatch* dispatch) {
395 return dispatch == &gwp_asan_dispatch;
396}
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700397
Mitch Phillipse6997d52020-11-30 15:04:14 -0800398bool EnableGwpAsan(const android_mallopt_gwp_asan_options_t& options) {
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700399 if (GwpAsanInitialized) {
400 return true;
401 }
402
403 bool ret_value;
404 __libc_globals.mutate(
Mitch Phillipse6997d52020-11-30 15:04:14 -0800405 [&](libc_globals* globals) { ret_value = MaybeInitGwpAsan(globals, options); });
Christopher Ferris8f9713e2021-09-20 17:25:46 -0700406 return ret_value;
407}