1 // Copyright 2021 The Chromium Authors
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 "partition_alloc/oom.h"
6
7 #include "build/build_config.h"
8 #include "partition_alloc/oom_callback.h"
9 #include "partition_alloc/partition_alloc_base/compiler_specific.h"
10 #include "partition_alloc/partition_alloc_base/debug/alias.h"
11 #include "partition_alloc/partition_alloc_base/immediate_crash.h"
12
13 #if BUILDFLAG(IS_WIN)
14 #include <windows.h>
15
16 #include <array>
17 #include <cstdlib>
18 #endif // BUILDFLAG(IS_WIN)
19
20 namespace partition_alloc {
21
22 size_t g_oom_size = 0U;
23
24 namespace internal {
25
26 // Crash server classifies base::internal::OnNoMemoryInternal as OOM.
27 // TODO(crbug.com/1151236): Update to
28 // partition_alloc::internal::base::internal::OnNoMemoryInternal
OnNoMemoryInternal(size_t size)29 PA_NOINLINE void OnNoMemoryInternal(size_t size) {
30 g_oom_size = size;
31 #if BUILDFLAG(IS_WIN)
32 // Kill the process. This is important for security since most of code
33 // does not check the result of memory allocation.
34 // https://msdn.microsoft.com/en-us/library/het71c37.aspx
35 // Pass the size of the failed request in an exception argument.
36 ULONG_PTR exception_args[] = {size};
37 ::RaiseException(win::kOomExceptionCode, EXCEPTION_NONCONTINUABLE,
38 std::size(exception_args), exception_args);
39
40 // Safety check, make sure process exits here.
41 _exit(win::kOomExceptionCode);
42 #else
43 size_t tmp_size = size;
44 internal::base::debug::Alias(&tmp_size);
45
46 // Note: Don't add anything that may allocate here. Depending on the
47 // allocator, this may be called from within the allocator (e.g. with
48 // PartitionAlloc), and would deadlock as our locks are not recursive.
49 //
50 // Additionally, this is unlikely to work, since allocating from an OOM
51 // handler is likely to fail.
52 //
53 // Use PA_IMMEDIATE_CRASH() so that the top frame in the crash is our code,
54 // rather than using abort() or similar; this avoids the crash server needing
55 // to be able to successfully unwind through libc to get to the correct
56 // address, which is particularly an issue on Android.
57 PA_IMMEDIATE_CRASH();
58 #endif // BUILDFLAG(IS_WIN)
59 }
60
61 } // namespace internal
62
TerminateBecauseOutOfMemory(size_t size)63 void TerminateBecauseOutOfMemory(size_t size) {
64 internal::OnNoMemoryInternal(size);
65 }
66
67 namespace internal {
68
69 // The crash is generated in a PA_NOINLINE function so that we can classify the
70 // crash as an OOM solely by analyzing the stack trace. It is tagged as
71 // PA_NOT_TAIL_CALLED to ensure that its parent function stays on the stack.
OnNoMemory(size_t size)72 [[noreturn]] PA_NOINLINE PA_NOT_TAIL_CALLED void OnNoMemory(size_t size) {
73 RunPartitionAllocOomCallback();
74 TerminateBecauseOutOfMemory(size);
75 PA_IMMEDIATE_CRASH();
76 }
77
78 } // namespace internal
79
80 } // namespace partition_alloc
81