1 // Copyright 2020 the V8 project 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 #include "src/heap/code-object-registry.h"
6
7 #include <algorithm>
8
9 #include "src/base/logging.h"
10
11 namespace v8 {
12 namespace internal {
13
RegisterNewlyAllocatedCodeObject(Address code)14 void CodeObjectRegistry::RegisterNewlyAllocatedCodeObject(Address code) {
15 if (is_sorted_) {
16 is_sorted_ =
17 (code_object_registry_.empty() || code_object_registry_.back() < code);
18 }
19 code_object_registry_.push_back(code);
20 }
21
RegisterAlreadyExistingCodeObject(Address code)22 void CodeObjectRegistry::RegisterAlreadyExistingCodeObject(Address code) {
23 DCHECK(is_sorted_);
24 DCHECK(code_object_registry_.empty() || code_object_registry_.back() < code);
25 code_object_registry_.push_back(code);
26 }
27
Clear()28 void CodeObjectRegistry::Clear() {
29 code_object_registry_.clear();
30 is_sorted_ = true;
31 }
32
Finalize()33 void CodeObjectRegistry::Finalize() {
34 DCHECK(is_sorted_);
35 code_object_registry_.shrink_to_fit();
36 }
37
Contains(Address object) const38 bool CodeObjectRegistry::Contains(Address object) const {
39 if (!is_sorted_) {
40 std::sort(code_object_registry_.begin(), code_object_registry_.end());
41 is_sorted_ = true;
42 }
43 return (std::binary_search(code_object_registry_.begin(),
44 code_object_registry_.end(), object));
45 }
46
GetCodeObjectStartFromInnerAddress(Address address) const47 Address CodeObjectRegistry::GetCodeObjectStartFromInnerAddress(
48 Address address) const {
49 if (!is_sorted_) {
50 std::sort(code_object_registry_.begin(), code_object_registry_.end());
51 is_sorted_ = true;
52 }
53
54 // The code registry can't be empty, else the code object can't exist.
55 DCHECK(!code_object_registry_.empty());
56
57 // std::upper_bound returns the first code object strictly greater than
58 // address, so the code object containing the address has to be the previous
59 // one.
60 auto it = std::upper_bound(code_object_registry_.begin(),
61 code_object_registry_.end(), address);
62 // The address has to be contained in a code object, so necessarily the
63 // address can't be smaller than the first code object.
64 DCHECK_NE(it, code_object_registry_.begin());
65 return *(--it);
66 }
67
68 } // namespace internal
69 } // namespace v8
70