1 // Copyright (c) 2018 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef THIRD_PARTY_BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_COOKIE_H_
6 #define THIRD_PARTY_BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_COOKIE_H_
7
8 #include "third_party/base/compiler_specific.h"
9 #include "third_party/base/logging.h"
10
11 namespace pdfium {
12 namespace base {
13 namespace internal {
14
15 #if DCHECK_IS_ON()
16 // Handles alignment up to XMM instructions on Intel.
17 static constexpr size_t kCookieSize = 16;
18
19 static constexpr unsigned char kCookieValue[kCookieSize] = {
20 0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xD0, 0x0D,
21 0x13, 0x37, 0xF0, 0x05, 0xBA, 0x11, 0xAB, 0x1E};
22 #endif
23
PartitionCookieCheckValue(void * ptr)24 ALWAYS_INLINE void PartitionCookieCheckValue(void* ptr) {
25 #if DCHECK_IS_ON()
26 unsigned char* cookie_ptr = reinterpret_cast<unsigned char*>(ptr);
27 for (size_t i = 0; i < kCookieSize; ++i, ++cookie_ptr)
28 DCHECK(*cookie_ptr == kCookieValue[i]);
29 #endif
30 }
31
PartitionCookieSizeAdjustAdd(size_t size)32 ALWAYS_INLINE size_t PartitionCookieSizeAdjustAdd(size_t size) {
33 #if DCHECK_IS_ON()
34 // Add space for cookies, checking for integer overflow. TODO(palmer):
35 // Investigate the performance and code size implications of using
36 // CheckedNumeric throughout PA.
37 DCHECK(size + (2 * kCookieSize) > size);
38 size += 2 * kCookieSize;
39 #endif
40 return size;
41 }
42
PartitionCookieFreePointerAdjust(void * ptr)43 ALWAYS_INLINE void* PartitionCookieFreePointerAdjust(void* ptr) {
44 #if DCHECK_IS_ON()
45 // The value given to the application is actually just after the cookie.
46 ptr = static_cast<char*>(ptr) - kCookieSize;
47 #endif
48 return ptr;
49 }
50
PartitionCookieSizeAdjustSubtract(size_t size)51 ALWAYS_INLINE size_t PartitionCookieSizeAdjustSubtract(size_t size) {
52 #if DCHECK_IS_ON()
53 // Remove space for cookies.
54 DCHECK(size >= 2 * kCookieSize);
55 size -= 2 * kCookieSize;
56 #endif
57 return size;
58 }
59
PartitionCookieWriteValue(void * ptr)60 ALWAYS_INLINE void PartitionCookieWriteValue(void* ptr) {
61 #if DCHECK_IS_ON()
62 unsigned char* cookie_ptr = reinterpret_cast<unsigned char*>(ptr);
63 for (size_t i = 0; i < kCookieSize; ++i, ++cookie_ptr)
64 *cookie_ptr = kCookieValue[i];
65 #endif
66 }
67
68 } // namespace internal
69 } // namespace base
70 } // namespace pdfium
71
72 #endif // THIRD_PARTY_BASE_ALLOCATOR_PARTITION_ALLOCATOR_PARTITION_COOKIE_H_
73