1 /*
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 
29 #include <alloca.h>
30 #include <assert.h>
31 #include <ctype.h>
32 #include <stddef.h>
33 #include <stdint.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <sys/types.h>
38 
39 #include "gwp_asan/crash_handler.h"
40 #include "gwp_asan/guarded_pool_allocator.h"
41 #include "gwp_asan/options.h"
42 #include "gwp_asan_wrappers.h"
43 #include "malloc_common.h"
44 #include "platform/bionic/android_unsafe_frame_pointer_chase.h"
45 #include "platform/bionic/macros.h"
46 #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"
52 
53 #ifndef LIBC_STATIC
54 #include "bionic/malloc_common_dynamic.h"
55 #endif  // LIBC_STATIC
56 
57 static gwp_asan::GuardedPoolAllocator GuardedAlloc;
58 static const MallocDispatch* prev_dispatch;
59 
60 using Mode = android_mallopt_gwp_asan_options_t::Mode;
61 using Options = gwp_asan::options::Options;
62 
63 // basename() is a mess, see the manpage. Let's be explicit what handling we
64 // want (don't touch my string!).
65 extern "C" const char* __gnu_basename(const char* path);
66 
67 namespace {
68 
69 // ============================================================================
70 // Implementation of GWP-ASan malloc wrappers.
71 // ============================================================================
72 
gwp_asan_calloc(size_t n_elements,size_t elem_size)73 void* 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 
gwp_asan_free(void * mem)85 void 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 
gwp_asan_malloc(size_t bytes)93 void* 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 
gwp_asan_malloc_usable_size(const void * mem)102 size_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 
gwp_asan_realloc(void * old_mem,size_t bytes)109 void* gwp_asan_realloc(void* old_mem, size_t bytes) {
110   // 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.
114   if (__predict_false(GuardedAlloc.pointerIsMine(old_mem))) {
115     if (__predict_false(bytes == 0)) {
116       GuardedAlloc.deallocate(old_mem);
117       return nullptr;
118     }
119     void* new_ptr = gwp_asan_malloc(bytes);
120     // 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);
125     GuardedAlloc.deallocate(old_mem);
126     return new_ptr;
127   }
128   return prev_dispatch->realloc(old_mem, bytes);
129 }
130 
gwp_asan_malloc_iterate(uintptr_t base,size_t size,void (* callback)(uintptr_t base,size_t size,void * arg),void * arg)131 int 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 
gwp_asan_malloc_disable()142 void gwp_asan_malloc_disable() {
143   GuardedAlloc.disable();
144   prev_dispatch->malloc_disable();
145 }
146 
gwp_asan_malloc_enable()147 void gwp_asan_malloc_enable() {
148   GuardedAlloc.enable();
149   prev_dispatch->malloc_enable();
150 }
151 
152 const 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),
160 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
161     Malloc(pvalloc),
162 #endif
163     gwp_asan_realloc,
164 #if defined(HAVE_DEPRECATED_MALLOC_FUNCS)
165     Malloc(valloc),
166 #endif
167     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),
173 };
174 
isPowerOfTwo(uint64_t x)175 bool isPowerOfTwo(uint64_t x) {
176   assert(x != 0);
177   return (x & (x - 1)) == 0;
178 }
179 
ShouldGwpAsanSampleProcess(unsigned sample_rate)180 bool 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 
187   uint8_t random_number;
188   __libc_safe_arc4random_buf(&random_number, sizeof(random_number));
189   return random_number % sample_rate == 0;
190 }
191 
192 bool GwpAsanInitialized = false;
193 bool GwpAsanRecoverable = false;
194 
195 // The probability (1 / SampleRate) that an allocation gets chosen to be put
196 // into the special GWP-ASan pool.
197 using SampleRate_t = typeof(gwp_asan::options::Options::SampleRate);
198 constexpr SampleRate_t kDefaultSampleRate = 2500;
199 static const char* kSampleRateSystemSysprop = "libc.debug.gwp_asan.sample_rate.system_default";
200 static const char* kSampleRateAppSysprop = "libc.debug.gwp_asan.sample_rate.app_default";
201 static const char* kSampleRateTargetedSyspropPrefix = "libc.debug.gwp_asan.sample_rate.";
202 static 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.
207 constexpr unsigned kDefaultProcessSampling = 128;
208 static const char* kProcessSamplingSystemSysprop =
209     "libc.debug.gwp_asan.process_sampling.system_default";
210 static const char* kProcessSamplingAppSysprop = "libc.debug.gwp_asan.process_sampling.app_default";
211 static const char* kProcessSamplingTargetedSyspropPrefix = "libc.debug.gwp_asan.process_sampling.";
212 static 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).
220 using SimultaneousAllocations_t = typeof(gwp_asan::options::Options::MaxSimultaneousAllocations);
221 constexpr SimultaneousAllocations_t kDefaultMaxAllocs = 32;
222 static const char* kMaxAllocsSystemSysprop = "libc.debug.gwp_asan.max_allocs.system_default";
223 static const char* kMaxAllocsAppSysprop = "libc.debug.gwp_asan.max_allocs.app_default";
224 static const char* kMaxAllocsTargetedSyspropPrefix = "libc.debug.gwp_asan.max_allocs.";
225 static const char* kMaxAllocsEnvVar = "GWP_ASAN_MAX_ALLOCS";
226 
227 static const char* kRecoverableSystemSysprop = "libc.debug.gwp_asan.recoverable.system_default";
228 static const char* kRecoverableAppSysprop = "libc.debug.gwp_asan.recoverable.app_default";
229 static const char* kRecoverableTargetedSyspropPrefix = "libc.debug.gwp_asan.recoverable.";
230 static const char* kRecoverableEnvVar = "GWP_ASAN_RECOVERABLE";
231 
232 static const char kPersistPrefix[] = "persist.";
233 
NeedsGwpAsanRecovery(void * fault_ptr)234 bool 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 
GwpAsanPreCrashHandler(void * fault_ptr)241 void GwpAsanPreCrashHandler(void* fault_ptr) {
242   fault_ptr = untag_address(fault_ptr);
243   if (!NeedsGwpAsanRecovery(fault_ptr)) return;
244   GuardedAlloc.preCrashReport(fault_ptr);
245 }
246 
GwpAsanPostCrashHandler(void * fault_ptr)247 void GwpAsanPostCrashHandler(void* fault_ptr) {
248   fault_ptr = untag_address(fault_ptr);
249   if (!NeedsGwpAsanRecovery(fault_ptr)) return;
250   GuardedAlloc.postCrashReportRecoverableOnly(fault_ptr);
251 }
252 
SetDefaultGwpAsanOptions(Options * options,unsigned * process_sample_rate,const android_mallopt_gwp_asan_options_t & mallopt_options)253 void 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   options->Recoverable = true;
262   GwpAsanRecoverable = true;
263 
264   if (mallopt_options.mode == Mode::SYSTEM_PROCESS_OR_SYSTEM_APP ||
265       mallopt_options.mode == Mode::APP_MANIFEST_DEFAULT) {
266     *process_sample_rate = kDefaultProcessSampling;
267   } else {
268     *process_sample_rate = 1;
269   }
270 }
271 
GetGwpAsanOptionImpl(char * value_out,const android_mallopt_gwp_asan_options_t & mallopt_options,const char * system_sysprop,const char * app_sysprop,const char * targeted_sysprop_prefix,const char * env_var)272 bool 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) {
276   const char* basename = "";
277   if (mallopt_options.program_name) basename = __gnu_basename(mallopt_options.program_name);
278 
279   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] = {};
284   // 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') {
287     const char* default_sysprop = system_sysprop;
288     if (mallopt_options.mode == Mode::APP_MANIFEST_ALWAYS) {
289       default_sysprop = app_sysprop;
290     }
291     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;
308   }
309 
310   return get_config_from_env_or_sysprops(env_var, sysprop_names, arraysize(sysprop_names),
311                                          value_out, PROP_VALUE_MAX);
312 }
313 
GetGwpAsanIntegerOption(unsigned long long * result,const android_mallopt_gwp_asan_options_t & mallopt_options,const char * system_sysprop,const char * app_sysprop,const char * targeted_sysprop_prefix,const char * env_var,const char * descriptive_name)314 bool 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)) {
322     return false;
323   }
324   char* end;
325   unsigned long long value = strtoull(buffer, &end, 10);
326   if (value == ULLONG_MAX || *end != '\0') {
327     warning_log("Invalid GWP-ASan %s: \"%s\". Using default value instead.", descriptive_name,
328                 buffer);
329     return false;
330   }
331 
332   *result = value;
333   return true;
334 }
335 
GetGwpAsanBoolOption(bool * result,const android_mallopt_gwp_asan_options_t & mallopt_options,const char * system_sysprop,const char * app_sysprop,const char * targeted_sysprop_prefix,const char * env_var,const char * descriptive_name)336 bool 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 
363 // 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.
GetGwpAsanOptions(Options * options,unsigned * process_sample_rate,const android_mallopt_gwp_asan_options_t & mallopt_options)370 bool 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);
373 
374   bool had_overrides = false;
375 
376   unsigned long long buf;
377   if (GetGwpAsanIntegerOption(&buf, mallopt_options, kSampleRateSystemSysprop,
378                               kSampleRateAppSysprop, kSampleRateTargetedSyspropPrefix,
379                               kSampleRateEnvVar, "sample rate")) {
380     options->SampleRate = buf;
381     had_overrides = true;
382   }
383 
384   if (GetGwpAsanIntegerOption(&buf, mallopt_options, kProcessSamplingSystemSysprop,
385                               kProcessSamplingAppSysprop, kProcessSamplingTargetedSyspropPrefix,
386                               kProcessSamplingEnvVar, "process sampling rate")) {
387     *process_sample_rate = buf;
388     had_overrides = true;
389   }
390 
391   if (GetGwpAsanIntegerOption(&buf, mallopt_options, kMaxAllocsSystemSysprop, kMaxAllocsAppSysprop,
392                               kMaxAllocsTargetedSyspropPrefix, kMaxAllocsEnvVar,
393                               "maximum simultaneous allocations")) {
394     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   }
405 
406   bool recoverable = true;
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 
415   return had_overrides;
416 }
417 
MaybeInitGwpAsan(libc_globals * globals,const android_mallopt_gwp_asan_options_t & mallopt_options)418 bool MaybeInitGwpAsan(libc_globals* globals,
419                       const android_mallopt_gwp_asan_options_t& mallopt_options) {
420   if (GwpAsanInitialized) {
421     error_log("GWP-ASan was already initialized for this process.");
422     return false;
423   }
424 
425   Options options;
426   unsigned process_sample_rate = kDefaultProcessSampling;
427   if (!GetGwpAsanOptions(&options, &process_sample_rate, mallopt_options) &&
428       mallopt_options.mode == Mode::APP_MANIFEST_NEVER) {
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)) {
438     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.
456   // 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);
459 
460   // 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   }
465 
466   GwpAsanInitialized = true;
467 
468   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();
474   __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;
477 
478   return true;
479 }
480 };  // anonymous namespace
481 
MaybeInitGwpAsanFromLibc(libc_globals * globals)482 bool 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.mode = Mode::SYSTEM_PROCESS_OR_SYSTEM_APP;
496 
497   return MaybeInitGwpAsan(globals, mallopt_options);
498 }
499 
DispatchIsGwpAsan(const MallocDispatch * dispatch)500 bool DispatchIsGwpAsan(const MallocDispatch* dispatch) {
501   return dispatch == &gwp_asan_dispatch;
502 }
503 
EnableGwpAsan(const android_mallopt_gwp_asan_options_t & options)504 bool EnableGwpAsan(const android_mallopt_gwp_asan_options_t& options) {
505   if (GwpAsanInitialized) {
506     return true;
507   }
508 
509   bool ret_value;
510   __libc_globals.mutate(
511       [&](libc_globals* globals) { ret_value = MaybeInitGwpAsan(globals, options); });
512   return ret_value;
513 }
514