xref: /aosp_15_r20/art/dex2oat/linker/image_writer.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1*795d594fSAndroid Build Coastguard Worker /*
2*795d594fSAndroid Build Coastguard Worker  * Copyright (C) 2011 The Android Open Source Project
3*795d594fSAndroid Build Coastguard Worker  *
4*795d594fSAndroid Build Coastguard Worker  * Licensed under the Apache License, Version 2.0 (the "License");
5*795d594fSAndroid Build Coastguard Worker  * you may not use this file except in compliance with the License.
6*795d594fSAndroid Build Coastguard Worker  * You may obtain a copy of the License at
7*795d594fSAndroid Build Coastguard Worker  *
8*795d594fSAndroid Build Coastguard Worker  *      http://www.apache.org/licenses/LICENSE-2.0
9*795d594fSAndroid Build Coastguard Worker  *
10*795d594fSAndroid Build Coastguard Worker  * Unless required by applicable law or agreed to in writing, software
11*795d594fSAndroid Build Coastguard Worker  * distributed under the License is distributed on an "AS IS" BASIS,
12*795d594fSAndroid Build Coastguard Worker  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*795d594fSAndroid Build Coastguard Worker  * See the License for the specific language governing permissions and
14*795d594fSAndroid Build Coastguard Worker  * limitations under the License.
15*795d594fSAndroid Build Coastguard Worker  */
16*795d594fSAndroid Build Coastguard Worker 
17*795d594fSAndroid Build Coastguard Worker #include "image_writer.h"
18*795d594fSAndroid Build Coastguard Worker 
19*795d594fSAndroid Build Coastguard Worker #include <lz4.h>
20*795d594fSAndroid Build Coastguard Worker #include <lz4hc.h>
21*795d594fSAndroid Build Coastguard Worker #include <sys/stat.h>
22*795d594fSAndroid Build Coastguard Worker #include <zlib.h>
23*795d594fSAndroid Build Coastguard Worker 
24*795d594fSAndroid Build Coastguard Worker #include <charconv>
25*795d594fSAndroid Build Coastguard Worker #include <memory>
26*795d594fSAndroid Build Coastguard Worker #include <numeric>
27*795d594fSAndroid Build Coastguard Worker #include <vector>
28*795d594fSAndroid Build Coastguard Worker 
29*795d594fSAndroid Build Coastguard Worker #include "android-base/strings.h"
30*795d594fSAndroid Build Coastguard Worker #include "art_field-inl.h"
31*795d594fSAndroid Build Coastguard Worker #include "art_method-inl.h"
32*795d594fSAndroid Build Coastguard Worker #include "base/callee_save_type.h"
33*795d594fSAndroid Build Coastguard Worker #include "base/globals.h"
34*795d594fSAndroid Build Coastguard Worker #include "base/logging.h"  // For VLOG.
35*795d594fSAndroid Build Coastguard Worker #include "base/pointer_size.h"
36*795d594fSAndroid Build Coastguard Worker #include "base/stl_util.h"
37*795d594fSAndroid Build Coastguard Worker #include "base/unix_file/fd_file.h"
38*795d594fSAndroid Build Coastguard Worker #include "class_linker-inl.h"
39*795d594fSAndroid Build Coastguard Worker #include "class_root-inl.h"
40*795d594fSAndroid Build Coastguard Worker #include "dex/dex_file-inl.h"
41*795d594fSAndroid Build Coastguard Worker #include "dex/dex_file_types.h"
42*795d594fSAndroid Build Coastguard Worker #include "driver/compiler_options.h"
43*795d594fSAndroid Build Coastguard Worker #include "elf/elf_utils.h"
44*795d594fSAndroid Build Coastguard Worker #include "entrypoints/entrypoint_utils-inl.h"
45*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/card_table-inl.h"
46*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/heap_bitmap.h"
47*795d594fSAndroid Build Coastguard Worker #include "gc/accounting/space_bitmap-inl.h"
48*795d594fSAndroid Build Coastguard Worker #include "gc/collector/concurrent_copying.h"
49*795d594fSAndroid Build Coastguard Worker #include "gc/heap-visit-objects-inl.h"
50*795d594fSAndroid Build Coastguard Worker #include "gc/heap.h"
51*795d594fSAndroid Build Coastguard Worker #include "gc/space/large_object_space.h"
52*795d594fSAndroid Build Coastguard Worker #include "gc/space/region_space.h"
53*795d594fSAndroid Build Coastguard Worker #include "gc/space/space-inl.h"
54*795d594fSAndroid Build Coastguard Worker #include "gc/verification.h"
55*795d594fSAndroid Build Coastguard Worker #include "handle_scope-inl.h"
56*795d594fSAndroid Build Coastguard Worker #include "imt_conflict_table.h"
57*795d594fSAndroid Build Coastguard Worker #include "indirect_reference_table-inl.h"
58*795d594fSAndroid Build Coastguard Worker #include "intern_table-inl.h"
59*795d594fSAndroid Build Coastguard Worker #include "jni/java_vm_ext-inl.h"
60*795d594fSAndroid Build Coastguard Worker #include "jni/jni_internal.h"
61*795d594fSAndroid Build Coastguard Worker #include "linear_alloc.h"
62*795d594fSAndroid Build Coastguard Worker #include "lock_word.h"
63*795d594fSAndroid Build Coastguard Worker #include "mirror/array-inl.h"
64*795d594fSAndroid Build Coastguard Worker #include "mirror/class-inl.h"
65*795d594fSAndroid Build Coastguard Worker #include "mirror/class_ext-inl.h"
66*795d594fSAndroid Build Coastguard Worker #include "mirror/class_loader.h"
67*795d594fSAndroid Build Coastguard Worker #include "mirror/dex_cache-inl.h"
68*795d594fSAndroid Build Coastguard Worker #include "mirror/dex_cache.h"
69*795d594fSAndroid Build Coastguard Worker #include "mirror/executable.h"
70*795d594fSAndroid Build Coastguard Worker #include "mirror/method.h"
71*795d594fSAndroid Build Coastguard Worker #include "mirror/object-inl.h"
72*795d594fSAndroid Build Coastguard Worker #include "mirror/object-refvisitor-inl.h"
73*795d594fSAndroid Build Coastguard Worker #include "mirror/object_array-alloc-inl.h"
74*795d594fSAndroid Build Coastguard Worker #include "mirror/object_array-inl.h"
75*795d594fSAndroid Build Coastguard Worker #include "mirror/string-inl.h"
76*795d594fSAndroid Build Coastguard Worker #include "mirror/var_handle.h"
77*795d594fSAndroid Build Coastguard Worker #include "nterp_helpers-inl.h"
78*795d594fSAndroid Build Coastguard Worker #include "nterp_helpers.h"
79*795d594fSAndroid Build Coastguard Worker #include "oat/elf_file.h"
80*795d594fSAndroid Build Coastguard Worker #include "oat/image-inl.h"
81*795d594fSAndroid Build Coastguard Worker #include "oat/jni_stub_hash_map-inl.h"
82*795d594fSAndroid Build Coastguard Worker #include "oat/oat.h"
83*795d594fSAndroid Build Coastguard Worker #include "oat/oat_file.h"
84*795d594fSAndroid Build Coastguard Worker #include "oat/oat_file_manager.h"
85*795d594fSAndroid Build Coastguard Worker #include "optimizing/intrinsic_objects.h"
86*795d594fSAndroid Build Coastguard Worker #include "runtime.h"
87*795d594fSAndroid Build Coastguard Worker #include "scoped_thread_state_change-inl.h"
88*795d594fSAndroid Build Coastguard Worker #include "subtype_check.h"
89*795d594fSAndroid Build Coastguard Worker #include "thread-current-inl.h"  // For AssertOnly1Thread.
90*795d594fSAndroid Build Coastguard Worker #include "thread_list.h"         // For AssertOnly1Thread.
91*795d594fSAndroid Build Coastguard Worker #include "well_known_classes-inl.h"
92*795d594fSAndroid Build Coastguard Worker 
93*795d594fSAndroid Build Coastguard Worker using ::art::mirror::Class;
94*795d594fSAndroid Build Coastguard Worker using ::art::mirror::DexCache;
95*795d594fSAndroid Build Coastguard Worker using ::art::mirror::Object;
96*795d594fSAndroid Build Coastguard Worker using ::art::mirror::ObjectArray;
97*795d594fSAndroid Build Coastguard Worker using ::art::mirror::String;
98*795d594fSAndroid Build Coastguard Worker 
99*795d594fSAndroid Build Coastguard Worker namespace art {
100*795d594fSAndroid Build Coastguard Worker namespace linker {
101*795d594fSAndroid Build Coastguard Worker 
102*795d594fSAndroid Build Coastguard Worker // The actual value of `kImageClassTableMinLoadFactor` is irrelevant because image class tables
103*795d594fSAndroid Build Coastguard Worker // are never resized, but we still need to pass a reasonable value to the constructor.
104*795d594fSAndroid Build Coastguard Worker constexpr double kImageClassTableMinLoadFactor = 0.5;
105*795d594fSAndroid Build Coastguard Worker // We use `kImageClassTableMaxLoadFactor` to determine the buffer size for image class tables
106*795d594fSAndroid Build Coastguard Worker // to make them full. We never insert additional elements to them, so we do not want to waste
107*795d594fSAndroid Build Coastguard Worker // extra memory. And unlike runtime class tables, we do not want this to depend on runtime
108*795d594fSAndroid Build Coastguard Worker // properties (see `Runtime::GetHashTableMaxLoadFactor()` checking for low memory mode).
109*795d594fSAndroid Build Coastguard Worker constexpr double kImageClassTableMaxLoadFactor = 0.6;
110*795d594fSAndroid Build Coastguard Worker 
111*795d594fSAndroid Build Coastguard Worker // The actual value of `kImageInternTableMinLoadFactor` is irrelevant because image intern tables
112*795d594fSAndroid Build Coastguard Worker // are never resized, but we still need to pass a reasonable value to the constructor.
113*795d594fSAndroid Build Coastguard Worker constexpr double kImageInternTableMinLoadFactor = 0.5;
114*795d594fSAndroid Build Coastguard Worker // We use `kImageInternTableMaxLoadFactor` to determine the buffer size for image intern tables
115*795d594fSAndroid Build Coastguard Worker // to make them full. We never insert additional elements to them, so we do not want to waste
116*795d594fSAndroid Build Coastguard Worker // extra memory. And unlike runtime intern tables, we do not want this to depend on runtime
117*795d594fSAndroid Build Coastguard Worker // properties (see `Runtime::GetHashTableMaxLoadFactor()` checking for low memory mode).
118*795d594fSAndroid Build Coastguard Worker constexpr double kImageInternTableMaxLoadFactor = 0.6;
119*795d594fSAndroid Build Coastguard Worker 
120*795d594fSAndroid Build Coastguard Worker // Separate objects into multiple bins to optimize dirty memory use.
121*795d594fSAndroid Build Coastguard Worker static constexpr bool kBinObjects = true;
122*795d594fSAndroid Build Coastguard Worker 
123*795d594fSAndroid Build Coastguard Worker namespace {
124*795d594fSAndroid Build Coastguard Worker 
125*795d594fSAndroid Build Coastguard Worker // Dirty object data from dirty-image-objects.
126*795d594fSAndroid Build Coastguard Worker struct DirtyEntry {
127*795d594fSAndroid Build Coastguard Worker   // Reference field name and type.
128*795d594fSAndroid Build Coastguard Worker   struct RefInfo {
129*795d594fSAndroid Build Coastguard Worker     std::string_view name;
130*795d594fSAndroid Build Coastguard Worker     std::string_view type;
131*795d594fSAndroid Build Coastguard Worker   };
132*795d594fSAndroid Build Coastguard Worker 
133*795d594fSAndroid Build Coastguard Worker   std::string_view class_descriptor;
134*795d594fSAndroid Build Coastguard Worker   // A "path" from class object to the dirty object. If empty -- the class itself is dirty.
135*795d594fSAndroid Build Coastguard Worker   std::vector<RefInfo> reference_path;
136*795d594fSAndroid Build Coastguard Worker   uint32_t sort_key = std::numeric_limits<uint32_t>::max();
137*795d594fSAndroid Build Coastguard Worker };
138*795d594fSAndroid Build Coastguard Worker 
139*795d594fSAndroid Build Coastguard Worker // Parse dirty-image-object line of the format:
140*795d594fSAndroid Build Coastguard Worker // <class_descriptor>[.<reference_field_name>:<reference_field_type>]* [<sort_key>]
ParseDirtyEntry(std::string_view entry_str)141*795d594fSAndroid Build Coastguard Worker std::optional<DirtyEntry> ParseDirtyEntry(std::string_view entry_str) {
142*795d594fSAndroid Build Coastguard Worker   DirtyEntry entry;
143*795d594fSAndroid Build Coastguard Worker   std::vector<std::string_view> tokens;
144*795d594fSAndroid Build Coastguard Worker   Split(entry_str, ' ', &tokens);
145*795d594fSAndroid Build Coastguard Worker   if (tokens.empty()) {
146*795d594fSAndroid Build Coastguard Worker     // entry_str is empty.
147*795d594fSAndroid Build Coastguard Worker     return std::nullopt;
148*795d594fSAndroid Build Coastguard Worker   }
149*795d594fSAndroid Build Coastguard Worker 
150*795d594fSAndroid Build Coastguard Worker   std::string_view path_to_root = tokens[0];
151*795d594fSAndroid Build Coastguard Worker   // Parse sort_key if present, otherwise it will be uint32::max by default.
152*795d594fSAndroid Build Coastguard Worker   if (tokens.size() > 1) {
153*795d594fSAndroid Build Coastguard Worker     std::from_chars_result res =
154*795d594fSAndroid Build Coastguard Worker         std::from_chars(tokens[1].data(), tokens[1].data() + tokens[1].size(), entry.sort_key);
155*795d594fSAndroid Build Coastguard Worker     if (res.ec != std::errc()) {
156*795d594fSAndroid Build Coastguard Worker       LOG(WARNING) << "Failed to parse dirty object sort key: \"" << entry_str << "\"";
157*795d594fSAndroid Build Coastguard Worker       return std::nullopt;
158*795d594fSAndroid Build Coastguard Worker     }
159*795d594fSAndroid Build Coastguard Worker   }
160*795d594fSAndroid Build Coastguard Worker 
161*795d594fSAndroid Build Coastguard Worker   std::vector<std::string_view> path_components;
162*795d594fSAndroid Build Coastguard Worker   Split(path_to_root, '.', &path_components);
163*795d594fSAndroid Build Coastguard Worker   if (path_components.empty()) {
164*795d594fSAndroid Build Coastguard Worker     return std::nullopt;
165*795d594fSAndroid Build Coastguard Worker   }
166*795d594fSAndroid Build Coastguard Worker   entry.class_descriptor = path_components[0];
167*795d594fSAndroid Build Coastguard Worker   for (size_t i = 1; i < path_components.size(); ++i) {
168*795d594fSAndroid Build Coastguard Worker     std::string_view name_and_type = path_components[i];
169*795d594fSAndroid Build Coastguard Worker     std::vector<std::string_view> ref_data;
170*795d594fSAndroid Build Coastguard Worker     Split(name_and_type, ':', &ref_data);
171*795d594fSAndroid Build Coastguard Worker     if (ref_data.size() != 2) {
172*795d594fSAndroid Build Coastguard Worker       LOG(WARNING) << "Failed to parse dirty object reference field: \"" << entry_str << "\"";
173*795d594fSAndroid Build Coastguard Worker       return std::nullopt;
174*795d594fSAndroid Build Coastguard Worker     }
175*795d594fSAndroid Build Coastguard Worker 
176*795d594fSAndroid Build Coastguard Worker     std::string_view field_name = ref_data[0];
177*795d594fSAndroid Build Coastguard Worker     std::string_view field_type = ref_data[1];
178*795d594fSAndroid Build Coastguard Worker     entry.reference_path.push_back({field_name, field_type});
179*795d594fSAndroid Build Coastguard Worker   }
180*795d594fSAndroid Build Coastguard Worker 
181*795d594fSAndroid Build Coastguard Worker   return entry;
182*795d594fSAndroid Build Coastguard Worker }
183*795d594fSAndroid Build Coastguard Worker 
184*795d594fSAndroid Build Coastguard Worker // Calls VisitFunc for each non-null (reference)Object/ArtField pair.
185*795d594fSAndroid Build Coastguard Worker // Doesn't work with ObjectArray instances, because array elements don't have ArtField.
186*795d594fSAndroid Build Coastguard Worker class ReferenceFieldVisitor {
187*795d594fSAndroid Build Coastguard Worker  public:
188*795d594fSAndroid Build Coastguard Worker   using VisitFunc = std::function<void(mirror::Object&, ArtField&)>;
189*795d594fSAndroid Build Coastguard Worker 
ReferenceFieldVisitor(VisitFunc visit_func)190*795d594fSAndroid Build Coastguard Worker   explicit ReferenceFieldVisitor(VisitFunc visit_func) : visit_func_(std::move(visit_func)) {}
191*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static) const192*795d594fSAndroid Build Coastguard Worker   void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool is_static) const
193*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
194*795d594fSAndroid Build Coastguard Worker     CHECK(!obj->IsObjectArray());
195*795d594fSAndroid Build Coastguard Worker     mirror::Object* field_obj =
196*795d594fSAndroid Build Coastguard Worker         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
197*795d594fSAndroid Build Coastguard Worker     // Skip fields that contain null.
198*795d594fSAndroid Build Coastguard Worker     if (field_obj == nullptr) {
199*795d594fSAndroid Build Coastguard Worker       return;
200*795d594fSAndroid Build Coastguard Worker     }
201*795d594fSAndroid Build Coastguard Worker     // Skip self references.
202*795d594fSAndroid Build Coastguard Worker     if (field_obj == obj.Ptr()) {
203*795d594fSAndroid Build Coastguard Worker       return;
204*795d594fSAndroid Build Coastguard Worker     }
205*795d594fSAndroid Build Coastguard Worker 
206*795d594fSAndroid Build Coastguard Worker     ArtField* field = nullptr;
207*795d594fSAndroid Build Coastguard Worker     // Don't use Object::FindFieldByOffset, because it can't find instance fields in classes.
208*795d594fSAndroid Build Coastguard Worker     // field = obj->FindFieldByOffset(offset);
209*795d594fSAndroid Build Coastguard Worker     if (is_static) {
210*795d594fSAndroid Build Coastguard Worker       CHECK(obj->IsClass());
211*795d594fSAndroid Build Coastguard Worker       field = ArtField::FindStaticFieldWithOffset(obj->AsClass(), offset.Uint32Value());
212*795d594fSAndroid Build Coastguard Worker     } else {
213*795d594fSAndroid Build Coastguard Worker       field = ArtField::
214*795d594fSAndroid Build Coastguard Worker           FindInstanceFieldWithOffset</*kExactOffset*/ true, kVerifyNone, kWithoutReadBarrier>(
215*795d594fSAndroid Build Coastguard Worker               obj->GetClass<kVerifyNone, kWithoutReadBarrier>(), offset.Uint32Value());
216*795d594fSAndroid Build Coastguard Worker     }
217*795d594fSAndroid Build Coastguard Worker     DCHECK(field != nullptr);
218*795d594fSAndroid Build Coastguard Worker     visit_func_(*field_obj, *field);
219*795d594fSAndroid Build Coastguard Worker   }
220*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const221*795d594fSAndroid Build Coastguard Worker   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
222*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
223*795d594fSAndroid Build Coastguard Worker     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
224*795d594fSAndroid Build Coastguard Worker   }
225*795d594fSAndroid Build Coastguard Worker 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const226*795d594fSAndroid Build Coastguard Worker   void VisitRootIfNonNull([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const
227*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
228*795d594fSAndroid Build Coastguard Worker     DCHECK(false) << "ReferenceFieldVisitor shouldn't visit roots";
229*795d594fSAndroid Build Coastguard Worker   }
230*795d594fSAndroid Build Coastguard Worker 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const231*795d594fSAndroid Build Coastguard Worker   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const
232*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
233*795d594fSAndroid Build Coastguard Worker     DCHECK(false) << "ReferenceFieldVisitor shouldn't visit roots";
234*795d594fSAndroid Build Coastguard Worker   }
235*795d594fSAndroid Build Coastguard Worker 
236*795d594fSAndroid Build Coastguard Worker  private:
237*795d594fSAndroid Build Coastguard Worker   VisitFunc visit_func_;
238*795d594fSAndroid Build Coastguard Worker };
239*795d594fSAndroid Build Coastguard Worker 
240*795d594fSAndroid Build Coastguard Worker // Finds Class objects for descriptors of dirty entries.
241*795d594fSAndroid Build Coastguard Worker // Map keys are string_views, that point to strings from `dirty_image_objects`.
242*795d594fSAndroid Build Coastguard Worker // If there is no Class for a descriptor, the result map will have an entry with nullptr value.
FindClassesByDescriptor(const std::vector<std::string> & dirty_image_objects)243*795d594fSAndroid Build Coastguard Worker static HashMap<std::string_view, mirror::Object*> FindClassesByDescriptor(
244*795d594fSAndroid Build Coastguard Worker     const std::vector<std::string>& dirty_image_objects) REQUIRES_SHARED(Locks::mutator_lock_) {
245*795d594fSAndroid Build Coastguard Worker   HashMap<std::string_view, mirror::Object*> descriptor_to_class;
246*795d594fSAndroid Build Coastguard Worker   // Collect class descriptors that are used in dirty-image-objects.
247*795d594fSAndroid Build Coastguard Worker   for (const std::string& entry : dirty_image_objects) {
248*795d594fSAndroid Build Coastguard Worker     auto it = std::find_if(entry.begin(), entry.end(), [](char c) { return c == '.' || c == ' '; });
249*795d594fSAndroid Build Coastguard Worker     size_t descriptor_len = std::distance(entry.begin(), it);
250*795d594fSAndroid Build Coastguard Worker 
251*795d594fSAndroid Build Coastguard Worker     std::string_view descriptor = std::string_view(entry).substr(0, descriptor_len);
252*795d594fSAndroid Build Coastguard Worker     descriptor_to_class.insert(std::make_pair(descriptor, nullptr));
253*795d594fSAndroid Build Coastguard Worker   }
254*795d594fSAndroid Build Coastguard Worker 
255*795d594fSAndroid Build Coastguard Worker   // Find Class objects for collected descriptors.
256*795d594fSAndroid Build Coastguard Worker   auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
257*795d594fSAndroid Build Coastguard Worker     DCHECK(obj != nullptr);
258*795d594fSAndroid Build Coastguard Worker     if (obj->IsClass()) {
259*795d594fSAndroid Build Coastguard Worker       std::string temp;
260*795d594fSAndroid Build Coastguard Worker       const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
261*795d594fSAndroid Build Coastguard Worker       auto it = descriptor_to_class.find(descriptor);
262*795d594fSAndroid Build Coastguard Worker       if (it != descriptor_to_class.end()) {
263*795d594fSAndroid Build Coastguard Worker         it->second = obj;
264*795d594fSAndroid Build Coastguard Worker       }
265*795d594fSAndroid Build Coastguard Worker     }
266*795d594fSAndroid Build Coastguard Worker   };
267*795d594fSAndroid Build Coastguard Worker   Runtime::Current()->GetHeap()->VisitObjects(visitor);
268*795d594fSAndroid Build Coastguard Worker 
269*795d594fSAndroid Build Coastguard Worker   return descriptor_to_class;
270*795d594fSAndroid Build Coastguard Worker }
271*795d594fSAndroid Build Coastguard Worker 
272*795d594fSAndroid Build Coastguard Worker // Get all objects that match dirty_entries by path from class.
273*795d594fSAndroid Build Coastguard Worker // Map values are sort_keys from DirtyEntry.
MatchDirtyObjectPaths(const std::vector<std::string> & dirty_image_objects)274*795d594fSAndroid Build Coastguard Worker HashMap<mirror::Object*, uint32_t> MatchDirtyObjectPaths(
275*795d594fSAndroid Build Coastguard Worker     const std::vector<std::string>& dirty_image_objects) REQUIRES_SHARED(Locks::mutator_lock_) {
276*795d594fSAndroid Build Coastguard Worker   auto get_array_element = [](mirror::Object* cur_obj, const DirtyEntry::RefInfo& ref_info)
277*795d594fSAndroid Build Coastguard Worker                                REQUIRES_SHARED(Locks::mutator_lock_) -> mirror::Object* {
278*795d594fSAndroid Build Coastguard Worker     if (!cur_obj->IsObjectArray()) {
279*795d594fSAndroid Build Coastguard Worker       return nullptr;
280*795d594fSAndroid Build Coastguard Worker     }
281*795d594fSAndroid Build Coastguard Worker     int32_t idx = 0;
282*795d594fSAndroid Build Coastguard Worker     std::from_chars_result idx_parse_res =
283*795d594fSAndroid Build Coastguard Worker         std::from_chars(ref_info.name.data(), ref_info.name.data() + ref_info.name.size(), idx);
284*795d594fSAndroid Build Coastguard Worker     if (idx_parse_res.ec != std::errc()) {
285*795d594fSAndroid Build Coastguard Worker       return nullptr;
286*795d594fSAndroid Build Coastguard Worker     }
287*795d594fSAndroid Build Coastguard Worker 
288*795d594fSAndroid Build Coastguard Worker     ObjPtr<ObjectArray<mirror::Object>> array = cur_obj->AsObjectArray<mirror::Object>();
289*795d594fSAndroid Build Coastguard Worker     if (idx < 0 || idx >= array->GetLength()) {
290*795d594fSAndroid Build Coastguard Worker       return nullptr;
291*795d594fSAndroid Build Coastguard Worker     }
292*795d594fSAndroid Build Coastguard Worker 
293*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Object> next_obj =
294*795d594fSAndroid Build Coastguard Worker         array->GetWithoutChecks<kVerifyNone, kWithoutReadBarrier>(idx);
295*795d594fSAndroid Build Coastguard Worker     if (next_obj == nullptr) {
296*795d594fSAndroid Build Coastguard Worker       return nullptr;
297*795d594fSAndroid Build Coastguard Worker     }
298*795d594fSAndroid Build Coastguard Worker 
299*795d594fSAndroid Build Coastguard Worker     std::string temp;
300*795d594fSAndroid Build Coastguard Worker     if (next_obj->GetClass<kVerifyNone, kWithoutReadBarrier>()->GetDescriptor(&temp) !=
301*795d594fSAndroid Build Coastguard Worker         ref_info.type) {
302*795d594fSAndroid Build Coastguard Worker       return nullptr;
303*795d594fSAndroid Build Coastguard Worker     }
304*795d594fSAndroid Build Coastguard Worker     return next_obj.Ptr();
305*795d594fSAndroid Build Coastguard Worker   };
306*795d594fSAndroid Build Coastguard Worker   auto get_object_field =
307*795d594fSAndroid Build Coastguard Worker       [](mirror::Object* cur_obj, const DirtyEntry::RefInfo& ref_info)
308*795d594fSAndroid Build Coastguard Worker           REQUIRES_SHARED(Locks::mutator_lock_) {
309*795d594fSAndroid Build Coastguard Worker             mirror::Object* next_obj = nullptr;
310*795d594fSAndroid Build Coastguard Worker             ReferenceFieldVisitor::VisitFunc visit_func =
311*795d594fSAndroid Build Coastguard Worker                 [&](mirror::Object& ref_obj, ArtField& ref_field)
312*795d594fSAndroid Build Coastguard Worker                     REQUIRES_SHARED(Locks::mutator_lock_) {
313*795d594fSAndroid Build Coastguard Worker                       if (ref_field.GetName() == ref_info.name &&
314*795d594fSAndroid Build Coastguard Worker                           ref_field.GetTypeDescriptor() == ref_info.type) {
315*795d594fSAndroid Build Coastguard Worker                         next_obj = &ref_obj;
316*795d594fSAndroid Build Coastguard Worker                       }
317*795d594fSAndroid Build Coastguard Worker                     };
318*795d594fSAndroid Build Coastguard Worker             ReferenceFieldVisitor visitor(visit_func);
319*795d594fSAndroid Build Coastguard Worker             cur_obj->VisitReferences</*kVisitNativeRoots=*/false, kVerifyNone, kWithoutReadBarrier>(
320*795d594fSAndroid Build Coastguard Worker                 visitor, visitor);
321*795d594fSAndroid Build Coastguard Worker 
322*795d594fSAndroid Build Coastguard Worker             return next_obj;
323*795d594fSAndroid Build Coastguard Worker           };
324*795d594fSAndroid Build Coastguard Worker 
325*795d594fSAndroid Build Coastguard Worker   HashMap<mirror::Object*, uint32_t> dirty_objects;
326*795d594fSAndroid Build Coastguard Worker   const HashMap<std::string_view, mirror::Object*> descriptor_to_class =
327*795d594fSAndroid Build Coastguard Worker       FindClassesByDescriptor(dirty_image_objects);
328*795d594fSAndroid Build Coastguard Worker   for (const std::string& entry_str : dirty_image_objects) {
329*795d594fSAndroid Build Coastguard Worker     const std::optional<DirtyEntry> entry = ParseDirtyEntry(entry_str);
330*795d594fSAndroid Build Coastguard Worker     if (entry == std::nullopt) {
331*795d594fSAndroid Build Coastguard Worker       continue;
332*795d594fSAndroid Build Coastguard Worker     }
333*795d594fSAndroid Build Coastguard Worker 
334*795d594fSAndroid Build Coastguard Worker     auto root_it = descriptor_to_class.find(entry->class_descriptor);
335*795d594fSAndroid Build Coastguard Worker     if (root_it == descriptor_to_class.end() || root_it->second == nullptr) {
336*795d594fSAndroid Build Coastguard Worker       LOG(WARNING) << "Class not found: \"" << entry->class_descriptor << "\"";
337*795d594fSAndroid Build Coastguard Worker       continue;
338*795d594fSAndroid Build Coastguard Worker     }
339*795d594fSAndroid Build Coastguard Worker 
340*795d594fSAndroid Build Coastguard Worker     mirror::Object* cur_obj = root_it->second;
341*795d594fSAndroid Build Coastguard Worker     for (const DirtyEntry::RefInfo& ref_info : entry->reference_path) {
342*795d594fSAndroid Build Coastguard Worker       if (std::all_of(
343*795d594fSAndroid Build Coastguard Worker               ref_info.name.begin(), ref_info.name.end(), [](char c) { return std::isdigit(c); })) {
344*795d594fSAndroid Build Coastguard Worker         cur_obj = get_array_element(cur_obj, ref_info);
345*795d594fSAndroid Build Coastguard Worker       } else {
346*795d594fSAndroid Build Coastguard Worker         cur_obj = get_object_field(cur_obj, ref_info);
347*795d594fSAndroid Build Coastguard Worker       }
348*795d594fSAndroid Build Coastguard Worker       if (cur_obj == nullptr) {
349*795d594fSAndroid Build Coastguard Worker         LOG(WARNING) << ART_FORMAT("Failed to find field \"{}:{}\", entry: \"{}\"",
350*795d594fSAndroid Build Coastguard Worker                                    ref_info.name,
351*795d594fSAndroid Build Coastguard Worker                                    ref_info.type,
352*795d594fSAndroid Build Coastguard Worker                                    entry_str);
353*795d594fSAndroid Build Coastguard Worker         break;
354*795d594fSAndroid Build Coastguard Worker       }
355*795d594fSAndroid Build Coastguard Worker     }
356*795d594fSAndroid Build Coastguard Worker     if (cur_obj == nullptr) {
357*795d594fSAndroid Build Coastguard Worker       continue;
358*795d594fSAndroid Build Coastguard Worker     }
359*795d594fSAndroid Build Coastguard Worker 
360*795d594fSAndroid Build Coastguard Worker     dirty_objects.insert(std::make_pair(cur_obj, entry->sort_key));
361*795d594fSAndroid Build Coastguard Worker   }
362*795d594fSAndroid Build Coastguard Worker 
363*795d594fSAndroid Build Coastguard Worker   return dirty_objects;
364*795d594fSAndroid Build Coastguard Worker }
365*795d594fSAndroid Build Coastguard Worker 
366*795d594fSAndroid Build Coastguard Worker }  // namespace
367*795d594fSAndroid Build Coastguard Worker 
AllocateBootImageLiveObjects(Thread * self,Runtime * runtime)368*795d594fSAndroid Build Coastguard Worker static ObjPtr<mirror::ObjectArray<mirror::Object>> AllocateBootImageLiveObjects(
369*795d594fSAndroid Build Coastguard Worker     Thread* self, Runtime* runtime) REQUIRES_SHARED(Locks::mutator_lock_) {
370*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = runtime->GetClassLinker();
371*795d594fSAndroid Build Coastguard Worker   // The objects used for intrinsics must remain live even if references
372*795d594fSAndroid Build Coastguard Worker   // to them are removed using reflection. Image roots are not accessible through reflection,
373*795d594fSAndroid Build Coastguard Worker   // so the array we construct here shall keep them alive.
374*795d594fSAndroid Build Coastguard Worker   StackHandleScope<1> hs(self);
375*795d594fSAndroid Build Coastguard Worker   size_t live_objects_size =
376*795d594fSAndroid Build Coastguard Worker       enum_cast<size_t>(ImageHeader::kIntrinsicObjectsStart) +
377*795d594fSAndroid Build Coastguard Worker       IntrinsicObjects::GetNumberOfIntrinsicObjects();
378*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::ObjectArray<mirror::Object>> live_objects =
379*795d594fSAndroid Build Coastguard Worker       mirror::ObjectArray<mirror::Object>::Alloc(
380*795d594fSAndroid Build Coastguard Worker           self, GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker), live_objects_size);
381*795d594fSAndroid Build Coastguard Worker   if (live_objects == nullptr) {
382*795d594fSAndroid Build Coastguard Worker     return nullptr;
383*795d594fSAndroid Build Coastguard Worker   }
384*795d594fSAndroid Build Coastguard Worker   int32_t index = 0u;
385*795d594fSAndroid Build Coastguard Worker   auto set_entry = [&](ImageHeader::BootImageLiveObjects entry,
386*795d594fSAndroid Build Coastguard Worker                        ObjPtr<mirror::Object> value) REQUIRES_SHARED(Locks::mutator_lock_) {
387*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(index, enum_cast<int32_t>(entry));
388*795d594fSAndroid Build Coastguard Worker     live_objects->Set</*kTransacrionActive=*/ false>(index, value);
389*795d594fSAndroid Build Coastguard Worker     ++index;
390*795d594fSAndroid Build Coastguard Worker   };
391*795d594fSAndroid Build Coastguard Worker   set_entry(ImageHeader::kOomeWhenThrowingException,
392*795d594fSAndroid Build Coastguard Worker             runtime->GetPreAllocatedOutOfMemoryErrorWhenThrowingException());
393*795d594fSAndroid Build Coastguard Worker   set_entry(ImageHeader::kOomeWhenThrowingOome,
394*795d594fSAndroid Build Coastguard Worker             runtime->GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME());
395*795d594fSAndroid Build Coastguard Worker   set_entry(ImageHeader::kOomeWhenHandlingStackOverflow,
396*795d594fSAndroid Build Coastguard Worker             runtime->GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow());
397*795d594fSAndroid Build Coastguard Worker   set_entry(ImageHeader::kNoClassDefFoundError, runtime->GetPreAllocatedNoClassDefFoundError());
398*795d594fSAndroid Build Coastguard Worker   set_entry(ImageHeader::kClearedJniWeakSentinel, runtime->GetSentinel().Read());
399*795d594fSAndroid Build Coastguard Worker 
400*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(index, enum_cast<int32_t>(ImageHeader::kIntrinsicObjectsStart));
401*795d594fSAndroid Build Coastguard Worker   IntrinsicObjects::FillIntrinsicObjects(live_objects, index);
402*795d594fSAndroid Build Coastguard Worker   return live_objects;
403*795d594fSAndroid Build Coastguard Worker }
404*795d594fSAndroid Build Coastguard Worker 
405*795d594fSAndroid Build Coastguard Worker template <typename MirrorType>
DecodeGlobalWithoutRB(JavaVMExt * vm,jobject obj)406*795d594fSAndroid Build Coastguard Worker ObjPtr<MirrorType> ImageWriter::DecodeGlobalWithoutRB(JavaVMExt* vm, jobject obj) {
407*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(obj), kGlobal);
408*795d594fSAndroid Build Coastguard Worker   return ObjPtr<MirrorType>::DownCast(vm->globals_.Get<kWithoutReadBarrier>(obj));
409*795d594fSAndroid Build Coastguard Worker }
410*795d594fSAndroid Build Coastguard Worker 
411*795d594fSAndroid Build Coastguard Worker template <typename MirrorType>
DecodeWeakGlobalWithoutRB(JavaVMExt * vm,Thread * self,jobject obj)412*795d594fSAndroid Build Coastguard Worker ObjPtr<MirrorType> ImageWriter::DecodeWeakGlobalWithoutRB(
413*795d594fSAndroid Build Coastguard Worker     JavaVMExt* vm, Thread* self, jobject obj) {
414*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(obj), kWeakGlobal);
415*795d594fSAndroid Build Coastguard Worker   DCHECK(vm->MayAccessWeakGlobals(self));
416*795d594fSAndroid Build Coastguard Worker   return ObjPtr<MirrorType>::DownCast(vm->weak_globals_.Get<kWithoutReadBarrier>(obj));
417*795d594fSAndroid Build Coastguard Worker }
418*795d594fSAndroid Build Coastguard Worker 
GetAppClassLoader() const419*795d594fSAndroid Build Coastguard Worker ObjPtr<mirror::ClassLoader> ImageWriter::GetAppClassLoader() const
420*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
421*795d594fSAndroid Build Coastguard Worker   return compiler_options_.IsAppImage()
422*795d594fSAndroid Build Coastguard Worker       ? ObjPtr<mirror::ClassLoader>::DownCast(Thread::Current()->DecodeJObject(app_class_loader_))
423*795d594fSAndroid Build Coastguard Worker       : nullptr;
424*795d594fSAndroid Build Coastguard Worker }
425*795d594fSAndroid Build Coastguard Worker 
IsImageDexCache(ObjPtr<mirror::DexCache> dex_cache) const426*795d594fSAndroid Build Coastguard Worker bool ImageWriter::IsImageDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
427*795d594fSAndroid Build Coastguard Worker   // For boot image, we keep all dex caches.
428*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsBootImage()) {
429*795d594fSAndroid Build Coastguard Worker     return true;
430*795d594fSAndroid Build Coastguard Worker   }
431*795d594fSAndroid Build Coastguard Worker   // Dex caches already in the boot image do not belong to the image being written.
432*795d594fSAndroid Build Coastguard Worker   if (IsInBootImage(dex_cache.Ptr())) {
433*795d594fSAndroid Build Coastguard Worker     return false;
434*795d594fSAndroid Build Coastguard Worker   }
435*795d594fSAndroid Build Coastguard Worker   // Dex caches for the boot class path components that are not part of the boot image
436*795d594fSAndroid Build Coastguard Worker   // cannot be garbage collected in PrepareImageAddressSpace() but we do not want to
437*795d594fSAndroid Build Coastguard Worker   // include them in the app image.
438*795d594fSAndroid Build Coastguard Worker   if (!ContainsElement(compiler_options_.GetDexFilesForOatFile(), dex_cache->GetDexFile())) {
439*795d594fSAndroid Build Coastguard Worker     return false;
440*795d594fSAndroid Build Coastguard Worker   }
441*795d594fSAndroid Build Coastguard Worker   return true;
442*795d594fSAndroid Build Coastguard Worker }
443*795d594fSAndroid Build Coastguard Worker 
ClearDexFileCookies()444*795d594fSAndroid Build Coastguard Worker static void ClearDexFileCookies() REQUIRES_SHARED(Locks::mutator_lock_) {
445*795d594fSAndroid Build Coastguard Worker   auto visitor = [](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
446*795d594fSAndroid Build Coastguard Worker     DCHECK(obj != nullptr);
447*795d594fSAndroid Build Coastguard Worker     Class* klass = obj->GetClass();
448*795d594fSAndroid Build Coastguard Worker     if (klass == WellKnownClasses::dalvik_system_DexFile) {
449*795d594fSAndroid Build Coastguard Worker       ArtField* field = WellKnownClasses::dalvik_system_DexFile_cookie;
450*795d594fSAndroid Build Coastguard Worker       // Null out the cookie to enable determinism. b/34090128
451*795d594fSAndroid Build Coastguard Worker       field->SetObject</*kTransactionActive*/false>(obj, nullptr);
452*795d594fSAndroid Build Coastguard Worker     }
453*795d594fSAndroid Build Coastguard Worker   };
454*795d594fSAndroid Build Coastguard Worker   Runtime::Current()->GetHeap()->VisitObjects(visitor);
455*795d594fSAndroid Build Coastguard Worker }
456*795d594fSAndroid Build Coastguard Worker 
PrepareImageAddressSpace(TimingLogger * timings)457*795d594fSAndroid Build Coastguard Worker bool ImageWriter::PrepareImageAddressSpace(TimingLogger* timings) {
458*795d594fSAndroid Build Coastguard Worker   Thread* const self = Thread::Current();
459*795d594fSAndroid Build Coastguard Worker 
460*795d594fSAndroid Build Coastguard Worker   gc::Heap* const heap = Runtime::Current()->GetHeap();
461*795d594fSAndroid Build Coastguard Worker   {
462*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(self);
463*795d594fSAndroid Build Coastguard Worker     {
464*795d594fSAndroid Build Coastguard Worker       TimingLogger::ScopedTiming t("PruneNonImageClasses", timings);
465*795d594fSAndroid Build Coastguard Worker       PruneNonImageClasses();  // Remove junk
466*795d594fSAndroid Build Coastguard Worker     }
467*795d594fSAndroid Build Coastguard Worker 
468*795d594fSAndroid Build Coastguard Worker     if (UNLIKELY(!CreateImageRoots())) {
469*795d594fSAndroid Build Coastguard Worker       self->AssertPendingOOMException();
470*795d594fSAndroid Build Coastguard Worker       self->ClearException();
471*795d594fSAndroid Build Coastguard Worker       return false;
472*795d594fSAndroid Build Coastguard Worker     }
473*795d594fSAndroid Build Coastguard Worker 
474*795d594fSAndroid Build Coastguard Worker     if (compiler_options_.IsAppImage()) {
475*795d594fSAndroid Build Coastguard Worker       TimingLogger::ScopedTiming t("ClearDexFileCookies", timings);
476*795d594fSAndroid Build Coastguard Worker       // Clear dex file cookies for app images to enable app image determinism. This is required
477*795d594fSAndroid Build Coastguard Worker       // since the cookie field contains long pointers to DexFiles which are not deterministic.
478*795d594fSAndroid Build Coastguard Worker       // b/34090128
479*795d594fSAndroid Build Coastguard Worker       ClearDexFileCookies();
480*795d594fSAndroid Build Coastguard Worker     }
481*795d594fSAndroid Build Coastguard Worker   }
482*795d594fSAndroid Build Coastguard Worker 
483*795d594fSAndroid Build Coastguard Worker   {
484*795d594fSAndroid Build Coastguard Worker     TimingLogger::ScopedTiming t("CollectGarbage", timings);
485*795d594fSAndroid Build Coastguard Worker     heap->CollectGarbage(/* clear_soft_references */ false);  // Remove garbage.
486*795d594fSAndroid Build Coastguard Worker   }
487*795d594fSAndroid Build Coastguard Worker 
488*795d594fSAndroid Build Coastguard Worker   if (kIsDebugBuild) {
489*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(self);
490*795d594fSAndroid Build Coastguard Worker     CheckNonImageClassesRemoved();
491*795d594fSAndroid Build Coastguard Worker   }
492*795d594fSAndroid Build Coastguard Worker 
493*795d594fSAndroid Build Coastguard Worker   // From this point on, there should be no GC, so we should not use unnecessary read barriers.
494*795d594fSAndroid Build Coastguard Worker   ScopedDebugDisallowReadBarriers sddrb(self);
495*795d594fSAndroid Build Coastguard Worker 
496*795d594fSAndroid Build Coastguard Worker   {
497*795d594fSAndroid Build Coastguard Worker     // All remaining weak interns are referenced. Promote them to strong interns. Whether a
498*795d594fSAndroid Build Coastguard Worker     // string was strongly or weakly interned, we shall make it strongly interned in the image.
499*795d594fSAndroid Build Coastguard Worker     TimingLogger::ScopedTiming t("PromoteInterns", timings);
500*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(self);
501*795d594fSAndroid Build Coastguard Worker     PromoteWeakInternsToStrong(self);
502*795d594fSAndroid Build Coastguard Worker   }
503*795d594fSAndroid Build Coastguard Worker 
504*795d594fSAndroid Build Coastguard Worker   {
505*795d594fSAndroid Build Coastguard Worker     TimingLogger::ScopedTiming t("CalculateNewObjectOffsets", timings);
506*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(self);
507*795d594fSAndroid Build Coastguard Worker     CalculateNewObjectOffsets();
508*795d594fSAndroid Build Coastguard Worker   }
509*795d594fSAndroid Build Coastguard Worker 
510*795d594fSAndroid Build Coastguard Worker   // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
511*795d594fSAndroid Build Coastguard Worker   // bin size sums being calculated.
512*795d594fSAndroid Build Coastguard Worker   TimingLogger::ScopedTiming t("AllocMemory", timings);
513*795d594fSAndroid Build Coastguard Worker   return AllocMemory();
514*795d594fSAndroid Build Coastguard Worker }
515*795d594fSAndroid Build Coastguard Worker 
CopyMetadata()516*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyMetadata() {
517*795d594fSAndroid Build Coastguard Worker   DCHECK(compiler_options_.IsAppImage());
518*795d594fSAndroid Build Coastguard Worker   CHECK_EQ(image_infos_.size(), 1u);
519*795d594fSAndroid Build Coastguard Worker 
520*795d594fSAndroid Build Coastguard Worker   const ImageInfo& image_info = image_infos_.back();
521*795d594fSAndroid Build Coastguard Worker   dchecked_vector<ImageSection> image_sections = image_info.CreateImageSections().second;
522*795d594fSAndroid Build Coastguard Worker 
523*795d594fSAndroid Build Coastguard Worker   auto* sfo_section_base = reinterpret_cast<AppImageReferenceOffsetInfo*>(
524*795d594fSAndroid Build Coastguard Worker       image_info.image_.Begin() +
525*795d594fSAndroid Build Coastguard Worker       image_sections[ImageHeader::kSectionStringReferenceOffsets].Offset());
526*795d594fSAndroid Build Coastguard Worker 
527*795d594fSAndroid Build Coastguard Worker   std::copy(image_info.string_reference_offsets_.begin(),
528*795d594fSAndroid Build Coastguard Worker             image_info.string_reference_offsets_.end(),
529*795d594fSAndroid Build Coastguard Worker             sfo_section_base);
530*795d594fSAndroid Build Coastguard Worker }
531*795d594fSAndroid Build Coastguard Worker 
532*795d594fSAndroid Build Coastguard Worker // NO_THREAD_SAFETY_ANALYSIS: Avoid locking the `Locks::intern_table_lock_` while single-threaded.
IsStronglyInternedString(ObjPtr<mirror::String> str)533*795d594fSAndroid Build Coastguard Worker bool ImageWriter::IsStronglyInternedString(ObjPtr<mirror::String> str) NO_THREAD_SAFETY_ANALYSIS {
534*795d594fSAndroid Build Coastguard Worker   uint32_t hash = static_cast<uint32_t>(str->GetStoredHashCode());
535*795d594fSAndroid Build Coastguard Worker   if (hash == 0u && str->ComputeHashCode() != 0) {
536*795d594fSAndroid Build Coastguard Worker     // A string with uninitialized hash code cannot be interned.
537*795d594fSAndroid Build Coastguard Worker     return false;
538*795d594fSAndroid Build Coastguard Worker   }
539*795d594fSAndroid Build Coastguard Worker   InternTable* intern_table = Runtime::Current()->GetInternTable();
540*795d594fSAndroid Build Coastguard Worker   for (InternTable::Table::InternalTable& table : intern_table->strong_interns_.tables_) {
541*795d594fSAndroid Build Coastguard Worker     auto it = table.set_.FindWithHash(GcRoot<mirror::String>(str), hash);
542*795d594fSAndroid Build Coastguard Worker     if (it != table.set_.end()) {
543*795d594fSAndroid Build Coastguard Worker       return it->Read<kWithoutReadBarrier>() == str;
544*795d594fSAndroid Build Coastguard Worker     }
545*795d594fSAndroid Build Coastguard Worker   }
546*795d594fSAndroid Build Coastguard Worker   return false;
547*795d594fSAndroid Build Coastguard Worker }
548*795d594fSAndroid Build Coastguard Worker 
IsInternedAppImageStringReference(ObjPtr<mirror::Object> referred_obj) const549*795d594fSAndroid Build Coastguard Worker bool ImageWriter::IsInternedAppImageStringReference(ObjPtr<mirror::Object> referred_obj) const {
550*795d594fSAndroid Build Coastguard Worker   return referred_obj != nullptr &&
551*795d594fSAndroid Build Coastguard Worker          !IsInBootImage(referred_obj.Ptr()) &&
552*795d594fSAndroid Build Coastguard Worker          referred_obj->IsString() &&
553*795d594fSAndroid Build Coastguard Worker          IsStronglyInternedString(referred_obj->AsString());
554*795d594fSAndroid Build Coastguard Worker }
555*795d594fSAndroid Build Coastguard Worker 
Write(int image_fd,const std::vector<std::string> & image_filenames,size_t component_count)556*795d594fSAndroid Build Coastguard Worker bool ImageWriter::Write(int image_fd,
557*795d594fSAndroid Build Coastguard Worker                         const std::vector<std::string>& image_filenames,
558*795d594fSAndroid Build Coastguard Worker                         size_t component_count) {
559*795d594fSAndroid Build Coastguard Worker   // If image_fd or oat_fd are not File::kInvalidFd then we may have empty strings in
560*795d594fSAndroid Build Coastguard Worker   // image_filenames or oat_filenames.
561*795d594fSAndroid Build Coastguard Worker   CHECK(!image_filenames.empty());
562*795d594fSAndroid Build Coastguard Worker   if (image_fd != File::kInvalidFd) {
563*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(image_filenames.size(), 1u);
564*795d594fSAndroid Build Coastguard Worker   }
565*795d594fSAndroid Build Coastguard Worker   DCHECK(!oat_filenames_.empty());
566*795d594fSAndroid Build Coastguard Worker   CHECK_EQ(image_filenames.size(), oat_filenames_.size());
567*795d594fSAndroid Build Coastguard Worker 
568*795d594fSAndroid Build Coastguard Worker   Thread* const self = Thread::Current();
569*795d594fSAndroid Build Coastguard Worker   ScopedDebugDisallowReadBarriers sddrb(self);
570*795d594fSAndroid Build Coastguard Worker   {
571*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(self);
572*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i < oat_filenames_.size(); ++i) {
573*795d594fSAndroid Build Coastguard Worker       CreateHeader(i, component_count);
574*795d594fSAndroid Build Coastguard Worker       CopyAndFixupNativeData(i);
575*795d594fSAndroid Build Coastguard Worker       CopyAndFixupJniStubMethods(i);
576*795d594fSAndroid Build Coastguard Worker     }
577*795d594fSAndroid Build Coastguard Worker   }
578*795d594fSAndroid Build Coastguard Worker 
579*795d594fSAndroid Build Coastguard Worker   {
580*795d594fSAndroid Build Coastguard Worker     // TODO: heap validation can't handle these fix up passes.
581*795d594fSAndroid Build Coastguard Worker     ScopedObjectAccess soa(self);
582*795d594fSAndroid Build Coastguard Worker     Runtime::Current()->GetHeap()->DisableObjectValidation();
583*795d594fSAndroid Build Coastguard Worker     CopyAndFixupObjects();
584*795d594fSAndroid Build Coastguard Worker   }
585*795d594fSAndroid Build Coastguard Worker 
586*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsAppImage()) {
587*795d594fSAndroid Build Coastguard Worker     CopyMetadata();
588*795d594fSAndroid Build Coastguard Worker   }
589*795d594fSAndroid Build Coastguard Worker 
590*795d594fSAndroid Build Coastguard Worker   // Primary image header shall be written last for two reasons. First, this ensures
591*795d594fSAndroid Build Coastguard Worker   // that we shall not end up with a valid primary image and invalid secondary image.
592*795d594fSAndroid Build Coastguard Worker   // Second, its checksum shall include the checksums of the secondary images (XORed).
593*795d594fSAndroid Build Coastguard Worker   // This way only the primary image checksum needs to be checked to determine whether
594*795d594fSAndroid Build Coastguard Worker   // any of the images or oat files are out of date. (Oat file checksums are included
595*795d594fSAndroid Build Coastguard Worker   // in the image checksum calculation.)
596*795d594fSAndroid Build Coastguard Worker   ImageHeader* primary_header = reinterpret_cast<ImageHeader*>(image_infos_[0].image_.Begin());
597*795d594fSAndroid Build Coastguard Worker   ImageFileGuard primary_image_file;
598*795d594fSAndroid Build Coastguard Worker   for (size_t i = 0; i < image_filenames.size(); ++i) {
599*795d594fSAndroid Build Coastguard Worker     const std::string& image_filename = image_filenames[i];
600*795d594fSAndroid Build Coastguard Worker     ImageInfo& image_info = GetImageInfo(i);
601*795d594fSAndroid Build Coastguard Worker     ImageFileGuard image_file;
602*795d594fSAndroid Build Coastguard Worker     if (image_fd != File::kInvalidFd) {
603*795d594fSAndroid Build Coastguard Worker       // Ignore image_filename, it is supplied only for better diagnostic.
604*795d594fSAndroid Build Coastguard Worker       image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
605*795d594fSAndroid Build Coastguard Worker       // Empty the file in case it already exists.
606*795d594fSAndroid Build Coastguard Worker       if (image_file != nullptr) {
607*795d594fSAndroid Build Coastguard Worker         TEMP_FAILURE_RETRY(image_file->SetLength(0));
608*795d594fSAndroid Build Coastguard Worker         TEMP_FAILURE_RETRY(image_file->Flush());
609*795d594fSAndroid Build Coastguard Worker       }
610*795d594fSAndroid Build Coastguard Worker     } else {
611*795d594fSAndroid Build Coastguard Worker       image_file.reset(OS::CreateEmptyFile(image_filename.c_str()));
612*795d594fSAndroid Build Coastguard Worker     }
613*795d594fSAndroid Build Coastguard Worker 
614*795d594fSAndroid Build Coastguard Worker     if (image_file == nullptr) {
615*795d594fSAndroid Build Coastguard Worker       LOG(ERROR) << "Failed to open image file " << image_filename;
616*795d594fSAndroid Build Coastguard Worker       return false;
617*795d594fSAndroid Build Coastguard Worker     }
618*795d594fSAndroid Build Coastguard Worker 
619*795d594fSAndroid Build Coastguard Worker     // Make file world readable if we have created it, i.e. when not passed as file descriptor.
620*795d594fSAndroid Build Coastguard Worker     if (image_fd == -1 && !compiler_options_.IsAppImage() && fchmod(image_file->Fd(), 0644) != 0) {
621*795d594fSAndroid Build Coastguard Worker       PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
622*795d594fSAndroid Build Coastguard Worker       return false;
623*795d594fSAndroid Build Coastguard Worker     }
624*795d594fSAndroid Build Coastguard Worker 
625*795d594fSAndroid Build Coastguard Worker     // Image data size excludes the bitmap and the header.
626*795d594fSAndroid Build Coastguard Worker     ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_.Begin());
627*795d594fSAndroid Build Coastguard Worker     std::string error_msg;
628*795d594fSAndroid Build Coastguard Worker     if (!image_header->WriteData(image_file,
629*795d594fSAndroid Build Coastguard Worker                                  image_info.image_.Begin(),
630*795d594fSAndroid Build Coastguard Worker                                  reinterpret_cast<const uint8_t*>(image_info.image_bitmap_.Begin()),
631*795d594fSAndroid Build Coastguard Worker                                  image_storage_mode_,
632*795d594fSAndroid Build Coastguard Worker                                  compiler_options_.MaxImageBlockSize(),
633*795d594fSAndroid Build Coastguard Worker                                  /* update_checksum= */ true,
634*795d594fSAndroid Build Coastguard Worker                                  &error_msg)) {
635*795d594fSAndroid Build Coastguard Worker       LOG(ERROR) << error_msg;
636*795d594fSAndroid Build Coastguard Worker       return false;
637*795d594fSAndroid Build Coastguard Worker     }
638*795d594fSAndroid Build Coastguard Worker 
639*795d594fSAndroid Build Coastguard Worker     // Write header last in case the compiler gets killed in the middle of image writing.
640*795d594fSAndroid Build Coastguard Worker     // We do not want to have a corrupted image with a valid header.
641*795d594fSAndroid Build Coastguard Worker     // Delay the writing of the primary image header until after writing secondary images.
642*795d594fSAndroid Build Coastguard Worker     if (i == 0u) {
643*795d594fSAndroid Build Coastguard Worker       primary_image_file = std::move(image_file);
644*795d594fSAndroid Build Coastguard Worker     } else {
645*795d594fSAndroid Build Coastguard Worker       if (!image_file.WriteHeaderAndClose(image_filename, image_header, &error_msg)) {
646*795d594fSAndroid Build Coastguard Worker         LOG(ERROR) << error_msg;
647*795d594fSAndroid Build Coastguard Worker         return false;
648*795d594fSAndroid Build Coastguard Worker       }
649*795d594fSAndroid Build Coastguard Worker       // Update the primary image checksum with the secondary image checksum.
650*795d594fSAndroid Build Coastguard Worker       primary_header->SetImageChecksum(
651*795d594fSAndroid Build Coastguard Worker           primary_header->GetImageChecksum() ^ image_header->GetImageChecksum());
652*795d594fSAndroid Build Coastguard Worker     }
653*795d594fSAndroid Build Coastguard Worker   }
654*795d594fSAndroid Build Coastguard Worker   DCHECK(primary_image_file != nullptr);
655*795d594fSAndroid Build Coastguard Worker   std::string error_msg;
656*795d594fSAndroid Build Coastguard Worker   if (!primary_image_file.WriteHeaderAndClose(image_filenames[0], primary_header, &error_msg)) {
657*795d594fSAndroid Build Coastguard Worker     LOG(ERROR) << error_msg;
658*795d594fSAndroid Build Coastguard Worker     return false;
659*795d594fSAndroid Build Coastguard Worker   }
660*795d594fSAndroid Build Coastguard Worker 
661*795d594fSAndroid Build Coastguard Worker   return true;
662*795d594fSAndroid Build Coastguard Worker }
663*795d594fSAndroid Build Coastguard Worker 
GetImageOffset(mirror::Object * object,size_t oat_index) const664*795d594fSAndroid Build Coastguard Worker size_t ImageWriter::GetImageOffset(mirror::Object* object, size_t oat_index) const {
665*795d594fSAndroid Build Coastguard Worker   BinSlot bin_slot = GetImageBinSlot(object, oat_index);
666*795d594fSAndroid Build Coastguard Worker   const ImageInfo& image_info = GetImageInfo(oat_index);
667*795d594fSAndroid Build Coastguard Worker   size_t offset = image_info.GetBinSlotOffset(bin_slot.GetBin()) + bin_slot.GetOffset();
668*795d594fSAndroid Build Coastguard Worker   DCHECK_LT(offset, image_info.image_end_);
669*795d594fSAndroid Build Coastguard Worker   return offset;
670*795d594fSAndroid Build Coastguard Worker }
671*795d594fSAndroid Build Coastguard Worker 
SetImageBinSlot(mirror::Object * object,BinSlot bin_slot)672*795d594fSAndroid Build Coastguard Worker void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
673*795d594fSAndroid Build Coastguard Worker   DCHECK(object != nullptr);
674*795d594fSAndroid Build Coastguard Worker   DCHECK(!IsImageBinSlotAssigned(object));
675*795d594fSAndroid Build Coastguard Worker 
676*795d594fSAndroid Build Coastguard Worker   // Before we stomp over the lock word, save the hash code for later.
677*795d594fSAndroid Build Coastguard Worker   LockWord lw(object->GetLockWord(false));
678*795d594fSAndroid Build Coastguard Worker   switch (lw.GetState()) {
679*795d594fSAndroid Build Coastguard Worker     case LockWord::kFatLocked:
680*795d594fSAndroid Build Coastguard Worker       FALLTHROUGH_INTENDED;
681*795d594fSAndroid Build Coastguard Worker     case LockWord::kThinLocked: {
682*795d594fSAndroid Build Coastguard Worker       std::ostringstream oss;
683*795d594fSAndroid Build Coastguard Worker       bool thin = (lw.GetState() == LockWord::kThinLocked);
684*795d594fSAndroid Build Coastguard Worker       oss << (thin ? "Thin" : "Fat")
685*795d594fSAndroid Build Coastguard Worker           << " locked object " << object << "(" << object->PrettyTypeOf()
686*795d594fSAndroid Build Coastguard Worker           << ") found during object copy";
687*795d594fSAndroid Build Coastguard Worker       if (thin) {
688*795d594fSAndroid Build Coastguard Worker         oss << ". Lock owner:" << lw.ThinLockOwner();
689*795d594fSAndroid Build Coastguard Worker       }
690*795d594fSAndroid Build Coastguard Worker       LOG(FATAL) << oss.str();
691*795d594fSAndroid Build Coastguard Worker       UNREACHABLE();
692*795d594fSAndroid Build Coastguard Worker     }
693*795d594fSAndroid Build Coastguard Worker     case LockWord::kUnlocked:
694*795d594fSAndroid Build Coastguard Worker       // No hash, don't need to save it.
695*795d594fSAndroid Build Coastguard Worker       break;
696*795d594fSAndroid Build Coastguard Worker     case LockWord::kHashCode:
697*795d594fSAndroid Build Coastguard Worker       DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
698*795d594fSAndroid Build Coastguard Worker       saved_hashcode_map_.insert(std::make_pair(object, lw.GetHashCode()));
699*795d594fSAndroid Build Coastguard Worker       break;
700*795d594fSAndroid Build Coastguard Worker     default:
701*795d594fSAndroid Build Coastguard Worker       LOG(FATAL) << "UNREACHABLE";
702*795d594fSAndroid Build Coastguard Worker       UNREACHABLE();
703*795d594fSAndroid Build Coastguard Worker   }
704*795d594fSAndroid Build Coastguard Worker   object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()),
705*795d594fSAndroid Build Coastguard Worker                       /*as_volatile=*/ false);
706*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
707*795d594fSAndroid Build Coastguard Worker   DCHECK(IsImageBinSlotAssigned(object));
708*795d594fSAndroid Build Coastguard Worker }
709*795d594fSAndroid Build Coastguard Worker 
GetImageBin(mirror::Object * object)710*795d594fSAndroid Build Coastguard Worker ImageWriter::Bin ImageWriter::GetImageBin(mirror::Object* object) {
711*795d594fSAndroid Build Coastguard Worker   DCHECK(object != nullptr);
712*795d594fSAndroid Build Coastguard Worker 
713*795d594fSAndroid Build Coastguard Worker   // The magic happens here. We segregate objects into different bins based
714*795d594fSAndroid Build Coastguard Worker   // on how likely they are to get dirty at runtime.
715*795d594fSAndroid Build Coastguard Worker   //
716*795d594fSAndroid Build Coastguard Worker   // Likely-to-dirty objects get packed together into the same bin so that
717*795d594fSAndroid Build Coastguard Worker   // at runtime their page dirtiness ratio (how many dirty objects a page has) is
718*795d594fSAndroid Build Coastguard Worker   // maximized.
719*795d594fSAndroid Build Coastguard Worker   //
720*795d594fSAndroid Build Coastguard Worker   // This means more pages will stay either clean or shared dirty (with zygote) and
721*795d594fSAndroid Build Coastguard Worker   // the app will use less of its own (private) memory.
722*795d594fSAndroid Build Coastguard Worker   Bin bin = Bin::kRegular;
723*795d594fSAndroid Build Coastguard Worker 
724*795d594fSAndroid Build Coastguard Worker   if (kBinObjects) {
725*795d594fSAndroid Build Coastguard Worker     //
726*795d594fSAndroid Build Coastguard Worker     // Changing the bin of an object is purely a memory-use tuning.
727*795d594fSAndroid Build Coastguard Worker     // It has no change on runtime correctness.
728*795d594fSAndroid Build Coastguard Worker     //
729*795d594fSAndroid Build Coastguard Worker     // Memory analysis has determined that the following types of objects get dirtied
730*795d594fSAndroid Build Coastguard Worker     // the most:
731*795d594fSAndroid Build Coastguard Worker     //
732*795d594fSAndroid Build Coastguard Worker     // * Class'es which are verified [their clinit runs only at runtime]
733*795d594fSAndroid Build Coastguard Worker     //   - classes in general [because their static fields get overwritten]
734*795d594fSAndroid Build Coastguard Worker     //   - initialized classes with all-final statics are unlikely to be ever dirty,
735*795d594fSAndroid Build Coastguard Worker     //     so bin them separately
736*795d594fSAndroid Build Coastguard Worker     // * Art Methods that are:
737*795d594fSAndroid Build Coastguard Worker     //   - native [their native entry point is not looked up until runtime]
738*795d594fSAndroid Build Coastguard Worker     //   - have declaring classes that aren't initialized
739*795d594fSAndroid Build Coastguard Worker     //            [their interpreter/quick entry points are trampolines until the class
740*795d594fSAndroid Build Coastguard Worker     //             becomes initialized]
741*795d594fSAndroid Build Coastguard Worker     //
742*795d594fSAndroid Build Coastguard Worker     // We also assume the following objects get dirtied either never or extremely rarely:
743*795d594fSAndroid Build Coastguard Worker     //  * Strings (they are immutable)
744*795d594fSAndroid Build Coastguard Worker     //  * Art methods that aren't native and have initialized declared classes
745*795d594fSAndroid Build Coastguard Worker     //
746*795d594fSAndroid Build Coastguard Worker     // We assume that "regular" bin objects are highly unlikely to become dirtied,
747*795d594fSAndroid Build Coastguard Worker     // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
748*795d594fSAndroid Build Coastguard Worker     //
749*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Class> klass = object->GetClass<kVerifyNone, kWithoutReadBarrier>();
750*795d594fSAndroid Build Coastguard Worker     if (klass->IsStringClass<kVerifyNone>()) {
751*795d594fSAndroid Build Coastguard Worker       // Assign strings to their bin before checking dirty objects, because
752*795d594fSAndroid Build Coastguard Worker       // string intern processing expects strings to be in Bin::kString.
753*795d594fSAndroid Build Coastguard Worker       bin = Bin::kString;  // Strings are almost always immutable (except for object header).
754*795d594fSAndroid Build Coastguard Worker     } else if (dirty_objects_.find(object) != dirty_objects_.end()) {
755*795d594fSAndroid Build Coastguard Worker       bin = Bin::kKnownDirty;
756*795d594fSAndroid Build Coastguard Worker     } else if (klass->IsClassClass()) {
757*795d594fSAndroid Build Coastguard Worker       bin = Bin::kClassVerified;
758*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Class> as_klass = object->AsClass<kVerifyNone>();
759*795d594fSAndroid Build Coastguard Worker       if (as_klass->IsVisiblyInitialized<kVerifyNone>()) {
760*795d594fSAndroid Build Coastguard Worker         bin = Bin::kClassInitialized;
761*795d594fSAndroid Build Coastguard Worker 
762*795d594fSAndroid Build Coastguard Worker         // If the class's static fields are all final, put it into a separate bin
763*795d594fSAndroid Build Coastguard Worker         // since it's very likely it will stay clean.
764*795d594fSAndroid Build Coastguard Worker         uint32_t num_static_fields = as_klass->NumStaticFields();
765*795d594fSAndroid Build Coastguard Worker         if (num_static_fields == 0) {
766*795d594fSAndroid Build Coastguard Worker           bin = Bin::kClassInitializedFinalStatics;
767*795d594fSAndroid Build Coastguard Worker         } else {
768*795d594fSAndroid Build Coastguard Worker           // Maybe all the statics are final?
769*795d594fSAndroid Build Coastguard Worker           bool all_final = true;
770*795d594fSAndroid Build Coastguard Worker           for (uint32_t i = 0; i < num_static_fields; ++i) {
771*795d594fSAndroid Build Coastguard Worker             ArtField* field = as_klass->GetStaticField(i);
772*795d594fSAndroid Build Coastguard Worker             if (!field->IsFinal()) {
773*795d594fSAndroid Build Coastguard Worker               all_final = false;
774*795d594fSAndroid Build Coastguard Worker               break;
775*795d594fSAndroid Build Coastguard Worker             }
776*795d594fSAndroid Build Coastguard Worker           }
777*795d594fSAndroid Build Coastguard Worker 
778*795d594fSAndroid Build Coastguard Worker           if (all_final) {
779*795d594fSAndroid Build Coastguard Worker             bin = Bin::kClassInitializedFinalStatics;
780*795d594fSAndroid Build Coastguard Worker           }
781*795d594fSAndroid Build Coastguard Worker         }
782*795d594fSAndroid Build Coastguard Worker       }
783*795d594fSAndroid Build Coastguard Worker     } else if (!klass->HasSuperClass()) {
784*795d594fSAndroid Build Coastguard Worker       // Only `j.l.Object` and primitive classes lack the superclass and
785*795d594fSAndroid Build Coastguard Worker       // there are no instances of primitive classes.
786*795d594fSAndroid Build Coastguard Worker       DCHECK(klass->IsObjectClass());
787*795d594fSAndroid Build Coastguard Worker       // Instance of java lang object, probably a lock object. This means it will be dirty when we
788*795d594fSAndroid Build Coastguard Worker       // synchronize on it.
789*795d594fSAndroid Build Coastguard Worker       bin = Bin::kMiscDirty;
790*795d594fSAndroid Build Coastguard Worker     } else if (klass->IsDexCacheClass<kVerifyNone>()) {
791*795d594fSAndroid Build Coastguard Worker       // Dex file field becomes dirty when the image is loaded.
792*795d594fSAndroid Build Coastguard Worker       bin = Bin::kMiscDirty;
793*795d594fSAndroid Build Coastguard Worker     }
794*795d594fSAndroid Build Coastguard Worker     // else bin = kBinRegular
795*795d594fSAndroid Build Coastguard Worker   }
796*795d594fSAndroid Build Coastguard Worker 
797*795d594fSAndroid Build Coastguard Worker   return bin;
798*795d594fSAndroid Build Coastguard Worker }
799*795d594fSAndroid Build Coastguard Worker 
AssignImageBinSlot(mirror::Object * object,size_t oat_index,Bin bin)800*795d594fSAndroid Build Coastguard Worker void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index, Bin bin) {
801*795d594fSAndroid Build Coastguard Worker   DCHECK(object != nullptr);
802*795d594fSAndroid Build Coastguard Worker   size_t object_size = object->SizeOf();
803*795d594fSAndroid Build Coastguard Worker 
804*795d594fSAndroid Build Coastguard Worker   // Assign the oat index too.
805*795d594fSAndroid Build Coastguard Worker   if (IsMultiImage()) {
806*795d594fSAndroid Build Coastguard Worker     DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
807*795d594fSAndroid Build Coastguard Worker     oat_index_map_.insert(std::make_pair(object, oat_index));
808*795d594fSAndroid Build Coastguard Worker   } else {
809*795d594fSAndroid Build Coastguard Worker     DCHECK(oat_index_map_.empty());
810*795d594fSAndroid Build Coastguard Worker   }
811*795d594fSAndroid Build Coastguard Worker 
812*795d594fSAndroid Build Coastguard Worker   ImageInfo& image_info = GetImageInfo(oat_index);
813*795d594fSAndroid Build Coastguard Worker 
814*795d594fSAndroid Build Coastguard Worker   size_t offset_delta = RoundUp(object_size, kObjectAlignment);  // 64-bit alignment
815*795d594fSAndroid Build Coastguard Worker   // How many bytes the current bin is at (aligned).
816*795d594fSAndroid Build Coastguard Worker   size_t current_offset = image_info.GetBinSlotSize(bin);
817*795d594fSAndroid Build Coastguard Worker   // Move the current bin size up to accommodate the object we just assigned a bin slot.
818*795d594fSAndroid Build Coastguard Worker   image_info.IncrementBinSlotSize(bin, offset_delta);
819*795d594fSAndroid Build Coastguard Worker 
820*795d594fSAndroid Build Coastguard Worker   BinSlot new_bin_slot(bin, current_offset);
821*795d594fSAndroid Build Coastguard Worker   SetImageBinSlot(object, new_bin_slot);
822*795d594fSAndroid Build Coastguard Worker 
823*795d594fSAndroid Build Coastguard Worker   image_info.IncrementBinSlotCount(bin, 1u);
824*795d594fSAndroid Build Coastguard Worker 
825*795d594fSAndroid Build Coastguard Worker   // Grow the image closer to the end by the object we just assigned.
826*795d594fSAndroid Build Coastguard Worker   image_info.image_end_ += offset_delta;
827*795d594fSAndroid Build Coastguard Worker }
828*795d594fSAndroid Build Coastguard Worker 
WillMethodBeDirty(ArtMethod * m) const829*795d594fSAndroid Build Coastguard Worker bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
830*795d594fSAndroid Build Coastguard Worker   if (m->IsNative()) {
831*795d594fSAndroid Build Coastguard Worker     return true;
832*795d594fSAndroid Build Coastguard Worker   }
833*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClass<kWithoutReadBarrier>();
834*795d594fSAndroid Build Coastguard Worker   // Initialized is highly unlikely to dirty since there's no entry points to mutate.
835*795d594fSAndroid Build Coastguard Worker   return declaring_class == nullptr ||
836*795d594fSAndroid Build Coastguard Worker          declaring_class->GetStatus() != ClassStatus::kVisiblyInitialized;
837*795d594fSAndroid Build Coastguard Worker }
838*795d594fSAndroid Build Coastguard Worker 
IsImageBinSlotAssigned(mirror::Object * object) const839*795d594fSAndroid Build Coastguard Worker bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
840*795d594fSAndroid Build Coastguard Worker   DCHECK(object != nullptr);
841*795d594fSAndroid Build Coastguard Worker 
842*795d594fSAndroid Build Coastguard Worker   // We always stash the bin slot into a lockword, in the 'forwarding address' state.
843*795d594fSAndroid Build Coastguard Worker   // If it's in some other state, then we haven't yet assigned an image bin slot.
844*795d594fSAndroid Build Coastguard Worker   if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
845*795d594fSAndroid Build Coastguard Worker     return false;
846*795d594fSAndroid Build Coastguard Worker   } else if (kIsDebugBuild) {
847*795d594fSAndroid Build Coastguard Worker     LockWord lock_word = object->GetLockWord(false);
848*795d594fSAndroid Build Coastguard Worker     size_t offset = lock_word.ForwardingAddress();
849*795d594fSAndroid Build Coastguard Worker     BinSlot bin_slot(offset);
850*795d594fSAndroid Build Coastguard Worker     size_t oat_index = GetOatIndex(object);
851*795d594fSAndroid Build Coastguard Worker     const ImageInfo& image_info = GetImageInfo(oat_index);
852*795d594fSAndroid Build Coastguard Worker     DCHECK_LT(bin_slot.GetOffset(), image_info.GetBinSlotSize(bin_slot.GetBin()))
853*795d594fSAndroid Build Coastguard Worker         << "bin slot offset should not exceed the size of that bin";
854*795d594fSAndroid Build Coastguard Worker   }
855*795d594fSAndroid Build Coastguard Worker   return true;
856*795d594fSAndroid Build Coastguard Worker }
857*795d594fSAndroid Build Coastguard Worker 
GetImageBinSlot(mirror::Object * object,size_t oat_index) const858*795d594fSAndroid Build Coastguard Worker ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object, size_t oat_index) const {
859*795d594fSAndroid Build Coastguard Worker   DCHECK(object != nullptr);
860*795d594fSAndroid Build Coastguard Worker   DCHECK(IsImageBinSlotAssigned(object));
861*795d594fSAndroid Build Coastguard Worker 
862*795d594fSAndroid Build Coastguard Worker   LockWord lock_word = object->GetLockWord(false);
863*795d594fSAndroid Build Coastguard Worker   size_t offset = lock_word.ForwardingAddress();  // TODO: ForwardingAddress should be uint32_t
864*795d594fSAndroid Build Coastguard Worker   DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
865*795d594fSAndroid Build Coastguard Worker 
866*795d594fSAndroid Build Coastguard Worker   BinSlot bin_slot(static_cast<uint32_t>(offset));
867*795d594fSAndroid Build Coastguard Worker   DCHECK_LT(bin_slot.GetOffset(), GetImageInfo(oat_index).GetBinSlotSize(bin_slot.GetBin()));
868*795d594fSAndroid Build Coastguard Worker 
869*795d594fSAndroid Build Coastguard Worker   return bin_slot;
870*795d594fSAndroid Build Coastguard Worker }
871*795d594fSAndroid Build Coastguard Worker 
UpdateImageBinSlotOffset(mirror::Object * object,size_t oat_index,size_t new_offset)872*795d594fSAndroid Build Coastguard Worker void ImageWriter::UpdateImageBinSlotOffset(mirror::Object* object,
873*795d594fSAndroid Build Coastguard Worker                                            size_t oat_index,
874*795d594fSAndroid Build Coastguard Worker                                            size_t new_offset) {
875*795d594fSAndroid Build Coastguard Worker   BinSlot old_bin_slot = GetImageBinSlot(object, oat_index);
876*795d594fSAndroid Build Coastguard Worker   DCHECK_LT(new_offset, GetImageInfo(oat_index).GetBinSlotSize(old_bin_slot.GetBin()));
877*795d594fSAndroid Build Coastguard Worker   BinSlot new_bin_slot(old_bin_slot.GetBin(), new_offset);
878*795d594fSAndroid Build Coastguard Worker   object->SetLockWord(LockWord::FromForwardingAddress(new_bin_slot.Uint32Value()),
879*795d594fSAndroid Build Coastguard Worker                       /*as_volatile=*/ false);
880*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
881*795d594fSAndroid Build Coastguard Worker   DCHECK(IsImageBinSlotAssigned(object));
882*795d594fSAndroid Build Coastguard Worker }
883*795d594fSAndroid Build Coastguard Worker 
AllocMemory()884*795d594fSAndroid Build Coastguard Worker bool ImageWriter::AllocMemory() {
885*795d594fSAndroid Build Coastguard Worker   for (ImageInfo& image_info : image_infos_) {
886*795d594fSAndroid Build Coastguard Worker     const size_t length = RoundUp(image_info.CreateImageSections().first, kElfSegmentAlignment);
887*795d594fSAndroid Build Coastguard Worker 
888*795d594fSAndroid Build Coastguard Worker     std::string error_msg;
889*795d594fSAndroid Build Coastguard Worker     image_info.image_ = MemMap::MapAnonymous("image writer image",
890*795d594fSAndroid Build Coastguard Worker                                              length,
891*795d594fSAndroid Build Coastguard Worker                                              PROT_READ | PROT_WRITE,
892*795d594fSAndroid Build Coastguard Worker                                              /*low_4gb=*/ false,
893*795d594fSAndroid Build Coastguard Worker                                              &error_msg);
894*795d594fSAndroid Build Coastguard Worker     if (UNLIKELY(!image_info.image_.IsValid())) {
895*795d594fSAndroid Build Coastguard Worker       LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
896*795d594fSAndroid Build Coastguard Worker       return false;
897*795d594fSAndroid Build Coastguard Worker     }
898*795d594fSAndroid Build Coastguard Worker 
899*795d594fSAndroid Build Coastguard Worker     // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
900*795d594fSAndroid Build Coastguard Worker     // The covered size is rounded up to kCardSize to match the bitmap size expected by Loader::Init
901*795d594fSAndroid Build Coastguard Worker     // at art::gc::space::ImageSpace.
902*795d594fSAndroid Build Coastguard Worker     CHECK_LE(image_info.image_end_, length);
903*795d594fSAndroid Build Coastguard Worker     image_info.image_bitmap_ = gc::accounting::ContinuousSpaceBitmap::Create("image bitmap",
904*795d594fSAndroid Build Coastguard Worker         image_info.image_.Begin(),
905*795d594fSAndroid Build Coastguard Worker         RoundUp(image_info.image_end_, gc::accounting::CardTable::kCardSize));
906*795d594fSAndroid Build Coastguard Worker     if (!image_info.image_bitmap_.IsValid()) {
907*795d594fSAndroid Build Coastguard Worker       LOG(ERROR) << "Failed to allocate memory for image bitmap";
908*795d594fSAndroid Build Coastguard Worker       return false;
909*795d594fSAndroid Build Coastguard Worker     }
910*795d594fSAndroid Build Coastguard Worker   }
911*795d594fSAndroid Build Coastguard Worker   return true;
912*795d594fSAndroid Build Coastguard Worker }
913*795d594fSAndroid Build Coastguard Worker 
914*795d594fSAndroid Build Coastguard Worker // This visitor follows the references of an instance, recursively then prune this class
915*795d594fSAndroid Build Coastguard Worker // if a type of any field is pruned.
916*795d594fSAndroid Build Coastguard Worker class ImageWriter::PruneObjectReferenceVisitor {
917*795d594fSAndroid Build Coastguard Worker  public:
PruneObjectReferenceVisitor(ImageWriter * image_writer,bool * early_exit,HashSet<mirror::Object * > * visited,bool * result)918*795d594fSAndroid Build Coastguard Worker   PruneObjectReferenceVisitor(ImageWriter* image_writer,
919*795d594fSAndroid Build Coastguard Worker                         bool* early_exit,
920*795d594fSAndroid Build Coastguard Worker                         HashSet<mirror::Object*>* visited,
921*795d594fSAndroid Build Coastguard Worker                         bool* result)
922*795d594fSAndroid Build Coastguard Worker       : image_writer_(image_writer), early_exit_(early_exit), visited_(visited), result_(result) {}
923*795d594fSAndroid Build Coastguard Worker 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const924*795d594fSAndroid Build Coastguard Worker   ALWAYS_INLINE void VisitRootIfNonNull(
925*795d594fSAndroid Build Coastguard Worker       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const
926*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {}
927*795d594fSAndroid Build Coastguard Worker 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const928*795d594fSAndroid Build Coastguard Worker   ALWAYS_INLINE void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root)
929*795d594fSAndroid Build Coastguard Worker       const REQUIRES_SHARED(Locks::mutator_lock_) {}
930*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static) const931*795d594fSAndroid Build Coastguard Worker   ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
932*795d594fSAndroid Build Coastguard Worker                                 MemberOffset offset,
933*795d594fSAndroid Build Coastguard Worker                                 [[maybe_unused]] bool is_static) const
934*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
935*795d594fSAndroid Build Coastguard Worker     mirror::Object* ref =
936*795d594fSAndroid Build Coastguard Worker         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
937*795d594fSAndroid Build Coastguard Worker     if (ref == nullptr || visited_->find(ref) != visited_->end()) {
938*795d594fSAndroid Build Coastguard Worker       return;
939*795d594fSAndroid Build Coastguard Worker     }
940*795d594fSAndroid Build Coastguard Worker 
941*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
942*795d594fSAndroid Build Coastguard Worker         Runtime::Current()->GetClassLinker()->GetClassRoots();
943*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Class> klass = ref->IsClass() ? ref->AsClass() : ref->GetClass();
944*795d594fSAndroid Build Coastguard Worker     if (klass == GetClassRoot<mirror::Method>(class_roots) ||
945*795d594fSAndroid Build Coastguard Worker         klass == GetClassRoot<mirror::Constructor>(class_roots)) {
946*795d594fSAndroid Build Coastguard Worker       // Prune all classes using reflection because the content they held will not be fixup.
947*795d594fSAndroid Build Coastguard Worker       *result_ = true;
948*795d594fSAndroid Build Coastguard Worker     }
949*795d594fSAndroid Build Coastguard Worker 
950*795d594fSAndroid Build Coastguard Worker     if (ref->IsClass()) {
951*795d594fSAndroid Build Coastguard Worker       *result_ = *result_ ||
952*795d594fSAndroid Build Coastguard Worker           image_writer_->PruneImageClassInternal(ref->AsClass(), early_exit_, visited_);
953*795d594fSAndroid Build Coastguard Worker     } else {
954*795d594fSAndroid Build Coastguard Worker       // Record the object visited in case of circular reference.
955*795d594fSAndroid Build Coastguard Worker       visited_->insert(ref);
956*795d594fSAndroid Build Coastguard Worker       *result_ = *result_ ||
957*795d594fSAndroid Build Coastguard Worker           image_writer_->PruneImageClassInternal(klass, early_exit_, visited_);
958*795d594fSAndroid Build Coastguard Worker       ref->VisitReferences(*this, *this);
959*795d594fSAndroid Build Coastguard Worker       // Clean up before exit for next call of this function.
960*795d594fSAndroid Build Coastguard Worker       auto it = visited_->find(ref);
961*795d594fSAndroid Build Coastguard Worker       DCHECK(it != visited_->end());
962*795d594fSAndroid Build Coastguard Worker       visited_->erase(it);
963*795d594fSAndroid Build Coastguard Worker     }
964*795d594fSAndroid Build Coastguard Worker   }
965*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const966*795d594fSAndroid Build Coastguard Worker   ALWAYS_INLINE void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass,
967*795d594fSAndroid Build Coastguard Worker                                 ObjPtr<mirror::Reference> ref) const
968*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
969*795d594fSAndroid Build Coastguard Worker     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
970*795d594fSAndroid Build Coastguard Worker   }
971*795d594fSAndroid Build Coastguard Worker 
972*795d594fSAndroid Build Coastguard Worker  private:
973*795d594fSAndroid Build Coastguard Worker   ImageWriter* image_writer_;
974*795d594fSAndroid Build Coastguard Worker   bool* early_exit_;
975*795d594fSAndroid Build Coastguard Worker   HashSet<mirror::Object*>* visited_;
976*795d594fSAndroid Build Coastguard Worker   bool* const result_;
977*795d594fSAndroid Build Coastguard Worker };
978*795d594fSAndroid Build Coastguard Worker 
979*795d594fSAndroid Build Coastguard Worker 
PruneImageClass(ObjPtr<mirror::Class> klass)980*795d594fSAndroid Build Coastguard Worker bool ImageWriter::PruneImageClass(ObjPtr<mirror::Class> klass) {
981*795d594fSAndroid Build Coastguard Worker   bool early_exit = false;
982*795d594fSAndroid Build Coastguard Worker   HashSet<mirror::Object*> visited;
983*795d594fSAndroid Build Coastguard Worker   return PruneImageClassInternal(klass, &early_exit, &visited);
984*795d594fSAndroid Build Coastguard Worker }
985*795d594fSAndroid Build Coastguard Worker 
PruneImageClassInternal(ObjPtr<mirror::Class> klass,bool * early_exit,HashSet<mirror::Object * > * visited)986*795d594fSAndroid Build Coastguard Worker bool ImageWriter::PruneImageClassInternal(
987*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Class> klass,
988*795d594fSAndroid Build Coastguard Worker     bool* early_exit,
989*795d594fSAndroid Build Coastguard Worker     HashSet<mirror::Object*>* visited) {
990*795d594fSAndroid Build Coastguard Worker   DCHECK(early_exit != nullptr);
991*795d594fSAndroid Build Coastguard Worker   DCHECK(visited != nullptr);
992*795d594fSAndroid Build Coastguard Worker   DCHECK(compiler_options_.IsAppImage() || compiler_options_.IsBootImageExtension());
993*795d594fSAndroid Build Coastguard Worker   if (klass == nullptr || IsInBootImage(klass.Ptr())) {
994*795d594fSAndroid Build Coastguard Worker     return false;
995*795d594fSAndroid Build Coastguard Worker   }
996*795d594fSAndroid Build Coastguard Worker   auto found = prune_class_memo_.find(klass.Ptr());
997*795d594fSAndroid Build Coastguard Worker   if (found != prune_class_memo_.end()) {
998*795d594fSAndroid Build Coastguard Worker     // Already computed, return the found value.
999*795d594fSAndroid Build Coastguard Worker     return found->second;
1000*795d594fSAndroid Build Coastguard Worker   }
1001*795d594fSAndroid Build Coastguard Worker   // Circular dependencies, return false but do not store the result in the memoization table.
1002*795d594fSAndroid Build Coastguard Worker   if (visited->find(klass.Ptr()) != visited->end()) {
1003*795d594fSAndroid Build Coastguard Worker     *early_exit = true;
1004*795d594fSAndroid Build Coastguard Worker     return false;
1005*795d594fSAndroid Build Coastguard Worker   }
1006*795d594fSAndroid Build Coastguard Worker   visited->insert(klass.Ptr());
1007*795d594fSAndroid Build Coastguard Worker   bool result = klass->IsBootStrapClassLoaded();
1008*795d594fSAndroid Build Coastguard Worker   std::string temp;
1009*795d594fSAndroid Build Coastguard Worker   // Prune if not an image class, this handles any broken sets of image classes such as having a
1010*795d594fSAndroid Build Coastguard Worker   // class in the set but not it's superclass.
1011*795d594fSAndroid Build Coastguard Worker   result = result || !compiler_options_.IsImageClass(klass->GetDescriptor(&temp));
1012*795d594fSAndroid Build Coastguard Worker   bool my_early_exit = false;  // Only for ourselves, ignore caller.
1013*795d594fSAndroid Build Coastguard Worker   // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
1014*795d594fSAndroid Build Coastguard Worker   // app image.
1015*795d594fSAndroid Build Coastguard Worker   if (klass->IsErroneous()) {
1016*795d594fSAndroid Build Coastguard Worker     result = true;
1017*795d594fSAndroid Build Coastguard Worker   } else {
1018*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
1019*795d594fSAndroid Build Coastguard Worker     CHECK(ext.IsNull() || ext->GetErroneousStateError() == nullptr) << klass->PrettyClass();
1020*795d594fSAndroid Build Coastguard Worker   }
1021*795d594fSAndroid Build Coastguard Worker   if (!result) {
1022*795d594fSAndroid Build Coastguard Worker     // Check interfaces since these wont be visited through VisitReferences.)
1023*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
1024*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
1025*795d594fSAndroid Build Coastguard Worker       result = result || PruneImageClassInternal(if_table->GetInterface(i),
1026*795d594fSAndroid Build Coastguard Worker                                                  &my_early_exit,
1027*795d594fSAndroid Build Coastguard Worker                                                  visited);
1028*795d594fSAndroid Build Coastguard Worker     }
1029*795d594fSAndroid Build Coastguard Worker   }
1030*795d594fSAndroid Build Coastguard Worker   if (klass->IsObjectArrayClass()) {
1031*795d594fSAndroid Build Coastguard Worker     result = result || PruneImageClassInternal(klass->GetComponentType(),
1032*795d594fSAndroid Build Coastguard Worker                                                &my_early_exit,
1033*795d594fSAndroid Build Coastguard Worker                                                visited);
1034*795d594fSAndroid Build Coastguard Worker   }
1035*795d594fSAndroid Build Coastguard Worker   // Check static fields and their classes.
1036*795d594fSAndroid Build Coastguard Worker   if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
1037*795d594fSAndroid Build Coastguard Worker     size_t num_static_fields = klass->NumReferenceStaticFields();
1038*795d594fSAndroid Build Coastguard Worker     // Presumably GC can happen when we are cross compiling, it should not cause performance
1039*795d594fSAndroid Build Coastguard Worker     // problems to do pointer size logic.
1040*795d594fSAndroid Build Coastguard Worker     MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
1041*795d594fSAndroid Build Coastguard Worker         Runtime::Current()->GetClassLinker()->GetImagePointerSize());
1042*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0u; i < num_static_fields; ++i) {
1043*795d594fSAndroid Build Coastguard Worker       mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
1044*795d594fSAndroid Build Coastguard Worker       if (ref != nullptr) {
1045*795d594fSAndroid Build Coastguard Worker         if (ref->IsClass()) {
1046*795d594fSAndroid Build Coastguard Worker           result = result || PruneImageClassInternal(ref->AsClass(), &my_early_exit, visited);
1047*795d594fSAndroid Build Coastguard Worker         } else {
1048*795d594fSAndroid Build Coastguard Worker           mirror::Class* type = ref->GetClass();
1049*795d594fSAndroid Build Coastguard Worker           result = result || PruneImageClassInternal(type, &my_early_exit, visited);
1050*795d594fSAndroid Build Coastguard Worker           if (!result) {
1051*795d594fSAndroid Build Coastguard Worker             // For non-class case, also go through all the types mentioned by it's fields'
1052*795d594fSAndroid Build Coastguard Worker             // references recursively to decide whether to keep this class.
1053*795d594fSAndroid Build Coastguard Worker             bool tmp = false;
1054*795d594fSAndroid Build Coastguard Worker             PruneObjectReferenceVisitor visitor(this, &my_early_exit, visited, &tmp);
1055*795d594fSAndroid Build Coastguard Worker             ref->VisitReferences(visitor, visitor);
1056*795d594fSAndroid Build Coastguard Worker             result = result || tmp;
1057*795d594fSAndroid Build Coastguard Worker           }
1058*795d594fSAndroid Build Coastguard Worker         }
1059*795d594fSAndroid Build Coastguard Worker       }
1060*795d594fSAndroid Build Coastguard Worker       field_offset = MemberOffset(field_offset.Uint32Value() +
1061*795d594fSAndroid Build Coastguard Worker                                   sizeof(mirror::HeapReference<mirror::Object>));
1062*795d594fSAndroid Build Coastguard Worker     }
1063*795d594fSAndroid Build Coastguard Worker   }
1064*795d594fSAndroid Build Coastguard Worker   result = result || PruneImageClassInternal(klass->GetSuperClass(), &my_early_exit, visited);
1065*795d594fSAndroid Build Coastguard Worker   // Remove the class if the dex file is not in the set of dex files. This happens for classes that
1066*795d594fSAndroid Build Coastguard Worker   // are from uses-library if there is no profile. b/30688277
1067*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
1068*795d594fSAndroid Build Coastguard Worker   if (dex_cache != nullptr) {
1069*795d594fSAndroid Build Coastguard Worker     result = result ||
1070*795d594fSAndroid Build Coastguard Worker         dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
1071*795d594fSAndroid Build Coastguard Worker   }
1072*795d594fSAndroid Build Coastguard Worker   // Erase the element we stored earlier since we are exiting the function.
1073*795d594fSAndroid Build Coastguard Worker   auto it = visited->find(klass.Ptr());
1074*795d594fSAndroid Build Coastguard Worker   DCHECK(it != visited->end());
1075*795d594fSAndroid Build Coastguard Worker   visited->erase(it);
1076*795d594fSAndroid Build Coastguard Worker   // Only store result if it is true or none of the calls early exited due to circular
1077*795d594fSAndroid Build Coastguard Worker   // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
1078*795d594fSAndroid Build Coastguard Worker   // a child call and we can remember the result.
1079*795d594fSAndroid Build Coastguard Worker   if (result == true || !my_early_exit || visited->empty()) {
1080*795d594fSAndroid Build Coastguard Worker     prune_class_memo_.Overwrite(klass.Ptr(), result);
1081*795d594fSAndroid Build Coastguard Worker   }
1082*795d594fSAndroid Build Coastguard Worker   *early_exit |= my_early_exit;
1083*795d594fSAndroid Build Coastguard Worker   return result;
1084*795d594fSAndroid Build Coastguard Worker }
1085*795d594fSAndroid Build Coastguard Worker 
KeepClass(ObjPtr<mirror::Class> klass)1086*795d594fSAndroid Build Coastguard Worker bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
1087*795d594fSAndroid Build Coastguard Worker   if (klass == nullptr) {
1088*795d594fSAndroid Build Coastguard Worker     return false;
1089*795d594fSAndroid Build Coastguard Worker   }
1090*795d594fSAndroid Build Coastguard Worker   if (IsInBootImage(klass.Ptr())) {
1091*795d594fSAndroid Build Coastguard Worker     // Already in boot image, return true.
1092*795d594fSAndroid Build Coastguard Worker     DCHECK(!compiler_options_.IsBootImage());
1093*795d594fSAndroid Build Coastguard Worker     return true;
1094*795d594fSAndroid Build Coastguard Worker   }
1095*795d594fSAndroid Build Coastguard Worker   std::string temp;
1096*795d594fSAndroid Build Coastguard Worker   if (!compiler_options_.IsImageClass(klass->GetDescriptor(&temp))) {
1097*795d594fSAndroid Build Coastguard Worker     return false;
1098*795d594fSAndroid Build Coastguard Worker   }
1099*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsAppImage()) {
1100*795d594fSAndroid Build Coastguard Worker     // For app images, we need to prune classes that
1101*795d594fSAndroid Build Coastguard Worker     // are defined by the boot class path we're compiling against but not in
1102*795d594fSAndroid Build Coastguard Worker     // the boot image spaces since these may have already been loaded at
1103*795d594fSAndroid Build Coastguard Worker     // run time when this image is loaded. Keep classes in the boot image
1104*795d594fSAndroid Build Coastguard Worker     // spaces we're compiling against since we don't want to re-resolve these.
1105*795d594fSAndroid Build Coastguard Worker     // FIXME: Update image classes in the `CompilerOptions` after initializing classes
1106*795d594fSAndroid Build Coastguard Worker     // with `--initialize-app-image-classes=true`. This experimental flag can currently
1107*795d594fSAndroid Build Coastguard Worker     // cause an inconsistency between `CompilerOptions::IsImageClass()` and what actually
1108*795d594fSAndroid Build Coastguard Worker     // ends up in the app image as seen in the run-test `660-clinit` where the class
1109*795d594fSAndroid Build Coastguard Worker     // `ObjectRef` is considered an app image class during compilation but in the end
1110*795d594fSAndroid Build Coastguard Worker     // it's pruned here. This inconsistency should be fixed if we want to properly
1111*795d594fSAndroid Build Coastguard Worker     // initialize app image classes. b/38313278
1112*795d594fSAndroid Build Coastguard Worker     bool keep = !PruneImageClass(klass);
1113*795d594fSAndroid Build Coastguard Worker     CHECK_IMPLIES(!compiler_options_.InitializeAppImageClasses(), keep)
1114*795d594fSAndroid Build Coastguard Worker         << klass->PrettyDescriptor();
1115*795d594fSAndroid Build Coastguard Worker     return keep;
1116*795d594fSAndroid Build Coastguard Worker   }
1117*795d594fSAndroid Build Coastguard Worker   return true;
1118*795d594fSAndroid Build Coastguard Worker }
1119*795d594fSAndroid Build Coastguard Worker 
1120*795d594fSAndroid Build Coastguard Worker class ImageWriter::PruneClassesVisitor : public ClassVisitor {
1121*795d594fSAndroid Build Coastguard Worker  public:
PruneClassesVisitor(ImageWriter * image_writer,ObjPtr<mirror::ClassLoader> class_loader)1122*795d594fSAndroid Build Coastguard Worker   PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
1123*795d594fSAndroid Build Coastguard Worker       : image_writer_(image_writer),
1124*795d594fSAndroid Build Coastguard Worker         class_loader_(class_loader),
1125*795d594fSAndroid Build Coastguard Worker         classes_to_prune_(),
1126*795d594fSAndroid Build Coastguard Worker         defined_class_count_(0u) { }
1127*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass)1128*795d594fSAndroid Build Coastguard Worker   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
1129*795d594fSAndroid Build Coastguard Worker     if (!image_writer_->KeepClass(klass.Ptr())) {
1130*795d594fSAndroid Build Coastguard Worker       classes_to_prune_.insert(klass.Ptr());
1131*795d594fSAndroid Build Coastguard Worker       if (klass->GetClassLoader() == class_loader_) {
1132*795d594fSAndroid Build Coastguard Worker         ++defined_class_count_;
1133*795d594fSAndroid Build Coastguard Worker       }
1134*795d594fSAndroid Build Coastguard Worker     }
1135*795d594fSAndroid Build Coastguard Worker     return true;
1136*795d594fSAndroid Build Coastguard Worker   }
1137*795d594fSAndroid Build Coastguard Worker 
Prune()1138*795d594fSAndroid Build Coastguard Worker   size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
1139*795d594fSAndroid Build Coastguard Worker     ClassTable* class_table =
1140*795d594fSAndroid Build Coastguard Worker         Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
1141*795d594fSAndroid Build Coastguard Worker     WriterMutexLock mu(Thread::Current(), class_table->lock_);
1142*795d594fSAndroid Build Coastguard Worker     // App class loader class tables contain only one internal set. The boot class path class
1143*795d594fSAndroid Build Coastguard Worker     // table also contains class sets from boot images we're compiling against but we are not
1144*795d594fSAndroid Build Coastguard Worker     // pruning these boot image classes, so all classes to remove are in the last set.
1145*795d594fSAndroid Build Coastguard Worker     DCHECK(!class_table->classes_.empty());
1146*795d594fSAndroid Build Coastguard Worker     ClassTable::ClassSet& last_class_set = class_table->classes_.back();
1147*795d594fSAndroid Build Coastguard Worker     for (mirror::Class* klass : classes_to_prune_) {
1148*795d594fSAndroid Build Coastguard Worker       uint32_t hash = klass->DescriptorHash();
1149*795d594fSAndroid Build Coastguard Worker       auto it = last_class_set.FindWithHash(ClassTable::TableSlot(klass, hash), hash);
1150*795d594fSAndroid Build Coastguard Worker       DCHECK(it != last_class_set.end());
1151*795d594fSAndroid Build Coastguard Worker       last_class_set.erase(it);
1152*795d594fSAndroid Build Coastguard Worker       DCHECK(std::none_of(class_table->classes_.begin(),
1153*795d594fSAndroid Build Coastguard Worker                           class_table->classes_.end(),
1154*795d594fSAndroid Build Coastguard Worker                           [klass, hash](ClassTable::ClassSet& class_set)
1155*795d594fSAndroid Build Coastguard Worker                               REQUIRES_SHARED(Locks::mutator_lock_) {
1156*795d594fSAndroid Build Coastguard Worker                             ClassTable::TableSlot slot(klass, hash);
1157*795d594fSAndroid Build Coastguard Worker                             return class_set.FindWithHash(slot, hash) != class_set.end();
1158*795d594fSAndroid Build Coastguard Worker                           }));
1159*795d594fSAndroid Build Coastguard Worker     }
1160*795d594fSAndroid Build Coastguard Worker     return defined_class_count_;
1161*795d594fSAndroid Build Coastguard Worker   }
1162*795d594fSAndroid Build Coastguard Worker 
1163*795d594fSAndroid Build Coastguard Worker  private:
1164*795d594fSAndroid Build Coastguard Worker   ImageWriter* const image_writer_;
1165*795d594fSAndroid Build Coastguard Worker   const ObjPtr<mirror::ClassLoader> class_loader_;
1166*795d594fSAndroid Build Coastguard Worker   HashSet<mirror::Class*> classes_to_prune_;
1167*795d594fSAndroid Build Coastguard Worker   size_t defined_class_count_;
1168*795d594fSAndroid Build Coastguard Worker };
1169*795d594fSAndroid Build Coastguard Worker 
1170*795d594fSAndroid Build Coastguard Worker class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
1171*795d594fSAndroid Build Coastguard Worker  public:
PruneClassLoaderClassesVisitor(ImageWriter * image_writer)1172*795d594fSAndroid Build Coastguard Worker   explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
1173*795d594fSAndroid Build Coastguard Worker       : image_writer_(image_writer), removed_class_count_(0) {}
1174*795d594fSAndroid Build Coastguard Worker 
Visit(ObjPtr<mirror::ClassLoader> class_loader)1175*795d594fSAndroid Build Coastguard Worker   void Visit(ObjPtr<mirror::ClassLoader> class_loader) override
1176*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
1177*795d594fSAndroid Build Coastguard Worker     PruneClassesVisitor classes_visitor(image_writer_, class_loader);
1178*795d594fSAndroid Build Coastguard Worker     ClassTable* class_table =
1179*795d594fSAndroid Build Coastguard Worker         Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
1180*795d594fSAndroid Build Coastguard Worker     class_table->Visit(classes_visitor);
1181*795d594fSAndroid Build Coastguard Worker     removed_class_count_ += classes_visitor.Prune();
1182*795d594fSAndroid Build Coastguard Worker   }
1183*795d594fSAndroid Build Coastguard Worker 
GetRemovedClassCount() const1184*795d594fSAndroid Build Coastguard Worker   size_t GetRemovedClassCount() const {
1185*795d594fSAndroid Build Coastguard Worker     return removed_class_count_;
1186*795d594fSAndroid Build Coastguard Worker   }
1187*795d594fSAndroid Build Coastguard Worker 
1188*795d594fSAndroid Build Coastguard Worker  private:
1189*795d594fSAndroid Build Coastguard Worker   ImageWriter* const image_writer_;
1190*795d594fSAndroid Build Coastguard Worker   size_t removed_class_count_;
1191*795d594fSAndroid Build Coastguard Worker };
1192*795d594fSAndroid Build Coastguard Worker 
VisitClassLoaders(ClassLoaderVisitor * visitor)1193*795d594fSAndroid Build Coastguard Worker void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
1194*795d594fSAndroid Build Coastguard Worker   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1195*795d594fSAndroid Build Coastguard Worker   visitor->Visit(nullptr);  // Visit boot class loader.
1196*795d594fSAndroid Build Coastguard Worker   Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
1197*795d594fSAndroid Build Coastguard Worker }
1198*795d594fSAndroid Build Coastguard Worker 
PruneNonImageClasses()1199*795d594fSAndroid Build Coastguard Worker void ImageWriter::PruneNonImageClasses() {
1200*795d594fSAndroid Build Coastguard Worker   Runtime* runtime = Runtime::Current();
1201*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = runtime->GetClassLinker();
1202*795d594fSAndroid Build Coastguard Worker   Thread* self = Thread::Current();
1203*795d594fSAndroid Build Coastguard Worker   ScopedAssertNoThreadSuspension sa(__FUNCTION__);
1204*795d594fSAndroid Build Coastguard Worker 
1205*795d594fSAndroid Build Coastguard Worker   // Prune uses-library dex caches. Only prune the uses-library dex caches since we want to make
1206*795d594fSAndroid Build Coastguard Worker   // sure the other ones don't get unloaded before the OatWriter runs.
1207*795d594fSAndroid Build Coastguard Worker   class_linker->VisitClassTables(
1208*795d594fSAndroid Build Coastguard Worker       [&](ClassTable* table) REQUIRES_SHARED(Locks::mutator_lock_) {
1209*795d594fSAndroid Build Coastguard Worker     table->RemoveStrongRoots(
1210*795d594fSAndroid Build Coastguard Worker         [&](GcRoot<mirror::Object> root) REQUIRES_SHARED(Locks::mutator_lock_) {
1211*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Object> obj = root.Read();
1212*795d594fSAndroid Build Coastguard Worker       if (obj->IsDexCache()) {
1213*795d594fSAndroid Build Coastguard Worker         // Return true if the dex file is not one of the ones in the map.
1214*795d594fSAndroid Build Coastguard Worker         return dex_file_oat_index_map_.find(obj->AsDexCache()->GetDexFile()) ==
1215*795d594fSAndroid Build Coastguard Worker             dex_file_oat_index_map_.end();
1216*795d594fSAndroid Build Coastguard Worker       }
1217*795d594fSAndroid Build Coastguard Worker       // Return false to avoid removing.
1218*795d594fSAndroid Build Coastguard Worker       return false;
1219*795d594fSAndroid Build Coastguard Worker     });
1220*795d594fSAndroid Build Coastguard Worker   });
1221*795d594fSAndroid Build Coastguard Worker 
1222*795d594fSAndroid Build Coastguard Worker   // Remove the undesired classes from the class roots.
1223*795d594fSAndroid Build Coastguard Worker   {
1224*795d594fSAndroid Build Coastguard Worker     PruneClassLoaderClassesVisitor class_loader_visitor(this);
1225*795d594fSAndroid Build Coastguard Worker     VisitClassLoaders(&class_loader_visitor);
1226*795d594fSAndroid Build Coastguard Worker     VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
1227*795d594fSAndroid Build Coastguard Worker   }
1228*795d594fSAndroid Build Coastguard Worker 
1229*795d594fSAndroid Build Coastguard Worker   // Completely clear DexCaches.
1230*795d594fSAndroid Build Coastguard Worker   dchecked_vector<ObjPtr<mirror::DexCache>> dex_caches = FindDexCaches(self);
1231*795d594fSAndroid Build Coastguard Worker   for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1232*795d594fSAndroid Build Coastguard Worker     dex_cache->ResetNativeArrays();
1233*795d594fSAndroid Build Coastguard Worker   }
1234*795d594fSAndroid Build Coastguard Worker 
1235*795d594fSAndroid Build Coastguard Worker   // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1236*795d594fSAndroid Build Coastguard Worker   class_linker->DropFindArrayClassCache();
1237*795d594fSAndroid Build Coastguard Worker 
1238*795d594fSAndroid Build Coastguard Worker   // Clear to save RAM.
1239*795d594fSAndroid Build Coastguard Worker   prune_class_memo_.clear();
1240*795d594fSAndroid Build Coastguard Worker }
1241*795d594fSAndroid Build Coastguard Worker 
FindDexCaches(Thread * self)1242*795d594fSAndroid Build Coastguard Worker dchecked_vector<ObjPtr<mirror::DexCache>> ImageWriter::FindDexCaches(Thread* self) {
1243*795d594fSAndroid Build Coastguard Worker   dchecked_vector<ObjPtr<mirror::DexCache>> dex_caches;
1244*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1245*795d594fSAndroid Build Coastguard Worker   ReaderMutexLock mu2(self, *Locks::dex_lock_);
1246*795d594fSAndroid Build Coastguard Worker   dex_caches.reserve(class_linker->GetDexCachesData().size());
1247*795d594fSAndroid Build Coastguard Worker   for (const auto& entry : class_linker->GetDexCachesData()) {
1248*795d594fSAndroid Build Coastguard Worker     const ClassLinker::DexCacheData& data = entry.second;
1249*795d594fSAndroid Build Coastguard Worker     if (self->IsJWeakCleared(data.weak_root)) {
1250*795d594fSAndroid Build Coastguard Worker       continue;
1251*795d594fSAndroid Build Coastguard Worker     }
1252*795d594fSAndroid Build Coastguard Worker     dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
1253*795d594fSAndroid Build Coastguard Worker   }
1254*795d594fSAndroid Build Coastguard Worker   return dex_caches;
1255*795d594fSAndroid Build Coastguard Worker }
1256*795d594fSAndroid Build Coastguard Worker 
CheckNonImageClassesRemoved()1257*795d594fSAndroid Build Coastguard Worker void ImageWriter::CheckNonImageClassesRemoved() {
1258*795d594fSAndroid Build Coastguard Worker   auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1259*795d594fSAndroid Build Coastguard Worker     if (obj->IsClass() && !IsInBootImage(obj)) {
1260*795d594fSAndroid Build Coastguard Worker       ObjPtr<Class> klass = obj->AsClass();
1261*795d594fSAndroid Build Coastguard Worker       if (!KeepClass(klass)) {
1262*795d594fSAndroid Build Coastguard Worker         DumpImageClasses();
1263*795d594fSAndroid Build Coastguard Worker         CHECK(KeepClass(klass))
1264*795d594fSAndroid Build Coastguard Worker             << Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
1265*795d594fSAndroid Build Coastguard Worker       }
1266*795d594fSAndroid Build Coastguard Worker     }
1267*795d594fSAndroid Build Coastguard Worker   };
1268*795d594fSAndroid Build Coastguard Worker   gc::Heap* heap = Runtime::Current()->GetHeap();
1269*795d594fSAndroid Build Coastguard Worker   heap->VisitObjects(visitor);
1270*795d594fSAndroid Build Coastguard Worker }
1271*795d594fSAndroid Build Coastguard Worker 
PromoteWeakInternsToStrong(Thread * self)1272*795d594fSAndroid Build Coastguard Worker void ImageWriter::PromoteWeakInternsToStrong(Thread* self) {
1273*795d594fSAndroid Build Coastguard Worker   InternTable* intern_table = Runtime::Current()->GetInternTable();
1274*795d594fSAndroid Build Coastguard Worker   MutexLock mu(self, *Locks::intern_table_lock_);
1275*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(intern_table->weak_interns_.tables_.size(), 1u);
1276*795d594fSAndroid Build Coastguard Worker   for (GcRoot<mirror::String>& entry : intern_table->weak_interns_.tables_.front().set_) {
1277*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::String> s = entry.Read<kWithoutReadBarrier>();
1278*795d594fSAndroid Build Coastguard Worker     DCHECK(!IsStronglyInternedString(s));
1279*795d594fSAndroid Build Coastguard Worker     uint32_t hash = static_cast<uint32_t>(s->GetStoredHashCode());
1280*795d594fSAndroid Build Coastguard Worker     intern_table->InsertStrong(s, hash);
1281*795d594fSAndroid Build Coastguard Worker   }
1282*795d594fSAndroid Build Coastguard Worker   intern_table->weak_interns_.tables_.front().set_.clear();
1283*795d594fSAndroid Build Coastguard Worker }
1284*795d594fSAndroid Build Coastguard Worker 
DumpImageClasses()1285*795d594fSAndroid Build Coastguard Worker void ImageWriter::DumpImageClasses() {
1286*795d594fSAndroid Build Coastguard Worker   for (const std::string& image_class : compiler_options_.GetImageClasses()) {
1287*795d594fSAndroid Build Coastguard Worker     LOG(INFO) << " " << image_class;
1288*795d594fSAndroid Build Coastguard Worker   }
1289*795d594fSAndroid Build Coastguard Worker }
1290*795d594fSAndroid Build Coastguard Worker 
CreateImageRoots()1291*795d594fSAndroid Build Coastguard Worker bool ImageWriter::CreateImageRoots() {
1292*795d594fSAndroid Build Coastguard Worker   Runtime* runtime = Runtime::Current();
1293*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = runtime->GetClassLinker();
1294*795d594fSAndroid Build Coastguard Worker   Thread* self = Thread::Current();
1295*795d594fSAndroid Build Coastguard Worker   VariableSizedHandleScope handles(self);
1296*795d594fSAndroid Build Coastguard Worker 
1297*795d594fSAndroid Build Coastguard Worker   // Prepare boot image live objects if we're compiling a boot image or boot image extension.
1298*795d594fSAndroid Build Coastguard Worker   Handle<mirror::ObjectArray<mirror::Object>> boot_image_live_objects;
1299*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsBootImage()) {
1300*795d594fSAndroid Build Coastguard Worker     boot_image_live_objects = handles.NewHandle(AllocateBootImageLiveObjects(self, runtime));
1301*795d594fSAndroid Build Coastguard Worker     if (boot_image_live_objects == nullptr) {
1302*795d594fSAndroid Build Coastguard Worker       return false;
1303*795d594fSAndroid Build Coastguard Worker     }
1304*795d594fSAndroid Build Coastguard Worker   } else if (compiler_options_.IsBootImageExtension()) {
1305*795d594fSAndroid Build Coastguard Worker     gc::Heap* heap = runtime->GetHeap();
1306*795d594fSAndroid Build Coastguard Worker     DCHECK(!heap->GetBootImageSpaces().empty());
1307*795d594fSAndroid Build Coastguard Worker     const ImageHeader& primary_header = heap->GetBootImageSpaces().front()->GetImageHeader();
1308*795d594fSAndroid Build Coastguard Worker     boot_image_live_objects = handles.NewHandle(ObjPtr<ObjectArray<Object>>::DownCast(
1309*795d594fSAndroid Build Coastguard Worker         primary_header.GetImageRoot<kWithReadBarrier>(ImageHeader::kBootImageLiveObjects)));
1310*795d594fSAndroid Build Coastguard Worker     DCHECK(boot_image_live_objects != nullptr);
1311*795d594fSAndroid Build Coastguard Worker   }
1312*795d594fSAndroid Build Coastguard Worker 
1313*795d594fSAndroid Build Coastguard Worker   // Collect dex caches and the sizes of dex cache arrays.
1314*795d594fSAndroid Build Coastguard Worker   struct DexCacheRecord {
1315*795d594fSAndroid Build Coastguard Worker     uint64_t registration_index;
1316*795d594fSAndroid Build Coastguard Worker     Handle<mirror::DexCache> dex_cache;
1317*795d594fSAndroid Build Coastguard Worker     size_t oat_index;
1318*795d594fSAndroid Build Coastguard Worker   };
1319*795d594fSAndroid Build Coastguard Worker   size_t num_oat_files = oat_filenames_.size();
1320*795d594fSAndroid Build Coastguard Worker   dchecked_vector<size_t> dex_cache_counts(num_oat_files, 0u);
1321*795d594fSAndroid Build Coastguard Worker   dchecked_vector<DexCacheRecord> dex_cache_records;
1322*795d594fSAndroid Build Coastguard Worker   dex_cache_records.reserve(dex_file_oat_index_map_.size());
1323*795d594fSAndroid Build Coastguard Worker   {
1324*795d594fSAndroid Build Coastguard Worker     ReaderMutexLock mu(self, *Locks::dex_lock_);
1325*795d594fSAndroid Build Coastguard Worker     // Count number of dex caches not in the boot image.
1326*795d594fSAndroid Build Coastguard Worker     for (const auto& entry : class_linker->GetDexCachesData()) {
1327*795d594fSAndroid Build Coastguard Worker       const ClassLinker::DexCacheData& data = entry.second;
1328*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::DexCache> dex_cache =
1329*795d594fSAndroid Build Coastguard Worker           ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
1330*795d594fSAndroid Build Coastguard Worker       if (dex_cache == nullptr) {
1331*795d594fSAndroid Build Coastguard Worker         continue;
1332*795d594fSAndroid Build Coastguard Worker       }
1333*795d594fSAndroid Build Coastguard Worker       const DexFile* dex_file = dex_cache->GetDexFile();
1334*795d594fSAndroid Build Coastguard Worker       auto it = dex_file_oat_index_map_.find(dex_file);
1335*795d594fSAndroid Build Coastguard Worker       if (it != dex_file_oat_index_map_.end()) {
1336*795d594fSAndroid Build Coastguard Worker         size_t oat_index = it->second;
1337*795d594fSAndroid Build Coastguard Worker         DCHECK(IsImageDexCache(dex_cache));
1338*795d594fSAndroid Build Coastguard Worker         ++dex_cache_counts[oat_index];
1339*795d594fSAndroid Build Coastguard Worker         Handle<mirror::DexCache> h_dex_cache = handles.NewHandle(dex_cache);
1340*795d594fSAndroid Build Coastguard Worker         dex_cache_records.push_back({data.registration_index, h_dex_cache, oat_index});
1341*795d594fSAndroid Build Coastguard Worker       }
1342*795d594fSAndroid Build Coastguard Worker     }
1343*795d594fSAndroid Build Coastguard Worker   }
1344*795d594fSAndroid Build Coastguard Worker 
1345*795d594fSAndroid Build Coastguard Worker   // Allocate dex cache arrays.
1346*795d594fSAndroid Build Coastguard Worker   dchecked_vector<Handle<ObjectArray<Object>>> dex_cache_arrays;
1347*795d594fSAndroid Build Coastguard Worker   dex_cache_arrays.reserve(num_oat_files);
1348*795d594fSAndroid Build Coastguard Worker   for (size_t oat_index = 0; oat_index != num_oat_files; ++oat_index) {
1349*795d594fSAndroid Build Coastguard Worker     ObjPtr<ObjectArray<Object>> dex_caches = ObjectArray<Object>::Alloc(
1350*795d594fSAndroid Build Coastguard Worker         self, GetClassRoot<ObjectArray<Object>>(class_linker), dex_cache_counts[oat_index]);
1351*795d594fSAndroid Build Coastguard Worker     if (dex_caches == nullptr) {
1352*795d594fSAndroid Build Coastguard Worker       return false;
1353*795d594fSAndroid Build Coastguard Worker     }
1354*795d594fSAndroid Build Coastguard Worker     dex_cache_counts[oat_index] = 0u;  // Reset count for filling in dex caches below.
1355*795d594fSAndroid Build Coastguard Worker     dex_cache_arrays.push_back(handles.NewHandle(dex_caches));
1356*795d594fSAndroid Build Coastguard Worker   }
1357*795d594fSAndroid Build Coastguard Worker 
1358*795d594fSAndroid Build Coastguard Worker   // Sort dex caches by registration index to make output deterministic.
1359*795d594fSAndroid Build Coastguard Worker   std::sort(dex_cache_records.begin(),
1360*795d594fSAndroid Build Coastguard Worker             dex_cache_records.end(),
1361*795d594fSAndroid Build Coastguard Worker             [](const DexCacheRecord& lhs, const DexCacheRecord&rhs) {
1362*795d594fSAndroid Build Coastguard Worker               return lhs.registration_index < rhs.registration_index;
1363*795d594fSAndroid Build Coastguard Worker             });
1364*795d594fSAndroid Build Coastguard Worker 
1365*795d594fSAndroid Build Coastguard Worker   // Fill dex cache arrays.
1366*795d594fSAndroid Build Coastguard Worker   for (const DexCacheRecord& record : dex_cache_records) {
1367*795d594fSAndroid Build Coastguard Worker     ObjPtr<ObjectArray<Object>> dex_caches = dex_cache_arrays[record.oat_index].Get();
1368*795d594fSAndroid Build Coastguard Worker     dex_caches->SetWithoutChecks</*kTransactionActive=*/ false>(
1369*795d594fSAndroid Build Coastguard Worker         dex_cache_counts[record.oat_index], record.dex_cache.Get());
1370*795d594fSAndroid Build Coastguard Worker     ++dex_cache_counts[record.oat_index];
1371*795d594fSAndroid Build Coastguard Worker   }
1372*795d594fSAndroid Build Coastguard Worker 
1373*795d594fSAndroid Build Coastguard Worker   // Create image roots with empty dex cache arrays.
1374*795d594fSAndroid Build Coastguard Worker   image_roots_.reserve(num_oat_files);
1375*795d594fSAndroid Build Coastguard Worker   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
1376*795d594fSAndroid Build Coastguard Worker   for (size_t oat_index = 0; oat_index != num_oat_files; ++oat_index) {
1377*795d594fSAndroid Build Coastguard Worker     // Build an Object[] of the roots needed to restore the runtime.
1378*795d594fSAndroid Build Coastguard Worker     int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compiler_options_.IsAppImage());
1379*795d594fSAndroid Build Coastguard Worker     ObjPtr<ObjectArray<Object>> image_roots = ObjectArray<Object>::Alloc(
1380*795d594fSAndroid Build Coastguard Worker         self, GetClassRoot<ObjectArray<Object>>(class_linker), image_roots_size);
1381*795d594fSAndroid Build Coastguard Worker     if (image_roots == nullptr) {
1382*795d594fSAndroid Build Coastguard Worker       return false;
1383*795d594fSAndroid Build Coastguard Worker     }
1384*795d594fSAndroid Build Coastguard Worker     ObjPtr<ObjectArray<Object>> dex_caches = dex_cache_arrays[oat_index].Get();
1385*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(dex_cache_counts[oat_index],
1386*795d594fSAndroid Build Coastguard Worker              dchecked_integral_cast<size_t>(dex_caches->GetLength<kVerifyNone>()))
1387*795d594fSAndroid Build Coastguard Worker         << "The number of non-image dex caches changed.";
1388*795d594fSAndroid Build Coastguard Worker     image_roots->SetWithoutChecks</*kTransactionActive=*/ false>(
1389*795d594fSAndroid Build Coastguard Worker         ImageHeader::kDexCaches, dex_caches);
1390*795d594fSAndroid Build Coastguard Worker     image_roots->SetWithoutChecks</*kTransactionActive=*/ false>(
1391*795d594fSAndroid Build Coastguard Worker         ImageHeader::kClassRoots, class_linker->GetClassRoots());
1392*795d594fSAndroid Build Coastguard Worker     if (!compiler_options_.IsAppImage()) {
1393*795d594fSAndroid Build Coastguard Worker       DCHECK(boot_image_live_objects != nullptr);
1394*795d594fSAndroid Build Coastguard Worker       image_roots->SetWithoutChecks</*kTransactionActive=*/ false>(
1395*795d594fSAndroid Build Coastguard Worker           ImageHeader::kBootImageLiveObjects, boot_image_live_objects.Get());
1396*795d594fSAndroid Build Coastguard Worker     } else {
1397*795d594fSAndroid Build Coastguard Worker       DCHECK(boot_image_live_objects.GetReference() == nullptr);
1398*795d594fSAndroid Build Coastguard Worker       image_roots->SetWithoutChecks</*kTransactionActive=*/ false>(
1399*795d594fSAndroid Build Coastguard Worker           ImageHeader::kAppImageClassLoader, GetAppClassLoader());
1400*795d594fSAndroid Build Coastguard Worker     }
1401*795d594fSAndroid Build Coastguard Worker     for (int32_t i = 0; i != image_roots_size; ++i) {
1402*795d594fSAndroid Build Coastguard Worker       CHECK(image_roots->Get(i) != nullptr);
1403*795d594fSAndroid Build Coastguard Worker     }
1404*795d594fSAndroid Build Coastguard Worker     image_roots_.push_back(vm->AddGlobalRef(self, image_roots));
1405*795d594fSAndroid Build Coastguard Worker   }
1406*795d594fSAndroid Build Coastguard Worker 
1407*795d594fSAndroid Build Coastguard Worker   return true;
1408*795d594fSAndroid Build Coastguard Worker }
1409*795d594fSAndroid Build Coastguard Worker 
RecordNativeRelocations(ObjPtr<mirror::Class> klass,size_t oat_index)1410*795d594fSAndroid Build Coastguard Worker void ImageWriter::RecordNativeRelocations(ObjPtr<mirror::Class> klass, size_t oat_index) {
1411*795d594fSAndroid Build Coastguard Worker   // Visit and assign offsets for fields and field arrays.
1412*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(oat_index, GetOatIndexForClass(klass));
1413*795d594fSAndroid Build Coastguard Worker   DCHECK(!klass->IsErroneous()) << klass->GetStatus();
1414*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsAppImage()) {
1415*795d594fSAndroid Build Coastguard Worker     // Extra consistency check: no boot loader classes should be left!
1416*795d594fSAndroid Build Coastguard Worker     CHECK(!klass->IsBootStrapClassLoaded()) << klass->PrettyClass();
1417*795d594fSAndroid Build Coastguard Worker   }
1418*795d594fSAndroid Build Coastguard Worker   LengthPrefixedArray<ArtField>* fields[] = {
1419*795d594fSAndroid Build Coastguard Worker       klass->GetSFieldsPtr(), klass->GetIFieldsPtr(),
1420*795d594fSAndroid Build Coastguard Worker   };
1421*795d594fSAndroid Build Coastguard Worker   ImageInfo& image_info = GetImageInfo(oat_index);
1422*795d594fSAndroid Build Coastguard Worker   for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1423*795d594fSAndroid Build Coastguard Worker     // Total array length including header.
1424*795d594fSAndroid Build Coastguard Worker     if (cur_fields != nullptr) {
1425*795d594fSAndroid Build Coastguard Worker       // Forward the entire array at once.
1426*795d594fSAndroid Build Coastguard Worker       size_t offset = image_info.GetBinSlotSize(Bin::kArtField);
1427*795d594fSAndroid Build Coastguard Worker       DCHECK(!IsInBootImage(cur_fields));
1428*795d594fSAndroid Build Coastguard Worker       bool inserted =
1429*795d594fSAndroid Build Coastguard Worker           native_object_relocations_.insert(std::make_pair(
1430*795d594fSAndroid Build Coastguard Worker               cur_fields,
1431*795d594fSAndroid Build Coastguard Worker               NativeObjectRelocation{
1432*795d594fSAndroid Build Coastguard Worker                   oat_index, offset, NativeObjectRelocationType::kArtFieldArray
1433*795d594fSAndroid Build Coastguard Worker               })).second;
1434*795d594fSAndroid Build Coastguard Worker       CHECK(inserted) << "Field array " << cur_fields << " already forwarded";
1435*795d594fSAndroid Build Coastguard Worker       const size_t size = LengthPrefixedArray<ArtField>::ComputeSize(cur_fields->size());
1436*795d594fSAndroid Build Coastguard Worker       offset += size;
1437*795d594fSAndroid Build Coastguard Worker       image_info.IncrementBinSlotSize(Bin::kArtField, size);
1438*795d594fSAndroid Build Coastguard Worker       DCHECK_EQ(offset, image_info.GetBinSlotSize(Bin::kArtField));
1439*795d594fSAndroid Build Coastguard Worker     }
1440*795d594fSAndroid Build Coastguard Worker   }
1441*795d594fSAndroid Build Coastguard Worker   // Visit and assign offsets for methods.
1442*795d594fSAndroid Build Coastguard Worker   size_t num_methods = klass->NumMethods();
1443*795d594fSAndroid Build Coastguard Worker   if (num_methods != 0) {
1444*795d594fSAndroid Build Coastguard Worker     bool any_dirty = false;
1445*795d594fSAndroid Build Coastguard Worker     for (auto& m : klass->GetMethods(target_ptr_size_)) {
1446*795d594fSAndroid Build Coastguard Worker       if (WillMethodBeDirty(&m)) {
1447*795d594fSAndroid Build Coastguard Worker         any_dirty = true;
1448*795d594fSAndroid Build Coastguard Worker         break;
1449*795d594fSAndroid Build Coastguard Worker       }
1450*795d594fSAndroid Build Coastguard Worker     }
1451*795d594fSAndroid Build Coastguard Worker     NativeObjectRelocationType type = any_dirty
1452*795d594fSAndroid Build Coastguard Worker         ? NativeObjectRelocationType::kArtMethodDirty
1453*795d594fSAndroid Build Coastguard Worker         : NativeObjectRelocationType::kArtMethodClean;
1454*795d594fSAndroid Build Coastguard Worker     Bin bin_type = BinTypeForNativeRelocationType(type);
1455*795d594fSAndroid Build Coastguard Worker     // Forward the entire array at once, but header first.
1456*795d594fSAndroid Build Coastguard Worker     const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1457*795d594fSAndroid Build Coastguard Worker     const size_t method_size = ArtMethod::Size(target_ptr_size_);
1458*795d594fSAndroid Build Coastguard Worker     const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1459*795d594fSAndroid Build Coastguard Worker                                                                            method_size,
1460*795d594fSAndroid Build Coastguard Worker                                                                            method_alignment);
1461*795d594fSAndroid Build Coastguard Worker     LengthPrefixedArray<ArtMethod>* array = klass->GetMethodsPtr();
1462*795d594fSAndroid Build Coastguard Worker     size_t offset = image_info.GetBinSlotSize(bin_type);
1463*795d594fSAndroid Build Coastguard Worker     DCHECK(!IsInBootImage(array));
1464*795d594fSAndroid Build Coastguard Worker     bool inserted =
1465*795d594fSAndroid Build Coastguard Worker         native_object_relocations_.insert(std::make_pair(
1466*795d594fSAndroid Build Coastguard Worker             array,
1467*795d594fSAndroid Build Coastguard Worker             NativeObjectRelocation{
1468*795d594fSAndroid Build Coastguard Worker                 oat_index,
1469*795d594fSAndroid Build Coastguard Worker                 offset,
1470*795d594fSAndroid Build Coastguard Worker                 any_dirty ? NativeObjectRelocationType::kArtMethodArrayDirty
1471*795d594fSAndroid Build Coastguard Worker                           : NativeObjectRelocationType::kArtMethodArrayClean
1472*795d594fSAndroid Build Coastguard Worker             })).second;
1473*795d594fSAndroid Build Coastguard Worker     CHECK(inserted) << "Method array " << array << " already forwarded";
1474*795d594fSAndroid Build Coastguard Worker     image_info.IncrementBinSlotSize(bin_type, header_size);
1475*795d594fSAndroid Build Coastguard Worker     for (auto& m : klass->GetMethods(target_ptr_size_)) {
1476*795d594fSAndroid Build Coastguard Worker       AssignMethodOffset(&m, type, oat_index);
1477*795d594fSAndroid Build Coastguard Worker     }
1478*795d594fSAndroid Build Coastguard Worker     // Only write JNI stub methods in boot images, but not in boot image extensions and app images.
1479*795d594fSAndroid Build Coastguard Worker     // And the write only happens in non-debuggable since we never use AOT code for debuggable.
1480*795d594fSAndroid Build Coastguard Worker     if (compiler_options_.IsBootImage() &&
1481*795d594fSAndroid Build Coastguard Worker         compiler_options_.IsJniCompilationEnabled() &&
1482*795d594fSAndroid Build Coastguard Worker         !compiler_options_.GetDebuggable()) {
1483*795d594fSAndroid Build Coastguard Worker       for (auto& m : klass->GetMethods(target_ptr_size_)) {
1484*795d594fSAndroid Build Coastguard Worker         if (m.IsNative() && !m.IsIntrinsic()) {
1485*795d594fSAndroid Build Coastguard Worker           AssignJniStubMethodOffset(&m, oat_index);
1486*795d594fSAndroid Build Coastguard Worker         }
1487*795d594fSAndroid Build Coastguard Worker       }
1488*795d594fSAndroid Build Coastguard Worker     }
1489*795d594fSAndroid Build Coastguard Worker     (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
1490*795d594fSAndroid Build Coastguard Worker   }
1491*795d594fSAndroid Build Coastguard Worker   // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1492*795d594fSAndroid Build Coastguard Worker   // live.
1493*795d594fSAndroid Build Coastguard Worker   if (klass->ShouldHaveImt()) {
1494*795d594fSAndroid Build Coastguard Worker     ImTable* imt = klass->GetImt(target_ptr_size_);
1495*795d594fSAndroid Build Coastguard Worker     if (TryAssignImTableOffset(imt, oat_index)) {
1496*795d594fSAndroid Build Coastguard Worker       // Since imt's can be shared only do this the first time to not double count imt method
1497*795d594fSAndroid Build Coastguard Worker       // fixups.
1498*795d594fSAndroid Build Coastguard Worker       for (size_t i = 0; i < ImTable::kSize; ++i) {
1499*795d594fSAndroid Build Coastguard Worker         ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1500*795d594fSAndroid Build Coastguard Worker         DCHECK(imt_method != nullptr);
1501*795d594fSAndroid Build Coastguard Worker         if (imt_method->IsRuntimeMethod() &&
1502*795d594fSAndroid Build Coastguard Worker             !IsInBootImage(imt_method) &&
1503*795d594fSAndroid Build Coastguard Worker             !NativeRelocationAssigned(imt_method)) {
1504*795d594fSAndroid Build Coastguard Worker           AssignMethodOffset(imt_method, NativeObjectRelocationType::kRuntimeMethod, oat_index);
1505*795d594fSAndroid Build Coastguard Worker         }
1506*795d594fSAndroid Build Coastguard Worker       }
1507*795d594fSAndroid Build Coastguard Worker     }
1508*795d594fSAndroid Build Coastguard Worker   }
1509*795d594fSAndroid Build Coastguard Worker }
1510*795d594fSAndroid Build Coastguard Worker 
NativeRelocationAssigned(void * ptr) const1511*795d594fSAndroid Build Coastguard Worker bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1512*795d594fSAndroid Build Coastguard Worker   return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1513*795d594fSAndroid Build Coastguard Worker }
1514*795d594fSAndroid Build Coastguard Worker 
TryAssignImTableOffset(ImTable * imt,size_t oat_index)1515*795d594fSAndroid Build Coastguard Worker bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1516*795d594fSAndroid Build Coastguard Worker   // No offset, or already assigned.
1517*795d594fSAndroid Build Coastguard Worker   if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1518*795d594fSAndroid Build Coastguard Worker     return false;
1519*795d594fSAndroid Build Coastguard Worker   }
1520*795d594fSAndroid Build Coastguard Worker   // If the method is a conflict method we also want to assign the conflict table offset.
1521*795d594fSAndroid Build Coastguard Worker   ImageInfo& image_info = GetImageInfo(oat_index);
1522*795d594fSAndroid Build Coastguard Worker   const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1523*795d594fSAndroid Build Coastguard Worker   native_object_relocations_.insert(std::make_pair(
1524*795d594fSAndroid Build Coastguard Worker       imt,
1525*795d594fSAndroid Build Coastguard Worker       NativeObjectRelocation{
1526*795d594fSAndroid Build Coastguard Worker           oat_index,
1527*795d594fSAndroid Build Coastguard Worker           image_info.GetBinSlotSize(Bin::kImTable),
1528*795d594fSAndroid Build Coastguard Worker           NativeObjectRelocationType::kIMTable
1529*795d594fSAndroid Build Coastguard Worker       }));
1530*795d594fSAndroid Build Coastguard Worker   image_info.IncrementBinSlotSize(Bin::kImTable, size);
1531*795d594fSAndroid Build Coastguard Worker   return true;
1532*795d594fSAndroid Build Coastguard Worker }
1533*795d594fSAndroid Build Coastguard Worker 
TryAssignConflictTableOffset(ImtConflictTable * table,size_t oat_index)1534*795d594fSAndroid Build Coastguard Worker void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1535*795d594fSAndroid Build Coastguard Worker   // No offset, or already assigned.
1536*795d594fSAndroid Build Coastguard Worker   if (table == nullptr || NativeRelocationAssigned(table)) {
1537*795d594fSAndroid Build Coastguard Worker     return;
1538*795d594fSAndroid Build Coastguard Worker   }
1539*795d594fSAndroid Build Coastguard Worker   CHECK(!IsInBootImage(table));
1540*795d594fSAndroid Build Coastguard Worker   // If the method is a conflict method we also want to assign the conflict table offset.
1541*795d594fSAndroid Build Coastguard Worker   ImageInfo& image_info = GetImageInfo(oat_index);
1542*795d594fSAndroid Build Coastguard Worker   const size_t size = table->ComputeSize(target_ptr_size_);
1543*795d594fSAndroid Build Coastguard Worker   native_object_relocations_.insert(std::make_pair(
1544*795d594fSAndroid Build Coastguard Worker       table,
1545*795d594fSAndroid Build Coastguard Worker       NativeObjectRelocation{
1546*795d594fSAndroid Build Coastguard Worker           oat_index,
1547*795d594fSAndroid Build Coastguard Worker           image_info.GetBinSlotSize(Bin::kIMTConflictTable),
1548*795d594fSAndroid Build Coastguard Worker           NativeObjectRelocationType::kIMTConflictTable
1549*795d594fSAndroid Build Coastguard Worker       }));
1550*795d594fSAndroid Build Coastguard Worker   image_info.IncrementBinSlotSize(Bin::kIMTConflictTable, size);
1551*795d594fSAndroid Build Coastguard Worker }
1552*795d594fSAndroid Build Coastguard Worker 
AssignMethodOffset(ArtMethod * method,NativeObjectRelocationType type,size_t oat_index)1553*795d594fSAndroid Build Coastguard Worker void ImageWriter::AssignMethodOffset(ArtMethod* method,
1554*795d594fSAndroid Build Coastguard Worker                                      NativeObjectRelocationType type,
1555*795d594fSAndroid Build Coastguard Worker                                      size_t oat_index) {
1556*795d594fSAndroid Build Coastguard Worker   DCHECK(!IsInBootImage(method));
1557*795d594fSAndroid Build Coastguard Worker   CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
1558*795d594fSAndroid Build Coastguard Worker       << ArtMethod::PrettyMethod(method);
1559*795d594fSAndroid Build Coastguard Worker   if (method->IsRuntimeMethod()) {
1560*795d594fSAndroid Build Coastguard Worker     TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1561*795d594fSAndroid Build Coastguard Worker   }
1562*795d594fSAndroid Build Coastguard Worker   ImageInfo& image_info = GetImageInfo(oat_index);
1563*795d594fSAndroid Build Coastguard Worker   Bin bin_type = BinTypeForNativeRelocationType(type);
1564*795d594fSAndroid Build Coastguard Worker   size_t offset = image_info.GetBinSlotSize(bin_type);
1565*795d594fSAndroid Build Coastguard Worker   native_object_relocations_.insert(
1566*795d594fSAndroid Build Coastguard Worker       std::make_pair(method, NativeObjectRelocation{oat_index, offset, type}));
1567*795d594fSAndroid Build Coastguard Worker   image_info.IncrementBinSlotSize(bin_type, ArtMethod::Size(target_ptr_size_));
1568*795d594fSAndroid Build Coastguard Worker }
1569*795d594fSAndroid Build Coastguard Worker 
AssignJniStubMethodOffset(ArtMethod * method,size_t oat_index)1570*795d594fSAndroid Build Coastguard Worker void ImageWriter::AssignJniStubMethodOffset(ArtMethod* method, size_t oat_index) {
1571*795d594fSAndroid Build Coastguard Worker   CHECK(method->IsNative());
1572*795d594fSAndroid Build Coastguard Worker   auto it = jni_stub_map_.find(JniStubKey(method));
1573*795d594fSAndroid Build Coastguard Worker   if (it == jni_stub_map_.end()) {
1574*795d594fSAndroid Build Coastguard Worker     ImageInfo& image_info = GetImageInfo(oat_index);
1575*795d594fSAndroid Build Coastguard Worker     constexpr Bin bin_type = Bin::kJniStubMethod;
1576*795d594fSAndroid Build Coastguard Worker     size_t offset = image_info.GetBinSlotSize(bin_type);
1577*795d594fSAndroid Build Coastguard Worker     jni_stub_map_.Put(std::make_pair(
1578*795d594fSAndroid Build Coastguard Worker         JniStubKey(method),
1579*795d594fSAndroid Build Coastguard Worker         std::make_pair(method, JniStubMethodRelocation{oat_index, offset})));
1580*795d594fSAndroid Build Coastguard Worker     image_info.IncrementBinSlotSize(bin_type, static_cast<size_t>(target_ptr_size_));
1581*795d594fSAndroid Build Coastguard Worker   }
1582*795d594fSAndroid Build Coastguard Worker }
1583*795d594fSAndroid Build Coastguard Worker 
1584*795d594fSAndroid Build Coastguard Worker class ImageWriter::LayoutHelper {
1585*795d594fSAndroid Build Coastguard Worker  public:
LayoutHelper(ImageWriter * image_writer)1586*795d594fSAndroid Build Coastguard Worker   explicit LayoutHelper(ImageWriter* image_writer)
1587*795d594fSAndroid Build Coastguard Worker       : image_writer_(image_writer) {
1588*795d594fSAndroid Build Coastguard Worker     bin_objects_.resize(image_writer_->image_infos_.size());
1589*795d594fSAndroid Build Coastguard Worker     for (auto& inner : bin_objects_) {
1590*795d594fSAndroid Build Coastguard Worker       inner.resize(enum_cast<size_t>(Bin::kMirrorCount));
1591*795d594fSAndroid Build Coastguard Worker     }
1592*795d594fSAndroid Build Coastguard Worker   }
1593*795d594fSAndroid Build Coastguard Worker 
1594*795d594fSAndroid Build Coastguard Worker   void ProcessDexFileObjects(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1595*795d594fSAndroid Build Coastguard Worker   void ProcessRoots(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1596*795d594fSAndroid Build Coastguard Worker   void FinalizeInternTables() REQUIRES_SHARED(Locks::mutator_lock_);
1597*795d594fSAndroid Build Coastguard Worker   // Recreate dirty object offsets (kKnownDirty bin) with objects sorted by sort_key.
1598*795d594fSAndroid Build Coastguard Worker   void SortDirtyObjects(const HashMap<mirror::Object*, uint32_t>& dirty_objects, size_t oat_index)
1599*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_);
1600*795d594fSAndroid Build Coastguard Worker 
1601*795d594fSAndroid Build Coastguard Worker   void VerifyImageBinSlotsAssigned() REQUIRES_SHARED(Locks::mutator_lock_);
1602*795d594fSAndroid Build Coastguard Worker 
1603*795d594fSAndroid Build Coastguard Worker   void FinalizeBinSlotOffsets() REQUIRES_SHARED(Locks::mutator_lock_);
1604*795d594fSAndroid Build Coastguard Worker 
1605*795d594fSAndroid Build Coastguard Worker   /*
1606*795d594fSAndroid Build Coastguard Worker    * Collects the string reference info necessary for loading app images.
1607*795d594fSAndroid Build Coastguard Worker    *
1608*795d594fSAndroid Build Coastguard Worker    * Because AppImages may contain interned strings that must be deduplicated
1609*795d594fSAndroid Build Coastguard Worker    * with previously interned strings when loading the app image, we need to
1610*795d594fSAndroid Build Coastguard Worker    * visit references to these strings and update them to point to the correct
1611*795d594fSAndroid Build Coastguard Worker    * string. To speed up the visiting of references at load time we include
1612*795d594fSAndroid Build Coastguard Worker    * a list of offsets to string references in the AppImage.
1613*795d594fSAndroid Build Coastguard Worker    */
1614*795d594fSAndroid Build Coastguard Worker   void CollectStringReferenceInfo() REQUIRES_SHARED(Locks::mutator_lock_);
1615*795d594fSAndroid Build Coastguard Worker 
1616*795d594fSAndroid Build Coastguard Worker  private:
1617*795d594fSAndroid Build Coastguard Worker   class CollectClassesVisitor;
1618*795d594fSAndroid Build Coastguard Worker   class CollectStringReferenceVisitor;
1619*795d594fSAndroid Build Coastguard Worker   class VisitReferencesVisitor;
1620*795d594fSAndroid Build Coastguard Worker 
1621*795d594fSAndroid Build Coastguard Worker   void ProcessInterns(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1622*795d594fSAndroid Build Coastguard Worker   void ProcessWorkQueue() REQUIRES_SHARED(Locks::mutator_lock_);
1623*795d594fSAndroid Build Coastguard Worker 
1624*795d594fSAndroid Build Coastguard Worker   using WorkQueue = std::deque<std::pair<ObjPtr<mirror::Object>, size_t>>;
1625*795d594fSAndroid Build Coastguard Worker 
1626*795d594fSAndroid Build Coastguard Worker   void VisitReferences(ObjPtr<mirror::Object> obj, size_t oat_index)
1627*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_);
1628*795d594fSAndroid Build Coastguard Worker   bool TryAssignBinSlot(ObjPtr<mirror::Object> obj, size_t oat_index)
1629*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_);
1630*795d594fSAndroid Build Coastguard Worker   ImageWriter::Bin AssignImageBinSlot(ObjPtr<mirror::Object> object, size_t oat_index)
1631*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_);
1632*795d594fSAndroid Build Coastguard Worker   void AssignImageBinSlot(ObjPtr<mirror::Object> object, size_t oat_index, Bin bin)
1633*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_);
1634*795d594fSAndroid Build Coastguard Worker 
1635*795d594fSAndroid Build Coastguard Worker   ImageWriter* const image_writer_;
1636*795d594fSAndroid Build Coastguard Worker 
1637*795d594fSAndroid Build Coastguard Worker   // Work list of <object, oat_index> for objects. Everything in the queue must already be
1638*795d594fSAndroid Build Coastguard Worker   // assigned a bin slot.
1639*795d594fSAndroid Build Coastguard Worker   WorkQueue work_queue_;
1640*795d594fSAndroid Build Coastguard Worker 
1641*795d594fSAndroid Build Coastguard Worker   // Objects for individual bins. Indexed by `oat_index` and `bin`.
1642*795d594fSAndroid Build Coastguard Worker   // Cannot use ObjPtr<> because of invalidation in Heap::VisitObjects().
1643*795d594fSAndroid Build Coastguard Worker   dchecked_vector<dchecked_vector<dchecked_vector<mirror::Object*>>> bin_objects_;
1644*795d594fSAndroid Build Coastguard Worker 
1645*795d594fSAndroid Build Coastguard Worker   // Interns that do not have a corresponding StringId in any of the input dex files.
1646*795d594fSAndroid Build Coastguard Worker   // These shall be assigned to individual images based on the `oat_index` that we
1647*795d594fSAndroid Build Coastguard Worker   // see as we visit them during the work queue processing.
1648*795d594fSAndroid Build Coastguard Worker   dchecked_vector<mirror::String*> non_dex_file_interns_;
1649*795d594fSAndroid Build Coastguard Worker };
1650*795d594fSAndroid Build Coastguard Worker 
1651*795d594fSAndroid Build Coastguard Worker class ImageWriter::LayoutHelper::CollectClassesVisitor {
1652*795d594fSAndroid Build Coastguard Worker  public:
CollectClassesVisitor(ImageWriter * image_writer)1653*795d594fSAndroid Build Coastguard Worker   explicit CollectClassesVisitor(ImageWriter* image_writer)
1654*795d594fSAndroid Build Coastguard Worker       : image_writer_(image_writer),
1655*795d594fSAndroid Build Coastguard Worker         dex_files_(image_writer_->compiler_options_.GetDexFilesForOatFile()) {}
1656*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass)1657*795d594fSAndroid Build Coastguard Worker   bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1658*795d594fSAndroid Build Coastguard Worker     if (!image_writer_->IsInBootImage(klass.Ptr())) {
1659*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Class> component_type = klass;
1660*795d594fSAndroid Build Coastguard Worker       size_t dimension = 0u;
1661*795d594fSAndroid Build Coastguard Worker       while (component_type->IsArrayClass<kVerifyNone>()) {
1662*795d594fSAndroid Build Coastguard Worker         ++dimension;
1663*795d594fSAndroid Build Coastguard Worker         component_type = component_type->GetComponentType<kVerifyNone, kWithoutReadBarrier>();
1664*795d594fSAndroid Build Coastguard Worker       }
1665*795d594fSAndroid Build Coastguard Worker       DCHECK(!component_type->IsProxyClass());
1666*795d594fSAndroid Build Coastguard Worker       size_t dex_file_index;
1667*795d594fSAndroid Build Coastguard Worker       uint32_t class_def_index = 0u;
1668*795d594fSAndroid Build Coastguard Worker       if (UNLIKELY(component_type->IsPrimitive())) {
1669*795d594fSAndroid Build Coastguard Worker         DCHECK(image_writer_->compiler_options_.IsBootImage());
1670*795d594fSAndroid Build Coastguard Worker         dex_file_index = 0u;
1671*795d594fSAndroid Build Coastguard Worker         class_def_index = enum_cast<uint32_t>(component_type->GetPrimitiveType());
1672*795d594fSAndroid Build Coastguard Worker       } else {
1673*795d594fSAndroid Build Coastguard Worker         auto it = std::find(dex_files_.begin(), dex_files_.end(), &component_type->GetDexFile());
1674*795d594fSAndroid Build Coastguard Worker         DCHECK(it != dex_files_.end()) << klass->PrettyDescriptor();
1675*795d594fSAndroid Build Coastguard Worker         dex_file_index = std::distance(dex_files_.begin(), it) + 1u;  // 0 is for primitive types.
1676*795d594fSAndroid Build Coastguard Worker         class_def_index = component_type->GetDexClassDefIndex();
1677*795d594fSAndroid Build Coastguard Worker       }
1678*795d594fSAndroid Build Coastguard Worker       klasses_.push_back({klass, dex_file_index, class_def_index, dimension});
1679*795d594fSAndroid Build Coastguard Worker     }
1680*795d594fSAndroid Build Coastguard Worker     return true;
1681*795d594fSAndroid Build Coastguard Worker   }
1682*795d594fSAndroid Build Coastguard Worker 
ProcessCollectedClasses(Thread * self)1683*795d594fSAndroid Build Coastguard Worker   WorkQueue ProcessCollectedClasses(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) {
1684*795d594fSAndroid Build Coastguard Worker     std::sort(klasses_.begin(), klasses_.end());
1685*795d594fSAndroid Build Coastguard Worker 
1686*795d594fSAndroid Build Coastguard Worker     ImageWriter* image_writer = image_writer_;
1687*795d594fSAndroid Build Coastguard Worker     WorkQueue work_queue;
1688*795d594fSAndroid Build Coastguard Worker     size_t last_dex_file_index = static_cast<size_t>(-1);
1689*795d594fSAndroid Build Coastguard Worker     size_t last_oat_index = static_cast<size_t>(-1);
1690*795d594fSAndroid Build Coastguard Worker     for (const ClassEntry& entry : klasses_) {
1691*795d594fSAndroid Build Coastguard Worker       if (last_dex_file_index != entry.dex_file_index) {
1692*795d594fSAndroid Build Coastguard Worker         if (UNLIKELY(entry.dex_file_index == 0u)) {
1693*795d594fSAndroid Build Coastguard Worker           last_oat_index = GetDefaultOatIndex();  // Primitive type.
1694*795d594fSAndroid Build Coastguard Worker         } else {
1695*795d594fSAndroid Build Coastguard Worker           uint32_t dex_file_index = entry.dex_file_index - 1u;  // 0 is for primitive types.
1696*795d594fSAndroid Build Coastguard Worker           last_oat_index = image_writer->GetOatIndexForDexFile(dex_files_[dex_file_index]);
1697*795d594fSAndroid Build Coastguard Worker         }
1698*795d594fSAndroid Build Coastguard Worker         last_dex_file_index = entry.dex_file_index;
1699*795d594fSAndroid Build Coastguard Worker       }
1700*795d594fSAndroid Build Coastguard Worker       // Count the number of classes for class tables.
1701*795d594fSAndroid Build Coastguard Worker       image_writer->image_infos_[last_oat_index].class_table_size_ += 1u;
1702*795d594fSAndroid Build Coastguard Worker       work_queue.emplace_back(entry.klass, last_oat_index);
1703*795d594fSAndroid Build Coastguard Worker     }
1704*795d594fSAndroid Build Coastguard Worker     klasses_.clear();
1705*795d594fSAndroid Build Coastguard Worker 
1706*795d594fSAndroid Build Coastguard Worker     // Prepare image class tables.
1707*795d594fSAndroid Build Coastguard Worker     dchecked_vector<mirror::Class*> boot_image_classes;
1708*795d594fSAndroid Build Coastguard Worker     if (image_writer->compiler_options_.IsAppImage()) {
1709*795d594fSAndroid Build Coastguard Worker       DCHECK_EQ(image_writer->image_infos_.size(), 1u);
1710*795d594fSAndroid Build Coastguard Worker       ImageInfo& image_info = image_writer->image_infos_[0];
1711*795d594fSAndroid Build Coastguard Worker       // Log the non-boot image class count for app image for debugging purposes.
1712*795d594fSAndroid Build Coastguard Worker       VLOG(compiler) << "Dex2Oat:AppImage:classCount = " << image_info.class_table_size_;
1713*795d594fSAndroid Build Coastguard Worker       // Collect boot image classes referenced by app class loader's class table.
1714*795d594fSAndroid Build Coastguard Worker       JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
1715*795d594fSAndroid Build Coastguard Worker       auto app_class_loader = DecodeGlobalWithoutRB<mirror::ClassLoader>(
1716*795d594fSAndroid Build Coastguard Worker           vm, image_writer->app_class_loader_);
1717*795d594fSAndroid Build Coastguard Worker       ClassTable* app_class_table = app_class_loader->GetClassTable();
1718*795d594fSAndroid Build Coastguard Worker       if (app_class_table != nullptr) {
1719*795d594fSAndroid Build Coastguard Worker         ReaderMutexLock lock(self, app_class_table->lock_);
1720*795d594fSAndroid Build Coastguard Worker         DCHECK_EQ(app_class_table->classes_.size(), 1u);
1721*795d594fSAndroid Build Coastguard Worker         const ClassTable::ClassSet& app_class_set = app_class_table->classes_[0];
1722*795d594fSAndroid Build Coastguard Worker         DCHECK_GE(app_class_set.size(), image_info.class_table_size_);
1723*795d594fSAndroid Build Coastguard Worker         boot_image_classes.reserve(app_class_set.size() - image_info.class_table_size_);
1724*795d594fSAndroid Build Coastguard Worker         for (const ClassTable::TableSlot& slot : app_class_set) {
1725*795d594fSAndroid Build Coastguard Worker           mirror::Class* klass = slot.Read<kWithoutReadBarrier>().Ptr();
1726*795d594fSAndroid Build Coastguard Worker           if (image_writer->IsInBootImage(klass)) {
1727*795d594fSAndroid Build Coastguard Worker             boot_image_classes.push_back(klass);
1728*795d594fSAndroid Build Coastguard Worker           }
1729*795d594fSAndroid Build Coastguard Worker         }
1730*795d594fSAndroid Build Coastguard Worker         DCHECK_EQ(app_class_set.size() - image_info.class_table_size_, boot_image_classes.size());
1731*795d594fSAndroid Build Coastguard Worker         // Increase the app class table size to include referenced boot image classes.
1732*795d594fSAndroid Build Coastguard Worker         image_info.class_table_size_ = app_class_set.size();
1733*795d594fSAndroid Build Coastguard Worker       }
1734*795d594fSAndroid Build Coastguard Worker     }
1735*795d594fSAndroid Build Coastguard Worker     for (ImageInfo& image_info : image_writer->image_infos_) {
1736*795d594fSAndroid Build Coastguard Worker       if (image_info.class_table_size_ != 0u) {
1737*795d594fSAndroid Build Coastguard Worker         // Make sure the class table shall be full by allocating a buffer of the right size.
1738*795d594fSAndroid Build Coastguard Worker         size_t buffer_size = static_cast<size_t>(
1739*795d594fSAndroid Build Coastguard Worker             ceil(image_info.class_table_size_ / kImageClassTableMaxLoadFactor));
1740*795d594fSAndroid Build Coastguard Worker         image_info.class_table_buffer_.reset(new ClassTable::TableSlot[buffer_size]);
1741*795d594fSAndroid Build Coastguard Worker         DCHECK(image_info.class_table_buffer_ != nullptr);
1742*795d594fSAndroid Build Coastguard Worker         image_info.class_table_.emplace(kImageClassTableMinLoadFactor,
1743*795d594fSAndroid Build Coastguard Worker                                         kImageClassTableMaxLoadFactor,
1744*795d594fSAndroid Build Coastguard Worker                                         image_info.class_table_buffer_.get(),
1745*795d594fSAndroid Build Coastguard Worker                                         buffer_size);
1746*795d594fSAndroid Build Coastguard Worker       }
1747*795d594fSAndroid Build Coastguard Worker     }
1748*795d594fSAndroid Build Coastguard Worker     for (const auto& pair : work_queue) {
1749*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Class> klass = pair.first->AsClass();
1750*795d594fSAndroid Build Coastguard Worker       size_t oat_index = pair.second;
1751*795d594fSAndroid Build Coastguard Worker       DCHECK(image_writer->image_infos_[oat_index].class_table_.has_value());
1752*795d594fSAndroid Build Coastguard Worker       ClassTable::ClassSet& class_table = *image_writer->image_infos_[oat_index].class_table_;
1753*795d594fSAndroid Build Coastguard Worker       uint32_t hash = klass->DescriptorHash();
1754*795d594fSAndroid Build Coastguard Worker       bool inserted = class_table.InsertWithHash(ClassTable::TableSlot(klass, hash), hash).second;
1755*795d594fSAndroid Build Coastguard Worker       DCHECK(inserted) << "Class " << klass->PrettyDescriptor()
1756*795d594fSAndroid Build Coastguard Worker           << " (" << klass.Ptr() << ") already inserted";
1757*795d594fSAndroid Build Coastguard Worker     }
1758*795d594fSAndroid Build Coastguard Worker     if (image_writer->compiler_options_.IsAppImage()) {
1759*795d594fSAndroid Build Coastguard Worker       DCHECK_EQ(image_writer->image_infos_.size(), 1u);
1760*795d594fSAndroid Build Coastguard Worker       ImageInfo& image_info = image_writer->image_infos_[0];
1761*795d594fSAndroid Build Coastguard Worker       if (image_info.class_table_size_ != 0u) {
1762*795d594fSAndroid Build Coastguard Worker         // Insert boot image class references to the app class table.
1763*795d594fSAndroid Build Coastguard Worker         // The order of insertion into the app class loader's ClassTable is non-deterministic,
1764*795d594fSAndroid Build Coastguard Worker         // so sort the boot image classes by the boot image address to get deterministic table.
1765*795d594fSAndroid Build Coastguard Worker         std::sort(boot_image_classes.begin(), boot_image_classes.end());
1766*795d594fSAndroid Build Coastguard Worker         DCHECK(image_info.class_table_.has_value());
1767*795d594fSAndroid Build Coastguard Worker         ClassTable::ClassSet& table = *image_info.class_table_;
1768*795d594fSAndroid Build Coastguard Worker         for (mirror::Class* klass : boot_image_classes) {
1769*795d594fSAndroid Build Coastguard Worker           uint32_t hash = klass->DescriptorHash();
1770*795d594fSAndroid Build Coastguard Worker           bool inserted = table.InsertWithHash(ClassTable::TableSlot(klass, hash), hash).second;
1771*795d594fSAndroid Build Coastguard Worker           DCHECK(inserted) << "Boot image class " << klass->PrettyDescriptor()
1772*795d594fSAndroid Build Coastguard Worker               << " (" << klass << ") already inserted";
1773*795d594fSAndroid Build Coastguard Worker         }
1774*795d594fSAndroid Build Coastguard Worker         DCHECK_EQ(table.size(), image_info.class_table_size_);
1775*795d594fSAndroid Build Coastguard Worker       }
1776*795d594fSAndroid Build Coastguard Worker     }
1777*795d594fSAndroid Build Coastguard Worker     for (ImageInfo& image_info : image_writer->image_infos_) {
1778*795d594fSAndroid Build Coastguard Worker       DCHECK_EQ(image_info.class_table_bytes_, 0u);
1779*795d594fSAndroid Build Coastguard Worker       if (image_info.class_table_size_ != 0u) {
1780*795d594fSAndroid Build Coastguard Worker         DCHECK(image_info.class_table_.has_value());
1781*795d594fSAndroid Build Coastguard Worker         DCHECK_EQ(image_info.class_table_->size(), image_info.class_table_size_);
1782*795d594fSAndroid Build Coastguard Worker         image_info.class_table_bytes_ = image_info.class_table_->WriteToMemory(nullptr);
1783*795d594fSAndroid Build Coastguard Worker         DCHECK_NE(image_info.class_table_bytes_, 0u);
1784*795d594fSAndroid Build Coastguard Worker       } else {
1785*795d594fSAndroid Build Coastguard Worker         DCHECK(!image_info.class_table_.has_value());
1786*795d594fSAndroid Build Coastguard Worker       }
1787*795d594fSAndroid Build Coastguard Worker     }
1788*795d594fSAndroid Build Coastguard Worker 
1789*795d594fSAndroid Build Coastguard Worker     return work_queue;
1790*795d594fSAndroid Build Coastguard Worker   }
1791*795d594fSAndroid Build Coastguard Worker 
1792*795d594fSAndroid Build Coastguard Worker  private:
1793*795d594fSAndroid Build Coastguard Worker   struct ClassEntry {
1794*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Class> klass;
1795*795d594fSAndroid Build Coastguard Worker     // We shall sort classes by dex file, class def index and array dimension.
1796*795d594fSAndroid Build Coastguard Worker     size_t dex_file_index;
1797*795d594fSAndroid Build Coastguard Worker     uint32_t class_def_index;
1798*795d594fSAndroid Build Coastguard Worker     size_t dimension;
1799*795d594fSAndroid Build Coastguard Worker 
operator <art::linker::ImageWriter::LayoutHelper::CollectClassesVisitor::ClassEntry1800*795d594fSAndroid Build Coastguard Worker     bool operator<(const ClassEntry& other) const {
1801*795d594fSAndroid Build Coastguard Worker       return std::tie(dex_file_index, class_def_index, dimension) <
1802*795d594fSAndroid Build Coastguard Worker              std::tie(other.dex_file_index, other.class_def_index, other.dimension);
1803*795d594fSAndroid Build Coastguard Worker     }
1804*795d594fSAndroid Build Coastguard Worker   };
1805*795d594fSAndroid Build Coastguard Worker 
1806*795d594fSAndroid Build Coastguard Worker   ImageWriter* const image_writer_;
1807*795d594fSAndroid Build Coastguard Worker   const ArrayRef<const DexFile* const> dex_files_;
1808*795d594fSAndroid Build Coastguard Worker   std::deque<ClassEntry> klasses_;
1809*795d594fSAndroid Build Coastguard Worker };
1810*795d594fSAndroid Build Coastguard Worker 
1811*795d594fSAndroid Build Coastguard Worker class ImageWriter::LayoutHelper::CollectStringReferenceVisitor {
1812*795d594fSAndroid Build Coastguard Worker  public:
CollectStringReferenceVisitor(const ImageWriter * image_writer,size_t oat_index,dchecked_vector<AppImageReferenceOffsetInfo> * const string_reference_offsets,ObjPtr<mirror::Object> current_obj)1813*795d594fSAndroid Build Coastguard Worker   explicit CollectStringReferenceVisitor(
1814*795d594fSAndroid Build Coastguard Worker       const ImageWriter* image_writer,
1815*795d594fSAndroid Build Coastguard Worker       size_t oat_index,
1816*795d594fSAndroid Build Coastguard Worker       dchecked_vector<AppImageReferenceOffsetInfo>* const string_reference_offsets,
1817*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Object> current_obj)
1818*795d594fSAndroid Build Coastguard Worker       : image_writer_(image_writer),
1819*795d594fSAndroid Build Coastguard Worker         oat_index_(oat_index),
1820*795d594fSAndroid Build Coastguard Worker         string_reference_offsets_(string_reference_offsets),
1821*795d594fSAndroid Build Coastguard Worker         current_obj_(current_obj) {}
1822*795d594fSAndroid Build Coastguard Worker 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1823*795d594fSAndroid Build Coastguard Worker   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1824*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
1825*795d594fSAndroid Build Coastguard Worker     if (!root->IsNull()) {
1826*795d594fSAndroid Build Coastguard Worker       VisitRoot(root);
1827*795d594fSAndroid Build Coastguard Worker     }
1828*795d594fSAndroid Build Coastguard Worker   }
1829*795d594fSAndroid Build Coastguard Worker 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1830*795d594fSAndroid Build Coastguard Worker   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1831*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_)  {
1832*795d594fSAndroid Build Coastguard Worker     // Only dex caches have native String roots. These are collected separately.
1833*795d594fSAndroid Build Coastguard Worker     DCHECK((current_obj_->IsDexCache<kVerifyNone, kWithoutReadBarrier>()) ||
1834*795d594fSAndroid Build Coastguard Worker            !image_writer_->IsInternedAppImageStringReference(root->AsMirrorPtr()))
1835*795d594fSAndroid Build Coastguard Worker         << mirror::Object::PrettyTypeOf(current_obj_);
1836*795d594fSAndroid Build Coastguard Worker   }
1837*795d594fSAndroid Build Coastguard Worker 
1838*795d594fSAndroid Build Coastguard Worker   // Collects info for managed fields that reference managed Strings.
operator ()(ObjPtr<mirror::Object> obj,MemberOffset member_offset,bool is_static) const1839*795d594fSAndroid Build Coastguard Worker   void operator()(ObjPtr<mirror::Object> obj,
1840*795d594fSAndroid Build Coastguard Worker                   MemberOffset member_offset,
1841*795d594fSAndroid Build Coastguard Worker                   [[maybe_unused]] bool is_static) const REQUIRES_SHARED(Locks::mutator_lock_) {
1842*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Object> referred_obj =
1843*795d594fSAndroid Build Coastguard Worker         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(member_offset);
1844*795d594fSAndroid Build Coastguard Worker 
1845*795d594fSAndroid Build Coastguard Worker     if (image_writer_->IsInternedAppImageStringReference(referred_obj)) {
1846*795d594fSAndroid Build Coastguard Worker       size_t base_offset = image_writer_->GetImageOffset(current_obj_.Ptr(), oat_index_);
1847*795d594fSAndroid Build Coastguard Worker       string_reference_offsets_->emplace_back(base_offset, member_offset.Uint32Value());
1848*795d594fSAndroid Build Coastguard Worker     }
1849*795d594fSAndroid Build Coastguard Worker   }
1850*795d594fSAndroid Build Coastguard Worker 
1851*795d594fSAndroid Build Coastguard Worker   ALWAYS_INLINE
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1852*795d594fSAndroid Build Coastguard Worker   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
1853*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
1854*795d594fSAndroid Build Coastguard Worker     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
1855*795d594fSAndroid Build Coastguard Worker   }
1856*795d594fSAndroid Build Coastguard Worker 
1857*795d594fSAndroid Build Coastguard Worker  private:
1858*795d594fSAndroid Build Coastguard Worker   const ImageWriter* const image_writer_;
1859*795d594fSAndroid Build Coastguard Worker   const size_t oat_index_;
1860*795d594fSAndroid Build Coastguard Worker   dchecked_vector<AppImageReferenceOffsetInfo>* const string_reference_offsets_;
1861*795d594fSAndroid Build Coastguard Worker   const ObjPtr<mirror::Object> current_obj_;
1862*795d594fSAndroid Build Coastguard Worker };
1863*795d594fSAndroid Build Coastguard Worker 
1864*795d594fSAndroid Build Coastguard Worker class ImageWriter::LayoutHelper::VisitReferencesVisitor {
1865*795d594fSAndroid Build Coastguard Worker  public:
VisitReferencesVisitor(LayoutHelper * helper,size_t oat_index)1866*795d594fSAndroid Build Coastguard Worker   VisitReferencesVisitor(LayoutHelper* helper, size_t oat_index)
1867*795d594fSAndroid Build Coastguard Worker       : helper_(helper), oat_index_(oat_index) {}
1868*795d594fSAndroid Build Coastguard Worker 
1869*795d594fSAndroid Build Coastguard Worker   // We do not visit native roots. These are handled with other logic.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1870*795d594fSAndroid Build Coastguard Worker   void VisitRootIfNonNull(
1871*795d594fSAndroid Build Coastguard Worker       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {
1872*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "UNREACHABLE";
1873*795d594fSAndroid Build Coastguard Worker   }
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1874*795d594fSAndroid Build Coastguard Worker   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {
1875*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "UNREACHABLE";
1876*795d594fSAndroid Build Coastguard Worker   }
1877*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static) const1878*795d594fSAndroid Build Coastguard Worker   ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1879*795d594fSAndroid Build Coastguard Worker                                 MemberOffset offset,
1880*795d594fSAndroid Build Coastguard Worker                                 [[maybe_unused]] bool is_static) const
1881*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
1882*795d594fSAndroid Build Coastguard Worker     mirror::Object* ref =
1883*795d594fSAndroid Build Coastguard Worker         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1884*795d594fSAndroid Build Coastguard Worker     VisitReference(ref);
1885*795d594fSAndroid Build Coastguard Worker   }
1886*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1887*795d594fSAndroid Build Coastguard Worker   ALWAYS_INLINE void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass,
1888*795d594fSAndroid Build Coastguard Worker                                 ObjPtr<mirror::Reference> ref) const
1889*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
1890*795d594fSAndroid Build Coastguard Worker     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
1891*795d594fSAndroid Build Coastguard Worker   }
1892*795d594fSAndroid Build Coastguard Worker 
1893*795d594fSAndroid Build Coastguard Worker  private:
VisitReference(mirror::Object * ref) const1894*795d594fSAndroid Build Coastguard Worker   void VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1895*795d594fSAndroid Build Coastguard Worker     if (helper_->TryAssignBinSlot(ref, oat_index_)) {
1896*795d594fSAndroid Build Coastguard Worker       // Remember how many objects we're adding at the front of the queue as we want
1897*795d594fSAndroid Build Coastguard Worker       // to reverse that range to process these references in the order of addition.
1898*795d594fSAndroid Build Coastguard Worker       helper_->work_queue_.emplace_front(ref, oat_index_);
1899*795d594fSAndroid Build Coastguard Worker     }
1900*795d594fSAndroid Build Coastguard Worker     if (ClassLinker::kAppImageMayContainStrings &&
1901*795d594fSAndroid Build Coastguard Worker         helper_->image_writer_->compiler_options_.IsAppImage() &&
1902*795d594fSAndroid Build Coastguard Worker         helper_->image_writer_->IsInternedAppImageStringReference(ref)) {
1903*795d594fSAndroid Build Coastguard Worker       helper_->image_writer_->image_infos_[oat_index_].num_string_references_ += 1u;
1904*795d594fSAndroid Build Coastguard Worker     }
1905*795d594fSAndroid Build Coastguard Worker   }
1906*795d594fSAndroid Build Coastguard Worker 
1907*795d594fSAndroid Build Coastguard Worker   LayoutHelper* const helper_;
1908*795d594fSAndroid Build Coastguard Worker   const size_t oat_index_;
1909*795d594fSAndroid Build Coastguard Worker };
1910*795d594fSAndroid Build Coastguard Worker 
1911*795d594fSAndroid Build Coastguard Worker // Visit method pointer arrays in `klass` that were not inherited from its superclass.
1912*795d594fSAndroid Build Coastguard Worker template <typename Visitor>
VisitNewMethodPointerArrays(ObjPtr<mirror::Class> klass,Visitor && visitor)1913*795d594fSAndroid Build Coastguard Worker static void VisitNewMethodPointerArrays(ObjPtr<mirror::Class> klass, Visitor&& visitor)
1914*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
1915*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::Class> super = klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
1916*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::PointerArray> vtable = klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1917*795d594fSAndroid Build Coastguard Worker   if (vtable != nullptr &&
1918*795d594fSAndroid Build Coastguard Worker       (super == nullptr || vtable != super->GetVTable<kVerifyNone, kWithoutReadBarrier>())) {
1919*795d594fSAndroid Build Coastguard Worker     visitor(vtable);
1920*795d594fSAndroid Build Coastguard Worker   }
1921*795d594fSAndroid Build Coastguard Worker   int32_t iftable_count = klass->GetIfTableCount();
1922*795d594fSAndroid Build Coastguard Worker   int32_t super_iftable_count = (super != nullptr) ? super->GetIfTableCount() : 0;
1923*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::IfTable> iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1924*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::IfTable> super_iftable =
1925*795d594fSAndroid Build Coastguard Worker       (super != nullptr) ? super->GetIfTable<kVerifyNone, kWithoutReadBarrier>() : nullptr;
1926*795d594fSAndroid Build Coastguard Worker   for (int32_t i = 0; i < iftable_count; ++i) {
1927*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::PointerArray> methods =
1928*795d594fSAndroid Build Coastguard Worker         iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
1929*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::PointerArray> super_methods = (i < super_iftable_count)
1930*795d594fSAndroid Build Coastguard Worker         ? super_iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i)
1931*795d594fSAndroid Build Coastguard Worker         : nullptr;
1932*795d594fSAndroid Build Coastguard Worker     if (methods != super_methods) {
1933*795d594fSAndroid Build Coastguard Worker       DCHECK(methods != nullptr);
1934*795d594fSAndroid Build Coastguard Worker       if (i < super_iftable_count) {
1935*795d594fSAndroid Build Coastguard Worker         DCHECK(super_methods != nullptr);
1936*795d594fSAndroid Build Coastguard Worker         DCHECK_EQ(methods->GetLength(), super_methods->GetLength());
1937*795d594fSAndroid Build Coastguard Worker       }
1938*795d594fSAndroid Build Coastguard Worker       visitor(methods);
1939*795d594fSAndroid Build Coastguard Worker     }
1940*795d594fSAndroid Build Coastguard Worker   }
1941*795d594fSAndroid Build Coastguard Worker }
1942*795d594fSAndroid Build Coastguard Worker 
ProcessDexFileObjects(Thread * self)1943*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::ProcessDexFileObjects(Thread* self) {
1944*795d594fSAndroid Build Coastguard Worker   Runtime* runtime = Runtime::Current();
1945*795d594fSAndroid Build Coastguard Worker   ClassLinker* class_linker = runtime->GetClassLinker();
1946*795d594fSAndroid Build Coastguard Worker   const CompilerOptions& compiler_options = image_writer_->compiler_options_;
1947*795d594fSAndroid Build Coastguard Worker   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
1948*795d594fSAndroid Build Coastguard Worker 
1949*795d594fSAndroid Build Coastguard Worker   // To ensure deterministic output, populate the work queue with objects in a pre-defined order.
1950*795d594fSAndroid Build Coastguard Worker   // Note: If we decide to implement a profile-guided layout, this is the place to do so.
1951*795d594fSAndroid Build Coastguard Worker 
1952*795d594fSAndroid Build Coastguard Worker   // Get initial work queue with the image classes and assign their bin slots.
1953*795d594fSAndroid Build Coastguard Worker   CollectClassesVisitor visitor(image_writer_);
1954*795d594fSAndroid Build Coastguard Worker   {
1955*795d594fSAndroid Build Coastguard Worker     WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1956*795d594fSAndroid Build Coastguard Worker     if (compiler_options.IsBootImage() || compiler_options.IsBootImageExtension()) {
1957*795d594fSAndroid Build Coastguard Worker       // No need to filter based on class loader, boot class table contains only
1958*795d594fSAndroid Build Coastguard Worker       // classes defined by the boot class loader.
1959*795d594fSAndroid Build Coastguard Worker       ClassTable* class_table = class_linker->boot_class_table_.get();
1960*795d594fSAndroid Build Coastguard Worker       class_table->Visit<kWithoutReadBarrier>(visitor);
1961*795d594fSAndroid Build Coastguard Worker     } else {
1962*795d594fSAndroid Build Coastguard Worker       // No need to visit boot class table as there are no classes there for the app image.
1963*795d594fSAndroid Build Coastguard Worker       for (const ClassLinker::ClassLoaderData& data : class_linker->class_loaders_) {
1964*795d594fSAndroid Build Coastguard Worker         auto class_loader =
1965*795d594fSAndroid Build Coastguard Worker             DecodeWeakGlobalWithoutRB<mirror::ClassLoader>(vm, self, data.weak_root);
1966*795d594fSAndroid Build Coastguard Worker         if (class_loader != nullptr) {
1967*795d594fSAndroid Build Coastguard Worker           ClassTable* class_table = class_loader->GetClassTable();
1968*795d594fSAndroid Build Coastguard Worker           if (class_table != nullptr) {
1969*795d594fSAndroid Build Coastguard Worker             // Visit only classes defined in this class loader (avoid visiting multiple times).
1970*795d594fSAndroid Build Coastguard Worker             auto filtering_visitor = [&visitor, class_loader](ObjPtr<mirror::Class> klass)
1971*795d594fSAndroid Build Coastguard Worker                 REQUIRES_SHARED(Locks::mutator_lock_) {
1972*795d594fSAndroid Build Coastguard Worker               if (klass->GetClassLoader<kVerifyNone, kWithoutReadBarrier>() == class_loader) {
1973*795d594fSAndroid Build Coastguard Worker                 visitor(klass);
1974*795d594fSAndroid Build Coastguard Worker               }
1975*795d594fSAndroid Build Coastguard Worker               return true;
1976*795d594fSAndroid Build Coastguard Worker             };
1977*795d594fSAndroid Build Coastguard Worker             class_table->Visit<kWithoutReadBarrier>(filtering_visitor);
1978*795d594fSAndroid Build Coastguard Worker           }
1979*795d594fSAndroid Build Coastguard Worker         }
1980*795d594fSAndroid Build Coastguard Worker       }
1981*795d594fSAndroid Build Coastguard Worker     }
1982*795d594fSAndroid Build Coastguard Worker   }
1983*795d594fSAndroid Build Coastguard Worker   DCHECK(work_queue_.empty());
1984*795d594fSAndroid Build Coastguard Worker   work_queue_ = visitor.ProcessCollectedClasses(self);
1985*795d594fSAndroid Build Coastguard Worker   for (const std::pair<ObjPtr<mirror::Object>, size_t>& entry : work_queue_) {
1986*795d594fSAndroid Build Coastguard Worker     DCHECK(entry.first != nullptr);
1987*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Class> klass = entry.first->AsClass();
1988*795d594fSAndroid Build Coastguard Worker     size_t oat_index = entry.second;
1989*795d594fSAndroid Build Coastguard Worker     image_writer_->RecordNativeRelocations(klass, oat_index);
1990*795d594fSAndroid Build Coastguard Worker     AssignImageBinSlot(klass.Ptr(), oat_index);
1991*795d594fSAndroid Build Coastguard Worker 
1992*795d594fSAndroid Build Coastguard Worker     auto method_pointer_array_visitor =
1993*795d594fSAndroid Build Coastguard Worker         [&](ObjPtr<mirror::PointerArray> pointer_array) REQUIRES_SHARED(Locks::mutator_lock_) {
1994*795d594fSAndroid Build Coastguard Worker           constexpr Bin bin = kBinObjects ? Bin::kInternalClean : Bin::kRegular;
1995*795d594fSAndroid Build Coastguard Worker           AssignImageBinSlot(pointer_array.Ptr(), oat_index, bin);
1996*795d594fSAndroid Build Coastguard Worker           // No need to add to the work queue. The class reference, if not in the boot image
1997*795d594fSAndroid Build Coastguard Worker           // (that is, when compiling the primary boot image), is already in the work queue.
1998*795d594fSAndroid Build Coastguard Worker         };
1999*795d594fSAndroid Build Coastguard Worker     VisitNewMethodPointerArrays(klass, method_pointer_array_visitor);
2000*795d594fSAndroid Build Coastguard Worker   }
2001*795d594fSAndroid Build Coastguard Worker 
2002*795d594fSAndroid Build Coastguard Worker   // Assign bin slots to dex caches.
2003*795d594fSAndroid Build Coastguard Worker   {
2004*795d594fSAndroid Build Coastguard Worker     ReaderMutexLock mu(self, *Locks::dex_lock_);
2005*795d594fSAndroid Build Coastguard Worker     for (const DexFile* dex_file : compiler_options.GetDexFilesForOatFile()) {
2006*795d594fSAndroid Build Coastguard Worker       auto it = image_writer_->dex_file_oat_index_map_.find(dex_file);
2007*795d594fSAndroid Build Coastguard Worker       DCHECK(it != image_writer_->dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2008*795d594fSAndroid Build Coastguard Worker       const size_t oat_index = it->second;
2009*795d594fSAndroid Build Coastguard Worker       // Assign bin slot to this file's dex cache and add it to the end of the work queue.
2010*795d594fSAndroid Build Coastguard Worker       auto dcd_it = class_linker->GetDexCachesData().find(dex_file);
2011*795d594fSAndroid Build Coastguard Worker       DCHECK(dcd_it != class_linker->GetDexCachesData().end()) << dex_file->GetLocation();
2012*795d594fSAndroid Build Coastguard Worker       auto dex_cache =
2013*795d594fSAndroid Build Coastguard Worker           DecodeWeakGlobalWithoutRB<mirror::DexCache>(vm, self, dcd_it->second.weak_root);
2014*795d594fSAndroid Build Coastguard Worker       DCHECK(dex_cache != nullptr);
2015*795d594fSAndroid Build Coastguard Worker       bool assigned = TryAssignBinSlot(dex_cache, oat_index);
2016*795d594fSAndroid Build Coastguard Worker       DCHECK(assigned);
2017*795d594fSAndroid Build Coastguard Worker       work_queue_.emplace_back(dex_cache, oat_index);
2018*795d594fSAndroid Build Coastguard Worker     }
2019*795d594fSAndroid Build Coastguard Worker   }
2020*795d594fSAndroid Build Coastguard Worker 
2021*795d594fSAndroid Build Coastguard Worker   // Assign interns to images depending on the first dex file they appear in.
2022*795d594fSAndroid Build Coastguard Worker   // Record those that do not have a StringId in any dex file.
2023*795d594fSAndroid Build Coastguard Worker   ProcessInterns(self);
2024*795d594fSAndroid Build Coastguard Worker 
2025*795d594fSAndroid Build Coastguard Worker   // Since classes and dex caches have been assigned to their bins, when we process a class
2026*795d594fSAndroid Build Coastguard Worker   // we do not follow through the class references or dex caches, so we correctly process
2027*795d594fSAndroid Build Coastguard Worker   // only objects actually belonging to that class before taking a new class from the queue.
2028*795d594fSAndroid Build Coastguard Worker   // If multiple class statics reference the same object (directly or indirectly), the object
2029*795d594fSAndroid Build Coastguard Worker   // is treated as belonging to the first encountered referencing class.
2030*795d594fSAndroid Build Coastguard Worker   ProcessWorkQueue();
2031*795d594fSAndroid Build Coastguard Worker }
2032*795d594fSAndroid Build Coastguard Worker 
ProcessRoots(Thread * self)2033*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::ProcessRoots(Thread* self) {
2034*795d594fSAndroid Build Coastguard Worker   // Assign bin slots to the image roots and boot image live objects, add them to the work queue
2035*795d594fSAndroid Build Coastguard Worker   // and process the work queue. These objects reference other objects needed for the image, for
2036*795d594fSAndroid Build Coastguard Worker   // example the array of dex cache references, or the pre-allocated exceptions for the boot image.
2037*795d594fSAndroid Build Coastguard Worker   DCHECK(work_queue_.empty());
2038*795d594fSAndroid Build Coastguard Worker 
2039*795d594fSAndroid Build Coastguard Worker   constexpr Bin clean_bin = kBinObjects ? Bin::kInternalClean : Bin::kRegular;
2040*795d594fSAndroid Build Coastguard Worker   size_t num_oat_files = image_writer_->oat_filenames_.size();
2041*795d594fSAndroid Build Coastguard Worker   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
2042*795d594fSAndroid Build Coastguard Worker   for (size_t oat_index = 0; oat_index != num_oat_files; ++oat_index) {
2043*795d594fSAndroid Build Coastguard Worker     // Put image roots and dex caches into `clean_bin`.
2044*795d594fSAndroid Build Coastguard Worker     auto image_roots = DecodeGlobalWithoutRB<mirror::ObjectArray<mirror::Object>>(
2045*795d594fSAndroid Build Coastguard Worker        vm, image_writer_->image_roots_[oat_index]);
2046*795d594fSAndroid Build Coastguard Worker     AssignImageBinSlot(image_roots, oat_index, clean_bin);
2047*795d594fSAndroid Build Coastguard Worker     work_queue_.emplace_back(image_roots, oat_index);
2048*795d594fSAndroid Build Coastguard Worker     // Do not rely on the `work_queue_` for dex cache arrays, it would assign a different bin.
2049*795d594fSAndroid Build Coastguard Worker     ObjPtr<ObjectArray<Object>> dex_caches = ObjPtr<ObjectArray<Object>>::DownCast(
2050*795d594fSAndroid Build Coastguard Worker         image_roots->GetWithoutChecks<kVerifyNone, kWithoutReadBarrier>(ImageHeader::kDexCaches));
2051*795d594fSAndroid Build Coastguard Worker     AssignImageBinSlot(dex_caches, oat_index, clean_bin);
2052*795d594fSAndroid Build Coastguard Worker     work_queue_.emplace_back(dex_caches, oat_index);
2053*795d594fSAndroid Build Coastguard Worker   }
2054*795d594fSAndroid Build Coastguard Worker   // Do not rely on the `work_queue_` for boot image live objects, it would assign a different bin.
2055*795d594fSAndroid Build Coastguard Worker   if (image_writer_->compiler_options_.IsBootImage()) {
2056*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
2057*795d594fSAndroid Build Coastguard Worker         image_writer_->boot_image_live_objects_;
2058*795d594fSAndroid Build Coastguard Worker     AssignImageBinSlot(boot_image_live_objects, GetDefaultOatIndex(), clean_bin);
2059*795d594fSAndroid Build Coastguard Worker     work_queue_.emplace_back(boot_image_live_objects, GetDefaultOatIndex());
2060*795d594fSAndroid Build Coastguard Worker   }
2061*795d594fSAndroid Build Coastguard Worker 
2062*795d594fSAndroid Build Coastguard Worker   ProcessWorkQueue();
2063*795d594fSAndroid Build Coastguard Worker }
2064*795d594fSAndroid Build Coastguard Worker 
ProcessInterns(Thread * self)2065*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::ProcessInterns(Thread* self) {
2066*795d594fSAndroid Build Coastguard Worker   // String bins are empty at this point.
2067*795d594fSAndroid Build Coastguard Worker   DCHECK(std::all_of(bin_objects_.begin(),
2068*795d594fSAndroid Build Coastguard Worker                      bin_objects_.end(),
2069*795d594fSAndroid Build Coastguard Worker                      [](const auto& bins) {
2070*795d594fSAndroid Build Coastguard Worker                        return bins[enum_cast<size_t>(Bin::kString)].empty();
2071*795d594fSAndroid Build Coastguard Worker                      }));
2072*795d594fSAndroid Build Coastguard Worker 
2073*795d594fSAndroid Build Coastguard Worker   // There is only one non-boot image intern table and it's the last one.
2074*795d594fSAndroid Build Coastguard Worker   InternTable* const intern_table = Runtime::Current()->GetInternTable();
2075*795d594fSAndroid Build Coastguard Worker   MutexLock mu(self, *Locks::intern_table_lock_);
2076*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(std::count_if(intern_table->strong_interns_.tables_.begin(),
2077*795d594fSAndroid Build Coastguard Worker                           intern_table->strong_interns_.tables_.end(),
2078*795d594fSAndroid Build Coastguard Worker                           [](const InternTable::Table::InternalTable& table) {
2079*795d594fSAndroid Build Coastguard Worker                             return !table.IsBootImage();
2080*795d594fSAndroid Build Coastguard Worker                           }),
2081*795d594fSAndroid Build Coastguard Worker             1);
2082*795d594fSAndroid Build Coastguard Worker   DCHECK(!intern_table->strong_interns_.tables_.back().IsBootImage());
2083*795d594fSAndroid Build Coastguard Worker   const InternTable::UnorderedSet& intern_set = intern_table->strong_interns_.tables_.back().set_;
2084*795d594fSAndroid Build Coastguard Worker 
2085*795d594fSAndroid Build Coastguard Worker   // Assign bin slots to all interns with a corresponding StringId in one of the input dex files.
2086*795d594fSAndroid Build Coastguard Worker   ImageWriter* image_writer = image_writer_;
2087*795d594fSAndroid Build Coastguard Worker   for (const DexFile* dex_file : image_writer->compiler_options_.GetDexFilesForOatFile()) {
2088*795d594fSAndroid Build Coastguard Worker     auto it = image_writer->dex_file_oat_index_map_.find(dex_file);
2089*795d594fSAndroid Build Coastguard Worker     DCHECK(it != image_writer->dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2090*795d594fSAndroid Build Coastguard Worker     const size_t oat_index = it->second;
2091*795d594fSAndroid Build Coastguard Worker     // Assign bin slots for strings defined in this dex file in StringId (lexicographical) order.
2092*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0, count = dex_file->NumStringIds(); i != count; ++i) {
2093*795d594fSAndroid Build Coastguard Worker       uint32_t utf16_length;
2094*795d594fSAndroid Build Coastguard Worker       const char* utf8_data = dex_file->GetStringDataAndUtf16Length(dex::StringIndex(i),
2095*795d594fSAndroid Build Coastguard Worker                                                                     &utf16_length);
2096*795d594fSAndroid Build Coastguard Worker       uint32_t hash = InternTable::Utf8String::Hash(utf16_length, utf8_data);
2097*795d594fSAndroid Build Coastguard Worker       auto intern_it =
2098*795d594fSAndroid Build Coastguard Worker           intern_set.FindWithHash(InternTable::Utf8String(utf16_length, utf8_data), hash);
2099*795d594fSAndroid Build Coastguard Worker       if (intern_it != intern_set.end()) {
2100*795d594fSAndroid Build Coastguard Worker         mirror::String* string = intern_it->Read<kWithoutReadBarrier>();
2101*795d594fSAndroid Build Coastguard Worker         DCHECK(string != nullptr);
2102*795d594fSAndroid Build Coastguard Worker         DCHECK(!image_writer->IsInBootImage(string));
2103*795d594fSAndroid Build Coastguard Worker         if (!image_writer->IsImageBinSlotAssigned(string)) {
2104*795d594fSAndroid Build Coastguard Worker           Bin bin = AssignImageBinSlot(string, oat_index);
2105*795d594fSAndroid Build Coastguard Worker           DCHECK_EQ(bin, kBinObjects ? Bin::kString : Bin::kRegular);
2106*795d594fSAndroid Build Coastguard Worker         } else {
2107*795d594fSAndroid Build Coastguard Worker           // We have already seen this string in a previous dex file.
2108*795d594fSAndroid Build Coastguard Worker           DCHECK(dex_file != image_writer->compiler_options_.GetDexFilesForOatFile().front());
2109*795d594fSAndroid Build Coastguard Worker         }
2110*795d594fSAndroid Build Coastguard Worker       }
2111*795d594fSAndroid Build Coastguard Worker     }
2112*795d594fSAndroid Build Coastguard Worker   }
2113*795d594fSAndroid Build Coastguard Worker 
2114*795d594fSAndroid Build Coastguard Worker   // String bins have been filled with dex file interns. Record their numbers in image infos.
2115*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(bin_objects_.size(), image_writer_->image_infos_.size());
2116*795d594fSAndroid Build Coastguard Worker   size_t total_dex_file_interns = 0u;
2117*795d594fSAndroid Build Coastguard Worker   for (size_t oat_index = 0, size = bin_objects_.size(); oat_index != size; ++oat_index) {
2118*795d594fSAndroid Build Coastguard Worker     size_t num_dex_file_interns = bin_objects_[oat_index][enum_cast<size_t>(Bin::kString)].size();
2119*795d594fSAndroid Build Coastguard Worker     ImageInfo& image_info = image_writer_->GetImageInfo(oat_index);
2120*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(image_info.intern_table_size_, 0u);
2121*795d594fSAndroid Build Coastguard Worker     image_info.intern_table_size_ = num_dex_file_interns;
2122*795d594fSAndroid Build Coastguard Worker     total_dex_file_interns += num_dex_file_interns;
2123*795d594fSAndroid Build Coastguard Worker   }
2124*795d594fSAndroid Build Coastguard Worker 
2125*795d594fSAndroid Build Coastguard Worker   // Collect interns that do not have a corresponding StringId in any of the input dex files.
2126*795d594fSAndroid Build Coastguard Worker   non_dex_file_interns_.reserve(intern_set.size() - total_dex_file_interns);
2127*795d594fSAndroid Build Coastguard Worker   for (const GcRoot<mirror::String>& root : intern_set) {
2128*795d594fSAndroid Build Coastguard Worker     mirror::String* string = root.Read<kWithoutReadBarrier>();
2129*795d594fSAndroid Build Coastguard Worker     if (!image_writer->IsImageBinSlotAssigned(string)) {
2130*795d594fSAndroid Build Coastguard Worker       non_dex_file_interns_.push_back(string);
2131*795d594fSAndroid Build Coastguard Worker     }
2132*795d594fSAndroid Build Coastguard Worker   }
2133*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(intern_set.size(), total_dex_file_interns + non_dex_file_interns_.size());
2134*795d594fSAndroid Build Coastguard Worker }
2135*795d594fSAndroid Build Coastguard Worker 
FinalizeInternTables()2136*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::FinalizeInternTables() {
2137*795d594fSAndroid Build Coastguard Worker   // Remove interns that do not have a bin slot assigned. These correspond
2138*795d594fSAndroid Build Coastguard Worker   // to the DexCache locations excluded in VerifyImageBinSlotsAssigned().
2139*795d594fSAndroid Build Coastguard Worker   ImageWriter* image_writer = image_writer_;
2140*795d594fSAndroid Build Coastguard Worker   auto retained_end = std::remove_if(
2141*795d594fSAndroid Build Coastguard Worker       non_dex_file_interns_.begin(),
2142*795d594fSAndroid Build Coastguard Worker       non_dex_file_interns_.end(),
2143*795d594fSAndroid Build Coastguard Worker       [=](mirror::String* string) REQUIRES_SHARED(Locks::mutator_lock_) {
2144*795d594fSAndroid Build Coastguard Worker         return !image_writer->IsImageBinSlotAssigned(string);
2145*795d594fSAndroid Build Coastguard Worker       });
2146*795d594fSAndroid Build Coastguard Worker   non_dex_file_interns_.resize(std::distance(non_dex_file_interns_.begin(), retained_end));
2147*795d594fSAndroid Build Coastguard Worker 
2148*795d594fSAndroid Build Coastguard Worker   // Sort `non_dex_file_interns_` based on oat index and bin offset.
2149*795d594fSAndroid Build Coastguard Worker   ArrayRef<mirror::String*> non_dex_file_interns(non_dex_file_interns_);
2150*795d594fSAndroid Build Coastguard Worker   std::sort(non_dex_file_interns.begin(),
2151*795d594fSAndroid Build Coastguard Worker             non_dex_file_interns.end(),
2152*795d594fSAndroid Build Coastguard Worker             [=](mirror::String* lhs, mirror::String* rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
2153*795d594fSAndroid Build Coastguard Worker               size_t lhs_oat_index = image_writer->GetOatIndex(lhs);
2154*795d594fSAndroid Build Coastguard Worker               size_t rhs_oat_index = image_writer->GetOatIndex(rhs);
2155*795d594fSAndroid Build Coastguard Worker               if (lhs_oat_index != rhs_oat_index) {
2156*795d594fSAndroid Build Coastguard Worker                 return lhs_oat_index < rhs_oat_index;
2157*795d594fSAndroid Build Coastguard Worker               }
2158*795d594fSAndroid Build Coastguard Worker               BinSlot lhs_bin_slot = image_writer->GetImageBinSlot(lhs, lhs_oat_index);
2159*795d594fSAndroid Build Coastguard Worker               BinSlot rhs_bin_slot = image_writer->GetImageBinSlot(rhs, rhs_oat_index);
2160*795d594fSAndroid Build Coastguard Worker               return lhs_bin_slot < rhs_bin_slot;
2161*795d594fSAndroid Build Coastguard Worker             });
2162*795d594fSAndroid Build Coastguard Worker 
2163*795d594fSAndroid Build Coastguard Worker   // Allocate and fill intern tables.
2164*795d594fSAndroid Build Coastguard Worker   size_t ndfi_index = 0u;
2165*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(bin_objects_.size(), image_writer->image_infos_.size());
2166*795d594fSAndroid Build Coastguard Worker   for (size_t oat_index = 0, size = bin_objects_.size(); oat_index != size; ++oat_index) {
2167*795d594fSAndroid Build Coastguard Worker     // Find the end of `non_dex_file_interns` for this oat file.
2168*795d594fSAndroid Build Coastguard Worker     size_t ndfi_end = ndfi_index;
2169*795d594fSAndroid Build Coastguard Worker     while (ndfi_end != non_dex_file_interns.size() &&
2170*795d594fSAndroid Build Coastguard Worker            image_writer->GetOatIndex(non_dex_file_interns[ndfi_end]) == oat_index) {
2171*795d594fSAndroid Build Coastguard Worker       ++ndfi_end;
2172*795d594fSAndroid Build Coastguard Worker     }
2173*795d594fSAndroid Build Coastguard Worker 
2174*795d594fSAndroid Build Coastguard Worker     // Calculate final intern table size.
2175*795d594fSAndroid Build Coastguard Worker     ImageInfo& image_info = image_writer->GetImageInfo(oat_index);
2176*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(image_info.intern_table_bytes_, 0u);
2177*795d594fSAndroid Build Coastguard Worker     size_t num_dex_file_interns = image_info.intern_table_size_;
2178*795d594fSAndroid Build Coastguard Worker     size_t num_non_dex_file_interns = ndfi_end - ndfi_index;
2179*795d594fSAndroid Build Coastguard Worker     image_info.intern_table_size_ = num_dex_file_interns + num_non_dex_file_interns;
2180*795d594fSAndroid Build Coastguard Worker     if (image_info.intern_table_size_ != 0u) {
2181*795d594fSAndroid Build Coastguard Worker       // Make sure the intern table shall be full by allocating a buffer of the right size.
2182*795d594fSAndroid Build Coastguard Worker       size_t buffer_size = static_cast<size_t>(
2183*795d594fSAndroid Build Coastguard Worker           ceil(image_info.intern_table_size_ / kImageInternTableMaxLoadFactor));
2184*795d594fSAndroid Build Coastguard Worker       image_info.intern_table_buffer_.reset(new GcRoot<mirror::String>[buffer_size]);
2185*795d594fSAndroid Build Coastguard Worker       DCHECK(image_info.intern_table_buffer_ != nullptr);
2186*795d594fSAndroid Build Coastguard Worker       image_info.intern_table_.emplace(kImageInternTableMinLoadFactor,
2187*795d594fSAndroid Build Coastguard Worker                                        kImageInternTableMaxLoadFactor,
2188*795d594fSAndroid Build Coastguard Worker                                        image_info.intern_table_buffer_.get(),
2189*795d594fSAndroid Build Coastguard Worker                                        buffer_size);
2190*795d594fSAndroid Build Coastguard Worker 
2191*795d594fSAndroid Build Coastguard Worker       // Fill the intern table. Dex file interns are at the start of the bin_objects[.][kString].
2192*795d594fSAndroid Build Coastguard Worker       InternTable::UnorderedSet& table = *image_info.intern_table_;
2193*795d594fSAndroid Build Coastguard Worker       const auto& oat_file_strings = bin_objects_[oat_index][enum_cast<size_t>(Bin::kString)];
2194*795d594fSAndroid Build Coastguard Worker       DCHECK_LE(num_dex_file_interns, oat_file_strings.size());
2195*795d594fSAndroid Build Coastguard Worker       ArrayRef<mirror::Object* const> dex_file_interns(
2196*795d594fSAndroid Build Coastguard Worker           oat_file_strings.data(), num_dex_file_interns);
2197*795d594fSAndroid Build Coastguard Worker       for (mirror::Object* string : dex_file_interns) {
2198*795d594fSAndroid Build Coastguard Worker         bool inserted = table.insert(GcRoot<mirror::String>(string->AsString())).second;
2199*795d594fSAndroid Build Coastguard Worker         DCHECK(inserted) << "String already inserted: " << string->AsString()->ToModifiedUtf8();
2200*795d594fSAndroid Build Coastguard Worker       }
2201*795d594fSAndroid Build Coastguard Worker       ArrayRef<mirror::String*> current_non_dex_file_interns =
2202*795d594fSAndroid Build Coastguard Worker           non_dex_file_interns.SubArray(ndfi_index, num_non_dex_file_interns);
2203*795d594fSAndroid Build Coastguard Worker       for (mirror::String* string : current_non_dex_file_interns) {
2204*795d594fSAndroid Build Coastguard Worker         bool inserted = table.insert(GcRoot<mirror::String>(string)).second;
2205*795d594fSAndroid Build Coastguard Worker         DCHECK(inserted) << "String already inserted: " << string->ToModifiedUtf8();
2206*795d594fSAndroid Build Coastguard Worker       }
2207*795d594fSAndroid Build Coastguard Worker 
2208*795d594fSAndroid Build Coastguard Worker       // Record the intern table size in bytes.
2209*795d594fSAndroid Build Coastguard Worker       image_info.intern_table_bytes_ = table.WriteToMemory(nullptr);
2210*795d594fSAndroid Build Coastguard Worker     }
2211*795d594fSAndroid Build Coastguard Worker 
2212*795d594fSAndroid Build Coastguard Worker     ndfi_index = ndfi_end;
2213*795d594fSAndroid Build Coastguard Worker   }
2214*795d594fSAndroid Build Coastguard Worker }
2215*795d594fSAndroid Build Coastguard Worker 
ProcessWorkQueue()2216*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::ProcessWorkQueue() {
2217*795d594fSAndroid Build Coastguard Worker   while (!work_queue_.empty()) {
2218*795d594fSAndroid Build Coastguard Worker     std::pair<ObjPtr<mirror::Object>, size_t> pair = work_queue_.front();
2219*795d594fSAndroid Build Coastguard Worker     work_queue_.pop_front();
2220*795d594fSAndroid Build Coastguard Worker     VisitReferences(/*obj=*/ pair.first, /*oat_index=*/ pair.second);
2221*795d594fSAndroid Build Coastguard Worker   }
2222*795d594fSAndroid Build Coastguard Worker }
2223*795d594fSAndroid Build Coastguard Worker 
SortDirtyObjects(const HashMap<mirror::Object *,uint32_t> & dirty_objects,size_t oat_index)2224*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::SortDirtyObjects(
2225*795d594fSAndroid Build Coastguard Worker     const HashMap<mirror::Object*, uint32_t>& dirty_objects, size_t oat_index) {
2226*795d594fSAndroid Build Coastguard Worker   constexpr Bin bin = Bin::kKnownDirty;
2227*795d594fSAndroid Build Coastguard Worker   ImageInfo& image_info = image_writer_->GetImageInfo(oat_index);
2228*795d594fSAndroid Build Coastguard Worker 
2229*795d594fSAndroid Build Coastguard Worker   dchecked_vector<mirror::Object*>& known_dirty = bin_objects_[oat_index][enum_cast<size_t>(bin)];
2230*795d594fSAndroid Build Coastguard Worker   if (known_dirty.empty()) {
2231*795d594fSAndroid Build Coastguard Worker     return;
2232*795d594fSAndroid Build Coastguard Worker   }
2233*795d594fSAndroid Build Coastguard Worker 
2234*795d594fSAndroid Build Coastguard Worker   // Collect objects and their combined sort_keys.
2235*795d594fSAndroid Build Coastguard Worker   // Combined key contains sort_key and original offset to ensure deterministic sorting.
2236*795d594fSAndroid Build Coastguard Worker   using CombinedKey = std::pair<uint32_t, uint32_t>;
2237*795d594fSAndroid Build Coastguard Worker   using ObjSortPair = std::pair<mirror::Object*, CombinedKey>;
2238*795d594fSAndroid Build Coastguard Worker   dchecked_vector<ObjSortPair> objects;
2239*795d594fSAndroid Build Coastguard Worker   objects.reserve(known_dirty.size());
2240*795d594fSAndroid Build Coastguard Worker   for (mirror::Object* obj : known_dirty) {
2241*795d594fSAndroid Build Coastguard Worker     const BinSlot bin_slot = image_writer_->GetImageBinSlot(obj, oat_index);
2242*795d594fSAndroid Build Coastguard Worker     const uint32_t original_offset = bin_slot.GetOffset();
2243*795d594fSAndroid Build Coastguard Worker     const auto it = dirty_objects.find(obj);
2244*795d594fSAndroid Build Coastguard Worker     const uint32_t sort_key = (it != dirty_objects.end()) ? it->second : 0;
2245*795d594fSAndroid Build Coastguard Worker     objects.emplace_back(obj, std::make_pair(sort_key, original_offset));
2246*795d594fSAndroid Build Coastguard Worker   }
2247*795d594fSAndroid Build Coastguard Worker   // Sort by combined sort_key.
2248*795d594fSAndroid Build Coastguard Worker   std::sort(std::begin(objects), std::end(objects), [&](ObjSortPair& lhs, ObjSortPair& rhs) {
2249*795d594fSAndroid Build Coastguard Worker     return lhs.second < rhs.second;
2250*795d594fSAndroid Build Coastguard Worker   });
2251*795d594fSAndroid Build Coastguard Worker 
2252*795d594fSAndroid Build Coastguard Worker   // Fill known_dirty objects in sorted order, update bin offsets.
2253*795d594fSAndroid Build Coastguard Worker   known_dirty.clear();
2254*795d594fSAndroid Build Coastguard Worker   size_t offset = 0;
2255*795d594fSAndroid Build Coastguard Worker   for (const ObjSortPair& entry : objects) {
2256*795d594fSAndroid Build Coastguard Worker     mirror::Object* obj = entry.first;
2257*795d594fSAndroid Build Coastguard Worker 
2258*795d594fSAndroid Build Coastguard Worker     known_dirty.push_back(obj);
2259*795d594fSAndroid Build Coastguard Worker     image_writer_->UpdateImageBinSlotOffset(obj, oat_index, offset);
2260*795d594fSAndroid Build Coastguard Worker 
2261*795d594fSAndroid Build Coastguard Worker     const size_t aligned_object_size = RoundUp(obj->SizeOf<kVerifyNone>(), kObjectAlignment);
2262*795d594fSAndroid Build Coastguard Worker     offset += aligned_object_size;
2263*795d594fSAndroid Build Coastguard Worker   }
2264*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(offset, image_info.GetBinSlotSize(bin));
2265*795d594fSAndroid Build Coastguard Worker }
2266*795d594fSAndroid Build Coastguard Worker 
VerifyImageBinSlotsAssigned()2267*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::VerifyImageBinSlotsAssigned() {
2268*795d594fSAndroid Build Coastguard Worker   dchecked_vector<mirror::Object*> carveout;
2269*795d594fSAndroid Build Coastguard Worker   JavaVMExt* vm = nullptr;
2270*795d594fSAndroid Build Coastguard Worker   if (image_writer_->compiler_options_.IsAppImage()) {
2271*795d594fSAndroid Build Coastguard Worker     // Exclude boot class path dex caches that are not part of the boot image.
2272*795d594fSAndroid Build Coastguard Worker     // Also exclude their locations if they have not been visited through another path.
2273*795d594fSAndroid Build Coastguard Worker     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2274*795d594fSAndroid Build Coastguard Worker     Thread* self = Thread::Current();
2275*795d594fSAndroid Build Coastguard Worker     vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
2276*795d594fSAndroid Build Coastguard Worker     ReaderMutexLock mu(self, *Locks::dex_lock_);
2277*795d594fSAndroid Build Coastguard Worker     for (const auto& entry : class_linker->GetDexCachesData()) {
2278*795d594fSAndroid Build Coastguard Worker       const ClassLinker::DexCacheData& data = entry.second;
2279*795d594fSAndroid Build Coastguard Worker       auto dex_cache = DecodeWeakGlobalWithoutRB<mirror::DexCache>(vm, self, data.weak_root);
2280*795d594fSAndroid Build Coastguard Worker       if (dex_cache == nullptr ||
2281*795d594fSAndroid Build Coastguard Worker           image_writer_->IsInBootImage(dex_cache.Ptr()) ||
2282*795d594fSAndroid Build Coastguard Worker           ContainsElement(image_writer_->compiler_options_.GetDexFilesForOatFile(),
2283*795d594fSAndroid Build Coastguard Worker                           dex_cache->GetDexFile())) {
2284*795d594fSAndroid Build Coastguard Worker         continue;
2285*795d594fSAndroid Build Coastguard Worker       }
2286*795d594fSAndroid Build Coastguard Worker       CHECK(!image_writer_->IsImageBinSlotAssigned(dex_cache.Ptr()));
2287*795d594fSAndroid Build Coastguard Worker       carveout.push_back(dex_cache.Ptr());
2288*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::String> location = dex_cache->GetLocation<kVerifyNone, kWithoutReadBarrier>();
2289*795d594fSAndroid Build Coastguard Worker       if (!image_writer_->IsImageBinSlotAssigned(location.Ptr())) {
2290*795d594fSAndroid Build Coastguard Worker         carveout.push_back(location.Ptr());
2291*795d594fSAndroid Build Coastguard Worker       }
2292*795d594fSAndroid Build Coastguard Worker     }
2293*795d594fSAndroid Build Coastguard Worker   }
2294*795d594fSAndroid Build Coastguard Worker 
2295*795d594fSAndroid Build Coastguard Worker   dchecked_vector<mirror::Object*> missed_objects;
2296*795d594fSAndroid Build Coastguard Worker   auto ensure_bin_slots_assigned = [&](mirror::Object* obj)
2297*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2298*795d594fSAndroid Build Coastguard Worker     if (!image_writer_->IsInBootImage(obj)) {
2299*795d594fSAndroid Build Coastguard Worker       if (!UNLIKELY(image_writer_->IsImageBinSlotAssigned(obj))) {
2300*795d594fSAndroid Build Coastguard Worker         // Ignore the `carveout` objects.
2301*795d594fSAndroid Build Coastguard Worker         if (ContainsElement(carveout, obj)) {
2302*795d594fSAndroid Build Coastguard Worker           return;
2303*795d594fSAndroid Build Coastguard Worker         }
2304*795d594fSAndroid Build Coastguard Worker         // Ignore finalizer references for the dalvik.system.DexFile objects referenced by
2305*795d594fSAndroid Build Coastguard Worker         // the app class loader.
2306*795d594fSAndroid Build Coastguard Worker         ObjPtr<mirror::Class> klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
2307*795d594fSAndroid Build Coastguard Worker         if (klass->IsFinalizerReferenceClass<kVerifyNone>()) {
2308*795d594fSAndroid Build Coastguard Worker           ObjPtr<mirror::Class> reference_class =
2309*795d594fSAndroid Build Coastguard Worker               klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
2310*795d594fSAndroid Build Coastguard Worker           DCHECK(reference_class->DescriptorEquals("Ljava/lang/ref/Reference;"));
2311*795d594fSAndroid Build Coastguard Worker           ArtField* ref_field = reference_class->FindDeclaredInstanceField(
2312*795d594fSAndroid Build Coastguard Worker               "referent", "Ljava/lang/Object;");
2313*795d594fSAndroid Build Coastguard Worker           CHECK(ref_field != nullptr);
2314*795d594fSAndroid Build Coastguard Worker           ObjPtr<mirror::Object> ref = ref_field->GetObject<kWithoutReadBarrier>(obj);
2315*795d594fSAndroid Build Coastguard Worker           CHECK(ref != nullptr);
2316*795d594fSAndroid Build Coastguard Worker           CHECK(image_writer_->IsImageBinSlotAssigned(ref.Ptr()));
2317*795d594fSAndroid Build Coastguard Worker           ObjPtr<mirror::Class> ref_klass = ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2318*795d594fSAndroid Build Coastguard Worker           CHECK(ref_klass == WellKnownClasses::dalvik_system_DexFile.Get<kWithoutReadBarrier>());
2319*795d594fSAndroid Build Coastguard Worker           // Note: The app class loader is used only for checking against the runtime
2320*795d594fSAndroid Build Coastguard Worker           // class loader, the dex file cookie is cleared and therefore we do not need
2321*795d594fSAndroid Build Coastguard Worker           // to run the finalizer even if we implement app image objects collection.
2322*795d594fSAndroid Build Coastguard Worker           ArtField* field = WellKnownClasses::dalvik_system_DexFile_cookie;
2323*795d594fSAndroid Build Coastguard Worker           CHECK(field->GetObject<kWithoutReadBarrier>(ref) == nullptr);
2324*795d594fSAndroid Build Coastguard Worker           return;
2325*795d594fSAndroid Build Coastguard Worker         }
2326*795d594fSAndroid Build Coastguard Worker         if (klass->IsStringClass()) {
2327*795d594fSAndroid Build Coastguard Worker           // Ignore interned strings. These may come from reflection interning method names.
2328*795d594fSAndroid Build Coastguard Worker           // TODO: Make dex file strings weak interns and GC them before writing the image.
2329*795d594fSAndroid Build Coastguard Worker           if (IsStronglyInternedString(obj->AsString())) {
2330*795d594fSAndroid Build Coastguard Worker             return;
2331*795d594fSAndroid Build Coastguard Worker           }
2332*795d594fSAndroid Build Coastguard Worker         }
2333*795d594fSAndroid Build Coastguard Worker         missed_objects.push_back(obj);
2334*795d594fSAndroid Build Coastguard Worker       }
2335*795d594fSAndroid Build Coastguard Worker     }
2336*795d594fSAndroid Build Coastguard Worker   };
2337*795d594fSAndroid Build Coastguard Worker   Runtime::Current()->GetHeap()->VisitObjects(ensure_bin_slots_assigned);
2338*795d594fSAndroid Build Coastguard Worker   if (!missed_objects.empty()) {
2339*795d594fSAndroid Build Coastguard Worker     const gc::Verification* v = Runtime::Current()->GetHeap()->GetVerification();
2340*795d594fSAndroid Build Coastguard Worker     size_t num_missed_objects = missed_objects.size();
2341*795d594fSAndroid Build Coastguard Worker     size_t num_paths = std::min<size_t>(num_missed_objects, 5u);  // Do not flood the output.
2342*795d594fSAndroid Build Coastguard Worker     ArrayRef<mirror::Object*> missed_objects_head =
2343*795d594fSAndroid Build Coastguard Worker         ArrayRef<mirror::Object*>(missed_objects).SubArray(/*pos=*/ 0u, /*length=*/ num_paths);
2344*795d594fSAndroid Build Coastguard Worker     for (mirror::Object* obj : missed_objects_head) {
2345*795d594fSAndroid Build Coastguard Worker       LOG(ERROR) << "Image object without assigned bin slot: "
2346*795d594fSAndroid Build Coastguard Worker           << mirror::Object::PrettyTypeOf(obj) << " " << obj
2347*795d594fSAndroid Build Coastguard Worker           << " " << v->FirstPathFromRootSet(obj);
2348*795d594fSAndroid Build Coastguard Worker     }
2349*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "Found " << num_missed_objects << " objects without assigned bin slots.";
2350*795d594fSAndroid Build Coastguard Worker   }
2351*795d594fSAndroid Build Coastguard Worker }
2352*795d594fSAndroid Build Coastguard Worker 
FinalizeBinSlotOffsets()2353*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::FinalizeBinSlotOffsets() {
2354*795d594fSAndroid Build Coastguard Worker   // Calculate bin slot offsets and adjust for region padding if needed.
2355*795d594fSAndroid Build Coastguard Worker   const size_t region_size = image_writer_->region_size_;
2356*795d594fSAndroid Build Coastguard Worker   const size_t num_image_infos = image_writer_->image_infos_.size();
2357*795d594fSAndroid Build Coastguard Worker   for (size_t oat_index = 0; oat_index != num_image_infos; ++oat_index) {
2358*795d594fSAndroid Build Coastguard Worker     ImageInfo& image_info = image_writer_->image_infos_[oat_index];
2359*795d594fSAndroid Build Coastguard Worker     size_t bin_offset = image_writer_->image_objects_offset_begin_;
2360*795d594fSAndroid Build Coastguard Worker 
2361*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i != kNumberOfBins; ++i) {
2362*795d594fSAndroid Build Coastguard Worker       Bin bin = enum_cast<Bin>(i);
2363*795d594fSAndroid Build Coastguard Worker       switch (bin) {
2364*795d594fSAndroid Build Coastguard Worker         case Bin::kArtMethodClean:
2365*795d594fSAndroid Build Coastguard Worker         case Bin::kArtMethodDirty: {
2366*795d594fSAndroid Build Coastguard Worker           bin_offset = RoundUp(bin_offset, ArtMethod::Alignment(image_writer_->target_ptr_size_));
2367*795d594fSAndroid Build Coastguard Worker           break;
2368*795d594fSAndroid Build Coastguard Worker         }
2369*795d594fSAndroid Build Coastguard Worker         case Bin::kImTable:
2370*795d594fSAndroid Build Coastguard Worker         case Bin::kIMTConflictTable: {
2371*795d594fSAndroid Build Coastguard Worker           bin_offset = RoundUp(bin_offset, static_cast<size_t>(image_writer_->target_ptr_size_));
2372*795d594fSAndroid Build Coastguard Worker           break;
2373*795d594fSAndroid Build Coastguard Worker         }
2374*795d594fSAndroid Build Coastguard Worker         default: {
2375*795d594fSAndroid Build Coastguard Worker           // Normal alignment.
2376*795d594fSAndroid Build Coastguard Worker         }
2377*795d594fSAndroid Build Coastguard Worker       }
2378*795d594fSAndroid Build Coastguard Worker       image_info.bin_slot_offsets_[i] = bin_offset;
2379*795d594fSAndroid Build Coastguard Worker 
2380*795d594fSAndroid Build Coastguard Worker       // If the bin is for mirror objects, we may need to add region padding and update offsets.
2381*795d594fSAndroid Build Coastguard Worker       if (i < enum_cast<size_t>(Bin::kMirrorCount) && region_size != 0u) {
2382*795d594fSAndroid Build Coastguard Worker         const size_t offset_after_header = bin_offset - sizeof(ImageHeader);
2383*795d594fSAndroid Build Coastguard Worker         size_t remaining_space =
2384*795d594fSAndroid Build Coastguard Worker             RoundUp(offset_after_header + 1u, region_size) - offset_after_header;
2385*795d594fSAndroid Build Coastguard Worker         // Exercise the loop below in debug builds to get coverage.
2386*795d594fSAndroid Build Coastguard Worker         if (kIsDebugBuild || remaining_space < image_info.bin_slot_sizes_[i]) {
2387*795d594fSAndroid Build Coastguard Worker           // The bin crosses a region boundary. Add padding if needed.
2388*795d594fSAndroid Build Coastguard Worker           size_t object_offset = 0u;
2389*795d594fSAndroid Build Coastguard Worker           size_t padding = 0u;
2390*795d594fSAndroid Build Coastguard Worker           for (mirror::Object* object : bin_objects_[oat_index][i]) {
2391*795d594fSAndroid Build Coastguard Worker             BinSlot bin_slot = image_writer_->GetImageBinSlot(object, oat_index);
2392*795d594fSAndroid Build Coastguard Worker             DCHECK_EQ(enum_cast<size_t>(bin_slot.GetBin()), i);
2393*795d594fSAndroid Build Coastguard Worker             DCHECK_EQ(bin_slot.GetOffset() + padding, object_offset);
2394*795d594fSAndroid Build Coastguard Worker             size_t object_size = RoundUp(object->SizeOf<kVerifyNone>(), kObjectAlignment);
2395*795d594fSAndroid Build Coastguard Worker 
2396*795d594fSAndroid Build Coastguard Worker             auto add_padding = [&](bool tail_region) {
2397*795d594fSAndroid Build Coastguard Worker               DCHECK_NE(remaining_space, 0u);
2398*795d594fSAndroid Build Coastguard Worker               DCHECK_LT(remaining_space, region_size);
2399*795d594fSAndroid Build Coastguard Worker               DCHECK_ALIGNED(remaining_space, kObjectAlignment);
2400*795d594fSAndroid Build Coastguard Worker               // TODO When copying to heap regions, leave the tail region padding zero-filled.
2401*795d594fSAndroid Build Coastguard Worker               if (!tail_region || true) {
2402*795d594fSAndroid Build Coastguard Worker                 image_info.padding_offsets_.push_back(bin_offset + object_offset);
2403*795d594fSAndroid Build Coastguard Worker               }
2404*795d594fSAndroid Build Coastguard Worker               image_info.bin_slot_sizes_[i] += remaining_space;
2405*795d594fSAndroid Build Coastguard Worker               padding += remaining_space;
2406*795d594fSAndroid Build Coastguard Worker               object_offset += remaining_space;
2407*795d594fSAndroid Build Coastguard Worker               remaining_space = region_size;
2408*795d594fSAndroid Build Coastguard Worker             };
2409*795d594fSAndroid Build Coastguard Worker             if (object_size > remaining_space) {
2410*795d594fSAndroid Build Coastguard Worker               // Padding needed if we're not at region boundary (with a multi-region object).
2411*795d594fSAndroid Build Coastguard Worker               if (remaining_space != region_size) {
2412*795d594fSAndroid Build Coastguard Worker                 // TODO: Instead of adding padding, we should consider reordering the bins
2413*795d594fSAndroid Build Coastguard Worker                 // or objects to reduce wasted space.
2414*795d594fSAndroid Build Coastguard Worker                 add_padding(/*tail_region=*/ false);
2415*795d594fSAndroid Build Coastguard Worker               }
2416*795d594fSAndroid Build Coastguard Worker               DCHECK_EQ(remaining_space, region_size);
2417*795d594fSAndroid Build Coastguard Worker               // For huge objects, adjust the remaining space to hold the object and some more.
2418*795d594fSAndroid Build Coastguard Worker               if (object_size > region_size) {
2419*795d594fSAndroid Build Coastguard Worker                 remaining_space = RoundUp(object_size + 1u, region_size);
2420*795d594fSAndroid Build Coastguard Worker               }
2421*795d594fSAndroid Build Coastguard Worker             } else if (remaining_space == object_size) {
2422*795d594fSAndroid Build Coastguard Worker               // Move to the next region, no padding needed.
2423*795d594fSAndroid Build Coastguard Worker               remaining_space += region_size;
2424*795d594fSAndroid Build Coastguard Worker             }
2425*795d594fSAndroid Build Coastguard Worker             DCHECK_GT(remaining_space, object_size);
2426*795d594fSAndroid Build Coastguard Worker             remaining_space -= object_size;
2427*795d594fSAndroid Build Coastguard Worker             image_writer_->UpdateImageBinSlotOffset(object, oat_index, object_offset);
2428*795d594fSAndroid Build Coastguard Worker             object_offset += object_size;
2429*795d594fSAndroid Build Coastguard Worker             // Add padding to the tail region of huge objects if not region-aligned.
2430*795d594fSAndroid Build Coastguard Worker             if (object_size > region_size && remaining_space != region_size) {
2431*795d594fSAndroid Build Coastguard Worker               DCHECK(!IsAlignedParam(object_size, region_size));
2432*795d594fSAndroid Build Coastguard Worker               add_padding(/*tail_region=*/ true);
2433*795d594fSAndroid Build Coastguard Worker             }
2434*795d594fSAndroid Build Coastguard Worker           }
2435*795d594fSAndroid Build Coastguard Worker           image_writer_->region_alignment_wasted_ += padding;
2436*795d594fSAndroid Build Coastguard Worker           image_info.image_end_ += padding;
2437*795d594fSAndroid Build Coastguard Worker         }
2438*795d594fSAndroid Build Coastguard Worker       }
2439*795d594fSAndroid Build Coastguard Worker       bin_offset += image_info.bin_slot_sizes_[i];
2440*795d594fSAndroid Build Coastguard Worker     }
2441*795d594fSAndroid Build Coastguard Worker     // NOTE: There may be additional padding between the bin slots and the intern table.
2442*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(
2443*795d594fSAndroid Build Coastguard Worker         image_info.image_end_,
2444*795d594fSAndroid Build Coastguard Worker         image_info.GetBinSizeSum(Bin::kMirrorCount) + image_writer_->image_objects_offset_begin_);
2445*795d594fSAndroid Build Coastguard Worker   }
2446*795d594fSAndroid Build Coastguard Worker 
2447*795d594fSAndroid Build Coastguard Worker   VLOG(image) << "Space wasted for region alignment " << image_writer_->region_alignment_wasted_;
2448*795d594fSAndroid Build Coastguard Worker }
2449*795d594fSAndroid Build Coastguard Worker 
CollectStringReferenceInfo()2450*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::CollectStringReferenceInfo() {
2451*795d594fSAndroid Build Coastguard Worker   size_t total_string_refs = 0u;
2452*795d594fSAndroid Build Coastguard Worker 
2453*795d594fSAndroid Build Coastguard Worker   const size_t num_image_infos = image_writer_->image_infos_.size();
2454*795d594fSAndroid Build Coastguard Worker   for (size_t oat_index = 0; oat_index != num_image_infos; ++oat_index) {
2455*795d594fSAndroid Build Coastguard Worker     ImageInfo& image_info = image_writer_->image_infos_[oat_index];
2456*795d594fSAndroid Build Coastguard Worker     DCHECK(image_info.string_reference_offsets_.empty());
2457*795d594fSAndroid Build Coastguard Worker     image_info.string_reference_offsets_.reserve(image_info.num_string_references_);
2458*795d594fSAndroid Build Coastguard Worker 
2459*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i < enum_cast<size_t>(Bin::kMirrorCount); ++i) {
2460*795d594fSAndroid Build Coastguard Worker       for (mirror::Object* obj : bin_objects_[oat_index][i]) {
2461*795d594fSAndroid Build Coastguard Worker         CollectStringReferenceVisitor visitor(image_writer_,
2462*795d594fSAndroid Build Coastguard Worker                                               oat_index,
2463*795d594fSAndroid Build Coastguard Worker                                               &image_info.string_reference_offsets_,
2464*795d594fSAndroid Build Coastguard Worker                                               obj);
2465*795d594fSAndroid Build Coastguard Worker         /*
2466*795d594fSAndroid Build Coastguard Worker          * References to managed strings can occur either in the managed heap or in
2467*795d594fSAndroid Build Coastguard Worker          * native memory regions. Information about managed references is collected
2468*795d594fSAndroid Build Coastguard Worker          * by the CollectStringReferenceVisitor and directly added to the image info.
2469*795d594fSAndroid Build Coastguard Worker          *
2470*795d594fSAndroid Build Coastguard Worker          * Native references to managed strings can only occur through DexCache
2471*795d594fSAndroid Build Coastguard Worker          * objects. This is verified by the visitor in debug mode and the references
2472*795d594fSAndroid Build Coastguard Worker          * are collected separately below.
2473*795d594fSAndroid Build Coastguard Worker          */
2474*795d594fSAndroid Build Coastguard Worker         obj->VisitReferences</*kVisitNativeRoots=*/ kIsDebugBuild,
2475*795d594fSAndroid Build Coastguard Worker                              kVerifyNone,
2476*795d594fSAndroid Build Coastguard Worker                              kWithoutReadBarrier>(visitor, visitor);
2477*795d594fSAndroid Build Coastguard Worker       }
2478*795d594fSAndroid Build Coastguard Worker     }
2479*795d594fSAndroid Build Coastguard Worker 
2480*795d594fSAndroid Build Coastguard Worker     total_string_refs += image_info.string_reference_offsets_.size();
2481*795d594fSAndroid Build Coastguard Worker 
2482*795d594fSAndroid Build Coastguard Worker     // Check that we collected the same number of string references as we saw in the previous pass.
2483*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(image_info.string_reference_offsets_.size(), image_info.num_string_references_);
2484*795d594fSAndroid Build Coastguard Worker   }
2485*795d594fSAndroid Build Coastguard Worker 
2486*795d594fSAndroid Build Coastguard Worker   VLOG(compiler) << "Dex2Oat:AppImage:stringReferences = " << total_string_refs;
2487*795d594fSAndroid Build Coastguard Worker }
2488*795d594fSAndroid Build Coastguard Worker 
VisitReferences(ObjPtr<mirror::Object> obj,size_t oat_index)2489*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::VisitReferences(ObjPtr<mirror::Object> obj, size_t oat_index) {
2490*795d594fSAndroid Build Coastguard Worker   size_t old_work_queue_size = work_queue_.size();
2491*795d594fSAndroid Build Coastguard Worker   VisitReferencesVisitor visitor(this, oat_index);
2492*795d594fSAndroid Build Coastguard Worker   // Walk references and assign bin slots for them.
2493*795d594fSAndroid Build Coastguard Worker   obj->VisitReferences</*kVisitNativeRoots=*/ false, kVerifyNone, kWithoutReadBarrier>(
2494*795d594fSAndroid Build Coastguard Worker       visitor,
2495*795d594fSAndroid Build Coastguard Worker       visitor);
2496*795d594fSAndroid Build Coastguard Worker   // Put the added references in the queue in the order in which they were added.
2497*795d594fSAndroid Build Coastguard Worker   // The visitor just pushes them to the front as it visits them.
2498*795d594fSAndroid Build Coastguard Worker   DCHECK_LE(old_work_queue_size, work_queue_.size());
2499*795d594fSAndroid Build Coastguard Worker   size_t num_added = work_queue_.size() - old_work_queue_size;
2500*795d594fSAndroid Build Coastguard Worker   std::reverse(work_queue_.begin(), work_queue_.begin() + num_added);
2501*795d594fSAndroid Build Coastguard Worker }
2502*795d594fSAndroid Build Coastguard Worker 
TryAssignBinSlot(ObjPtr<mirror::Object> obj,size_t oat_index)2503*795d594fSAndroid Build Coastguard Worker bool ImageWriter::LayoutHelper::TryAssignBinSlot(ObjPtr<mirror::Object> obj, size_t oat_index) {
2504*795d594fSAndroid Build Coastguard Worker   if (obj == nullptr || image_writer_->IsInBootImage(obj.Ptr())) {
2505*795d594fSAndroid Build Coastguard Worker     // Object is null or already in the image, there is no work to do.
2506*795d594fSAndroid Build Coastguard Worker     return false;
2507*795d594fSAndroid Build Coastguard Worker   }
2508*795d594fSAndroid Build Coastguard Worker   bool assigned = false;
2509*795d594fSAndroid Build Coastguard Worker   if (!image_writer_->IsImageBinSlotAssigned(obj.Ptr())) {
2510*795d594fSAndroid Build Coastguard Worker     AssignImageBinSlot(obj.Ptr(), oat_index);
2511*795d594fSAndroid Build Coastguard Worker     assigned = true;
2512*795d594fSAndroid Build Coastguard Worker   }
2513*795d594fSAndroid Build Coastguard Worker   return assigned;
2514*795d594fSAndroid Build Coastguard Worker }
2515*795d594fSAndroid Build Coastguard Worker 
AssignImageBinSlot(ObjPtr<mirror::Object> object,size_t oat_index)2516*795d594fSAndroid Build Coastguard Worker ImageWriter::Bin ImageWriter::LayoutHelper::AssignImageBinSlot(ObjPtr<mirror::Object> object,
2517*795d594fSAndroid Build Coastguard Worker                                                                size_t oat_index) {
2518*795d594fSAndroid Build Coastguard Worker   DCHECK(object != nullptr);
2519*795d594fSAndroid Build Coastguard Worker   Bin bin = image_writer_->GetImageBin(object.Ptr());
2520*795d594fSAndroid Build Coastguard Worker   AssignImageBinSlot(object.Ptr(), oat_index, bin);
2521*795d594fSAndroid Build Coastguard Worker   return bin;
2522*795d594fSAndroid Build Coastguard Worker }
2523*795d594fSAndroid Build Coastguard Worker 
AssignImageBinSlot(ObjPtr<mirror::Object> object,size_t oat_index,Bin bin)2524*795d594fSAndroid Build Coastguard Worker void ImageWriter::LayoutHelper::AssignImageBinSlot(
2525*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::Object> object, size_t oat_index, Bin bin) {
2526*795d594fSAndroid Build Coastguard Worker   DCHECK(object != nullptr);
2527*795d594fSAndroid Build Coastguard Worker   DCHECK(!image_writer_->IsInBootImage(object.Ptr()));
2528*795d594fSAndroid Build Coastguard Worker   DCHECK(!image_writer_->IsImageBinSlotAssigned(object.Ptr()));
2529*795d594fSAndroid Build Coastguard Worker   image_writer_->AssignImageBinSlot(object.Ptr(), oat_index, bin);
2530*795d594fSAndroid Build Coastguard Worker   bin_objects_[oat_index][enum_cast<size_t>(bin)].push_back(object.Ptr());
2531*795d594fSAndroid Build Coastguard Worker }
2532*795d594fSAndroid Build Coastguard Worker 
AssertOnly1Thread()2533*795d594fSAndroid Build Coastguard Worker static inline void AssertOnly1Thread() REQUIRES(!Locks::thread_list_lock_) {
2534*795d594fSAndroid Build Coastguard Worker   if (kIsDebugBuild) {
2535*795d594fSAndroid Build Coastguard Worker     Runtime::Current()->GetThreadList()->CheckOnly1Thread(Thread::Current());
2536*795d594fSAndroid Build Coastguard Worker   }
2537*795d594fSAndroid Build Coastguard Worker }
2538*795d594fSAndroid Build Coastguard Worker 
CalculateNewObjectOffsets()2539*795d594fSAndroid Build Coastguard Worker void ImageWriter::CalculateNewObjectOffsets() {
2540*795d594fSAndroid Build Coastguard Worker   Thread* const self = Thread::Current();
2541*795d594fSAndroid Build Coastguard Worker   Runtime* const runtime = Runtime::Current();
2542*795d594fSAndroid Build Coastguard Worker   gc::Heap* const heap = runtime->GetHeap();
2543*795d594fSAndroid Build Coastguard Worker 
2544*795d594fSAndroid Build Coastguard Worker   AssertOnly1Thread();
2545*795d594fSAndroid Build Coastguard Worker   // Leave space for the header, but do not write it yet, we need to
2546*795d594fSAndroid Build Coastguard Worker   // know where image_roots is going to end up
2547*795d594fSAndroid Build Coastguard Worker   image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment);  // 64-bit-alignment
2548*795d594fSAndroid Build Coastguard Worker 
2549*795d594fSAndroid Build Coastguard Worker   // Write the image runtime methods.
2550*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
2551*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
2552*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
2553*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
2554*795d594fSAndroid Build Coastguard Worker       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves);
2555*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
2556*795d594fSAndroid Build Coastguard Worker       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly);
2557*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
2558*795d594fSAndroid Build Coastguard Worker       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
2559*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kSaveEverythingMethod] =
2560*795d594fSAndroid Build Coastguard Worker       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything);
2561*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kSaveEverythingMethodForClinit] =
2562*795d594fSAndroid Build Coastguard Worker       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit);
2563*795d594fSAndroid Build Coastguard Worker   image_methods_[ImageHeader::kSaveEverythingMethodForSuspendCheck] =
2564*795d594fSAndroid Build Coastguard Worker       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck);
2565*795d594fSAndroid Build Coastguard Worker   // Visit image methods first to have the main runtime methods in the first image.
2566*795d594fSAndroid Build Coastguard Worker   for (auto* m : image_methods_) {
2567*795d594fSAndroid Build Coastguard Worker     CHECK(m != nullptr);
2568*795d594fSAndroid Build Coastguard Worker     CHECK(m->IsRuntimeMethod());
2569*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(!compiler_options_.IsBootImage(), IsInBootImage(m))
2570*795d594fSAndroid Build Coastguard Worker         << "Trampolines should be in boot image";
2571*795d594fSAndroid Build Coastguard Worker     if (!IsInBootImage(m)) {
2572*795d594fSAndroid Build Coastguard Worker       AssignMethodOffset(m, NativeObjectRelocationType::kRuntimeMethod, GetDefaultOatIndex());
2573*795d594fSAndroid Build Coastguard Worker     }
2574*795d594fSAndroid Build Coastguard Worker   }
2575*795d594fSAndroid Build Coastguard Worker 
2576*795d594fSAndroid Build Coastguard Worker   // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
2577*795d594fSAndroid Build Coastguard Worker   // this lock while holding other locks may cause lock order violations.
2578*795d594fSAndroid Build Coastguard Worker   {
2579*795d594fSAndroid Build Coastguard Worker     auto deflate_monitor =
2580*795d594fSAndroid Build Coastguard Worker         // NO_THREAD_SAFETY_ANALYSIS: We don't really hold mutator_lock_ exclusively.
2581*795d594fSAndroid Build Coastguard Worker         [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_)
2582*795d594fSAndroid Build Coastguard Worker             NO_THREAD_SAFETY_ANALYSIS { Monitor::Deflate(Thread::Current(), obj); };
2583*795d594fSAndroid Build Coastguard Worker     heap->VisitObjects(deflate_monitor);
2584*795d594fSAndroid Build Coastguard Worker     // This does not update the MonitorList, which is thus rendered invalid, and is no longer used.
2585*795d594fSAndroid Build Coastguard Worker   }
2586*795d594fSAndroid Build Coastguard Worker 
2587*795d594fSAndroid Build Coastguard Worker   // From this point on, there shall be no GC anymore and no objects shall be allocated.
2588*795d594fSAndroid Build Coastguard Worker   // We can now assign a BitSlot to each object and store it in its lockword.
2589*795d594fSAndroid Build Coastguard Worker 
2590*795d594fSAndroid Build Coastguard Worker   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
2591*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsBootImage() || compiler_options_.IsBootImageExtension()) {
2592*795d594fSAndroid Build Coastguard Worker     // Record the address of boot image live objects.
2593*795d594fSAndroid Build Coastguard Worker     auto image_roots = DecodeGlobalWithoutRB<mirror::ObjectArray<mirror::Object>>(
2594*795d594fSAndroid Build Coastguard Worker         vm, image_roots_[0]);
2595*795d594fSAndroid Build Coastguard Worker     boot_image_live_objects_ = ObjPtr<ObjectArray<Object>>::DownCast(
2596*795d594fSAndroid Build Coastguard Worker         image_roots->GetWithoutChecks<kVerifyNone, kWithoutReadBarrier>(
2597*795d594fSAndroid Build Coastguard Worker             ImageHeader::kBootImageLiveObjects)).Ptr();
2598*795d594fSAndroid Build Coastguard Worker   }
2599*795d594fSAndroid Build Coastguard Worker 
2600*795d594fSAndroid Build Coastguard Worker   // If dirty_image_objects_ is present - try optimizing object layout.
2601*795d594fSAndroid Build Coastguard Worker   // Parse dirty-image-objects entries and put them in dirty_objects_ map, which is then used in
2602*795d594fSAndroid Build Coastguard Worker   // `AssignImageBinSlot` method to put the objects in dirty bin.
2603*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsBootImage() && dirty_image_objects_ != nullptr) {
2604*795d594fSAndroid Build Coastguard Worker     dirty_objects_ = MatchDirtyObjectPaths(*dirty_image_objects_);
2605*795d594fSAndroid Build Coastguard Worker     LOG(INFO) << ART_FORMAT("Matched {} out of {} dirty-image-objects",
2606*795d594fSAndroid Build Coastguard Worker                             dirty_objects_.size(),
2607*795d594fSAndroid Build Coastguard Worker                             dirty_image_objects_->size());
2608*795d594fSAndroid Build Coastguard Worker   }
2609*795d594fSAndroid Build Coastguard Worker 
2610*795d594fSAndroid Build Coastguard Worker   LayoutHelper layout_helper(this);
2611*795d594fSAndroid Build Coastguard Worker   layout_helper.ProcessDexFileObjects(self);
2612*795d594fSAndroid Build Coastguard Worker   layout_helper.ProcessRoots(self);
2613*795d594fSAndroid Build Coastguard Worker   layout_helper.FinalizeInternTables();
2614*795d594fSAndroid Build Coastguard Worker 
2615*795d594fSAndroid Build Coastguard Worker   // Sort objects in dirty bin.
2616*795d594fSAndroid Build Coastguard Worker   if (!dirty_objects_.empty()) {
2617*795d594fSAndroid Build Coastguard Worker     for (size_t oat_index = 0; oat_index < image_infos_.size(); ++oat_index) {
2618*795d594fSAndroid Build Coastguard Worker       layout_helper.SortDirtyObjects(dirty_objects_, oat_index);
2619*795d594fSAndroid Build Coastguard Worker     }
2620*795d594fSAndroid Build Coastguard Worker   }
2621*795d594fSAndroid Build Coastguard Worker 
2622*795d594fSAndroid Build Coastguard Worker   // Verify that all objects have assigned image bin slots.
2623*795d594fSAndroid Build Coastguard Worker   layout_helper.VerifyImageBinSlotsAssigned();
2624*795d594fSAndroid Build Coastguard Worker 
2625*795d594fSAndroid Build Coastguard Worker   // Finalize bin slot offsets. This may add padding for regions.
2626*795d594fSAndroid Build Coastguard Worker   layout_helper.FinalizeBinSlotOffsets();
2627*795d594fSAndroid Build Coastguard Worker 
2628*795d594fSAndroid Build Coastguard Worker   // Collect string reference info for app images.
2629*795d594fSAndroid Build Coastguard Worker   if (ClassLinker::kAppImageMayContainStrings && compiler_options_.IsAppImage()) {
2630*795d594fSAndroid Build Coastguard Worker     layout_helper.CollectStringReferenceInfo();
2631*795d594fSAndroid Build Coastguard Worker   }
2632*795d594fSAndroid Build Coastguard Worker 
2633*795d594fSAndroid Build Coastguard Worker   // Calculate image offsets.
2634*795d594fSAndroid Build Coastguard Worker   size_t image_offset = 0;
2635*795d594fSAndroid Build Coastguard Worker   for (ImageInfo& image_info : image_infos_) {
2636*795d594fSAndroid Build Coastguard Worker     image_info.image_begin_ = global_image_begin_ + image_offset;
2637*795d594fSAndroid Build Coastguard Worker     image_info.image_offset_ = image_offset;
2638*795d594fSAndroid Build Coastguard Worker     image_info.image_size_ = RoundUp(image_info.CreateImageSections().first, kElfSegmentAlignment);
2639*795d594fSAndroid Build Coastguard Worker     // There should be no gaps until the next image.
2640*795d594fSAndroid Build Coastguard Worker     image_offset += image_info.image_size_;
2641*795d594fSAndroid Build Coastguard Worker   }
2642*795d594fSAndroid Build Coastguard Worker 
2643*795d594fSAndroid Build Coastguard Worker   size_t oat_index = 0;
2644*795d594fSAndroid Build Coastguard Worker   for (ImageInfo& image_info : image_infos_) {
2645*795d594fSAndroid Build Coastguard Worker     auto image_roots = DecodeGlobalWithoutRB<mirror::ObjectArray<mirror::Object>>(
2646*795d594fSAndroid Build Coastguard Worker         vm, image_roots_[oat_index]);
2647*795d594fSAndroid Build Coastguard Worker     image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Ptr()));
2648*795d594fSAndroid Build Coastguard Worker     ++oat_index;
2649*795d594fSAndroid Build Coastguard Worker   }
2650*795d594fSAndroid Build Coastguard Worker 
2651*795d594fSAndroid Build Coastguard Worker   // Update the native relocations by adding their bin sums.
2652*795d594fSAndroid Build Coastguard Worker   for (auto& pair : native_object_relocations_) {
2653*795d594fSAndroid Build Coastguard Worker     NativeObjectRelocation& relocation = pair.second;
2654*795d594fSAndroid Build Coastguard Worker     Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
2655*795d594fSAndroid Build Coastguard Worker     ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2656*795d594fSAndroid Build Coastguard Worker     relocation.offset += image_info.GetBinSlotOffset(bin_type);
2657*795d594fSAndroid Build Coastguard Worker   }
2658*795d594fSAndroid Build Coastguard Worker 
2659*795d594fSAndroid Build Coastguard Worker   // Update the JNI stub methods by adding their bin sums.
2660*795d594fSAndroid Build Coastguard Worker   for (auto& pair : jni_stub_map_) {
2661*795d594fSAndroid Build Coastguard Worker     JniStubMethodRelocation& relocation = pair.second.second;
2662*795d594fSAndroid Build Coastguard Worker     constexpr Bin bin_type = Bin::kJniStubMethod;
2663*795d594fSAndroid Build Coastguard Worker     ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2664*795d594fSAndroid Build Coastguard Worker     relocation.offset += image_info.GetBinSlotOffset(bin_type);
2665*795d594fSAndroid Build Coastguard Worker   }
2666*795d594fSAndroid Build Coastguard Worker }
2667*795d594fSAndroid Build Coastguard Worker 
2668*795d594fSAndroid Build Coastguard Worker std::pair<size_t, dchecked_vector<ImageSection>>
CreateImageSections() const2669*795d594fSAndroid Build Coastguard Worker ImageWriter::ImageInfo::CreateImageSections() const {
2670*795d594fSAndroid Build Coastguard Worker   dchecked_vector<ImageSection> sections(ImageHeader::kSectionCount);
2671*795d594fSAndroid Build Coastguard Worker 
2672*795d594fSAndroid Build Coastguard Worker   // Do not round up any sections here that are represented by the bins since it
2673*795d594fSAndroid Build Coastguard Worker   // will break offsets.
2674*795d594fSAndroid Build Coastguard Worker 
2675*795d594fSAndroid Build Coastguard Worker   /*
2676*795d594fSAndroid Build Coastguard Worker    * Objects section
2677*795d594fSAndroid Build Coastguard Worker    */
2678*795d594fSAndroid Build Coastguard Worker   sections[ImageHeader::kSectionObjects] =
2679*795d594fSAndroid Build Coastguard Worker       ImageSection(0u, image_end_);
2680*795d594fSAndroid Build Coastguard Worker 
2681*795d594fSAndroid Build Coastguard Worker   /*
2682*795d594fSAndroid Build Coastguard Worker    * Field section
2683*795d594fSAndroid Build Coastguard Worker    */
2684*795d594fSAndroid Build Coastguard Worker   sections[ImageHeader::kSectionArtFields] =
2685*795d594fSAndroid Build Coastguard Worker       ImageSection(GetBinSlotOffset(Bin::kArtField), GetBinSlotSize(Bin::kArtField));
2686*795d594fSAndroid Build Coastguard Worker 
2687*795d594fSAndroid Build Coastguard Worker   /*
2688*795d594fSAndroid Build Coastguard Worker    * Method section
2689*795d594fSAndroid Build Coastguard Worker    */
2690*795d594fSAndroid Build Coastguard Worker   sections[ImageHeader::kSectionArtMethods] =
2691*795d594fSAndroid Build Coastguard Worker       ImageSection(GetBinSlotOffset(Bin::kArtMethodClean),
2692*795d594fSAndroid Build Coastguard Worker                    GetBinSlotSize(Bin::kArtMethodClean) +
2693*795d594fSAndroid Build Coastguard Worker                    GetBinSlotSize(Bin::kArtMethodDirty));
2694*795d594fSAndroid Build Coastguard Worker 
2695*795d594fSAndroid Build Coastguard Worker   /*
2696*795d594fSAndroid Build Coastguard Worker    * IMT section
2697*795d594fSAndroid Build Coastguard Worker    */
2698*795d594fSAndroid Build Coastguard Worker   sections[ImageHeader::kSectionImTables] =
2699*795d594fSAndroid Build Coastguard Worker       ImageSection(GetBinSlotOffset(Bin::kImTable), GetBinSlotSize(Bin::kImTable));
2700*795d594fSAndroid Build Coastguard Worker 
2701*795d594fSAndroid Build Coastguard Worker   /*
2702*795d594fSAndroid Build Coastguard Worker    * Conflict Tables section
2703*795d594fSAndroid Build Coastguard Worker    */
2704*795d594fSAndroid Build Coastguard Worker   sections[ImageHeader::kSectionIMTConflictTables] =
2705*795d594fSAndroid Build Coastguard Worker       ImageSection(GetBinSlotOffset(Bin::kIMTConflictTable), GetBinSlotSize(Bin::kIMTConflictTable));
2706*795d594fSAndroid Build Coastguard Worker 
2707*795d594fSAndroid Build Coastguard Worker   /*
2708*795d594fSAndroid Build Coastguard Worker    * Runtime Methods section
2709*795d594fSAndroid Build Coastguard Worker    */
2710*795d594fSAndroid Build Coastguard Worker   sections[ImageHeader::kSectionRuntimeMethods] =
2711*795d594fSAndroid Build Coastguard Worker       ImageSection(GetBinSlotOffset(Bin::kRuntimeMethod), GetBinSlotSize(Bin::kRuntimeMethod));
2712*795d594fSAndroid Build Coastguard Worker 
2713*795d594fSAndroid Build Coastguard Worker   /*
2714*795d594fSAndroid Build Coastguard Worker    * JNI Stub Methods section
2715*795d594fSAndroid Build Coastguard Worker    */
2716*795d594fSAndroid Build Coastguard Worker   sections[ImageHeader::kSectionJniStubMethods] =
2717*795d594fSAndroid Build Coastguard Worker       ImageSection(GetBinSlotOffset(Bin::kJniStubMethod), GetBinSlotSize(Bin::kJniStubMethod));
2718*795d594fSAndroid Build Coastguard Worker 
2719*795d594fSAndroid Build Coastguard Worker   /*
2720*795d594fSAndroid Build Coastguard Worker    * Interned Strings section
2721*795d594fSAndroid Build Coastguard Worker    */
2722*795d594fSAndroid Build Coastguard Worker 
2723*795d594fSAndroid Build Coastguard Worker   // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
2724*795d594fSAndroid Build Coastguard Worker   size_t cur_pos = RoundUp(sections[ImageHeader::kSectionJniStubMethods].End(), sizeof(uint64_t));
2725*795d594fSAndroid Build Coastguard Worker 
2726*795d594fSAndroid Build Coastguard Worker   const ImageSection& interned_strings_section =
2727*795d594fSAndroid Build Coastguard Worker       sections[ImageHeader::kSectionInternedStrings] =
2728*795d594fSAndroid Build Coastguard Worker           ImageSection(cur_pos, intern_table_bytes_);
2729*795d594fSAndroid Build Coastguard Worker 
2730*795d594fSAndroid Build Coastguard Worker   /*
2731*795d594fSAndroid Build Coastguard Worker    * Class Table section
2732*795d594fSAndroid Build Coastguard Worker    */
2733*795d594fSAndroid Build Coastguard Worker 
2734*795d594fSAndroid Build Coastguard Worker   // Obtain the new position and round it up to the appropriate alignment.
2735*795d594fSAndroid Build Coastguard Worker   cur_pos = RoundUp(interned_strings_section.End(), sizeof(uint64_t));
2736*795d594fSAndroid Build Coastguard Worker 
2737*795d594fSAndroid Build Coastguard Worker   const ImageSection& class_table_section =
2738*795d594fSAndroid Build Coastguard Worker       sections[ImageHeader::kSectionClassTable] =
2739*795d594fSAndroid Build Coastguard Worker           ImageSection(cur_pos, class_table_bytes_);
2740*795d594fSAndroid Build Coastguard Worker 
2741*795d594fSAndroid Build Coastguard Worker   /*
2742*795d594fSAndroid Build Coastguard Worker    * String Field Offsets section
2743*795d594fSAndroid Build Coastguard Worker    */
2744*795d594fSAndroid Build Coastguard Worker 
2745*795d594fSAndroid Build Coastguard Worker   // Round up to the alignment of the offsets we are going to store.
2746*795d594fSAndroid Build Coastguard Worker   cur_pos = RoundUp(class_table_section.End(), sizeof(uint32_t));
2747*795d594fSAndroid Build Coastguard Worker 
2748*795d594fSAndroid Build Coastguard Worker   // The size of string_reference_offsets_ can't be used here because it hasn't
2749*795d594fSAndroid Build Coastguard Worker   // been filled with AppImageReferenceOffsetInfo objects yet.  The
2750*795d594fSAndroid Build Coastguard Worker   // num_string_references_ value is calculated separately, before we can
2751*795d594fSAndroid Build Coastguard Worker   // compute the actual offsets.
2752*795d594fSAndroid Build Coastguard Worker   const ImageSection& string_reference_offsets =
2753*795d594fSAndroid Build Coastguard Worker       sections[ImageHeader::kSectionStringReferenceOffsets] =
2754*795d594fSAndroid Build Coastguard Worker           ImageSection(cur_pos, sizeof(string_reference_offsets_[0]) * num_string_references_);
2755*795d594fSAndroid Build Coastguard Worker 
2756*795d594fSAndroid Build Coastguard Worker   /*
2757*795d594fSAndroid Build Coastguard Worker    * DexCache arrays section
2758*795d594fSAndroid Build Coastguard Worker    */
2759*795d594fSAndroid Build Coastguard Worker 
2760*795d594fSAndroid Build Coastguard Worker   // Round up to the alignment dex caches arrays expects.
2761*795d594fSAndroid Build Coastguard Worker   cur_pos = RoundUp(sections[ImageHeader::kSectionStringReferenceOffsets].End(), sizeof(uint32_t));
2762*795d594fSAndroid Build Coastguard Worker   // We don't generate dex cache arrays in an image generated by dex2oat.
2763*795d594fSAndroid Build Coastguard Worker   sections[ImageHeader::kSectionDexCacheArrays] = ImageSection(cur_pos, 0u);
2764*795d594fSAndroid Build Coastguard Worker 
2765*795d594fSAndroid Build Coastguard Worker   /*
2766*795d594fSAndroid Build Coastguard Worker    * Metadata section.
2767*795d594fSAndroid Build Coastguard Worker    */
2768*795d594fSAndroid Build Coastguard Worker 
2769*795d594fSAndroid Build Coastguard Worker   // Round up to the alignment of the offsets we are going to store.
2770*795d594fSAndroid Build Coastguard Worker   cur_pos = RoundUp(string_reference_offsets.End(), sizeof(uint32_t));
2771*795d594fSAndroid Build Coastguard Worker 
2772*795d594fSAndroid Build Coastguard Worker   const ImageSection& metadata_section =
2773*795d594fSAndroid Build Coastguard Worker       sections[ImageHeader::kSectionMetadata] =
2774*795d594fSAndroid Build Coastguard Worker           ImageSection(cur_pos, GetBinSlotSize(Bin::kMetadata));
2775*795d594fSAndroid Build Coastguard Worker 
2776*795d594fSAndroid Build Coastguard Worker   // Return the number of bytes described by these sections, and the sections
2777*795d594fSAndroid Build Coastguard Worker   // themselves.
2778*795d594fSAndroid Build Coastguard Worker   return make_pair(metadata_section.End(), std::move(sections));
2779*795d594fSAndroid Build Coastguard Worker }
2780*795d594fSAndroid Build Coastguard Worker 
CreateHeader(size_t oat_index,size_t component_count)2781*795d594fSAndroid Build Coastguard Worker void ImageWriter::CreateHeader(size_t oat_index, size_t component_count) {
2782*795d594fSAndroid Build Coastguard Worker   ImageInfo& image_info = GetImageInfo(oat_index);
2783*795d594fSAndroid Build Coastguard Worker   const uint8_t* oat_file_begin = image_info.oat_file_begin_;
2784*795d594fSAndroid Build Coastguard Worker   const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
2785*795d594fSAndroid Build Coastguard Worker   const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
2786*795d594fSAndroid Build Coastguard Worker 
2787*795d594fSAndroid Build Coastguard Worker   uint32_t image_reservation_size = image_info.image_size_;
2788*795d594fSAndroid Build Coastguard Worker   DCHECK_ALIGNED(image_reservation_size, kElfSegmentAlignment);
2789*795d594fSAndroid Build Coastguard Worker   uint32_t current_component_count = 1u;
2790*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsAppImage()) {
2791*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(oat_index, 0u);
2792*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(component_count, current_component_count);
2793*795d594fSAndroid Build Coastguard Worker   } else {
2794*795d594fSAndroid Build Coastguard Worker     DCHECK(image_infos_.size() == 1u || image_infos_.size() == component_count)
2795*795d594fSAndroid Build Coastguard Worker         << image_infos_.size() << " " << component_count;
2796*795d594fSAndroid Build Coastguard Worker     if (oat_index == 0u) {
2797*795d594fSAndroid Build Coastguard Worker       const ImageInfo& last_info = image_infos_.back();
2798*795d594fSAndroid Build Coastguard Worker       const uint8_t* end = last_info.oat_file_begin_ + last_info.oat_loaded_size_;
2799*795d594fSAndroid Build Coastguard Worker       DCHECK_ALIGNED(image_info.image_begin_, kElfSegmentAlignment);
2800*795d594fSAndroid Build Coastguard Worker       image_reservation_size = dchecked_integral_cast<uint32_t>(
2801*795d594fSAndroid Build Coastguard Worker           RoundUp(end - image_info.image_begin_, kElfSegmentAlignment));
2802*795d594fSAndroid Build Coastguard Worker       current_component_count = component_count;
2803*795d594fSAndroid Build Coastguard Worker     } else {
2804*795d594fSAndroid Build Coastguard Worker       image_reservation_size = 0u;
2805*795d594fSAndroid Build Coastguard Worker       current_component_count = 0u;
2806*795d594fSAndroid Build Coastguard Worker     }
2807*795d594fSAndroid Build Coastguard Worker   }
2808*795d594fSAndroid Build Coastguard Worker 
2809*795d594fSAndroid Build Coastguard Worker   // Compute boot image checksums for the primary component, leave as 0 otherwise.
2810*795d594fSAndroid Build Coastguard Worker   uint32_t boot_image_components = 0u;
2811*795d594fSAndroid Build Coastguard Worker   uint32_t boot_image_checksums = 0u;
2812*795d594fSAndroid Build Coastguard Worker   if (oat_index == 0u) {
2813*795d594fSAndroid Build Coastguard Worker     const std::vector<gc::space::ImageSpace*>& image_spaces =
2814*795d594fSAndroid Build Coastguard Worker         Runtime::Current()->GetHeap()->GetBootImageSpaces();
2815*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(image_spaces.empty(), compiler_options_.IsBootImage());
2816*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0u, size = image_spaces.size(); i != size; ) {
2817*795d594fSAndroid Build Coastguard Worker       const ImageHeader& header = image_spaces[i]->GetImageHeader();
2818*795d594fSAndroid Build Coastguard Worker       boot_image_components += header.GetComponentCount();
2819*795d594fSAndroid Build Coastguard Worker       boot_image_checksums ^= header.GetImageChecksum();
2820*795d594fSAndroid Build Coastguard Worker       DCHECK_LE(header.GetImageSpaceCount(), size - i);
2821*795d594fSAndroid Build Coastguard Worker       i += header.GetImageSpaceCount();
2822*795d594fSAndroid Build Coastguard Worker     }
2823*795d594fSAndroid Build Coastguard Worker   }
2824*795d594fSAndroid Build Coastguard Worker 
2825*795d594fSAndroid Build Coastguard Worker   // Create the image sections.
2826*795d594fSAndroid Build Coastguard Worker   auto section_info_pair = image_info.CreateImageSections();
2827*795d594fSAndroid Build Coastguard Worker   const size_t image_end = section_info_pair.first;
2828*795d594fSAndroid Build Coastguard Worker   dchecked_vector<ImageSection>& sections = section_info_pair.second;
2829*795d594fSAndroid Build Coastguard Worker 
2830*795d594fSAndroid Build Coastguard Worker   // Finally bitmap section.
2831*795d594fSAndroid Build Coastguard Worker   const size_t bitmap_bytes = image_info.image_bitmap_.Size();
2832*795d594fSAndroid Build Coastguard Worker   auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
2833*795d594fSAndroid Build Coastguard Worker   // The offset of the bitmap section should be aligned to kElfSegmentAlignment to enable mapping
2834*795d594fSAndroid Build Coastguard Worker   // the section from file to memory. However the section size doesn't have to be rounded up as it
2835*795d594fSAndroid Build Coastguard Worker   // is located at the end of the file. When mapping file contents to memory, if the last page of
2836*795d594fSAndroid Build Coastguard Worker   // the mapping is only partially filled with data, the rest will be zero-filled.
2837*795d594fSAndroid Build Coastguard Worker   *bitmap_section = ImageSection(RoundUp(image_end, kElfSegmentAlignment), bitmap_bytes);
2838*795d594fSAndroid Build Coastguard Worker   if (VLOG_IS_ON(compiler)) {
2839*795d594fSAndroid Build Coastguard Worker     LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
2840*795d594fSAndroid Build Coastguard Worker     size_t idx = 0;
2841*795d594fSAndroid Build Coastguard Worker     for (const ImageSection& section : sections) {
2842*795d594fSAndroid Build Coastguard Worker       LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
2843*795d594fSAndroid Build Coastguard Worker       ++idx;
2844*795d594fSAndroid Build Coastguard Worker     }
2845*795d594fSAndroid Build Coastguard Worker     LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
2846*795d594fSAndroid Build Coastguard Worker     LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
2847*795d594fSAndroid Build Coastguard Worker     LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
2848*795d594fSAndroid Build Coastguard Worker               << " Image offset=" << image_info.image_offset_ << std::dec;
2849*795d594fSAndroid Build Coastguard Worker     LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
2850*795d594fSAndroid Build Coastguard Worker               << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
2851*795d594fSAndroid Build Coastguard Worker               << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
2852*795d594fSAndroid Build Coastguard Worker               << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
2853*795d594fSAndroid Build Coastguard Worker   }
2854*795d594fSAndroid Build Coastguard Worker 
2855*795d594fSAndroid Build Coastguard Worker   // Create the header, leave 0 for data size since we will fill this in as we are writing the
2856*795d594fSAndroid Build Coastguard Worker   // image.
2857*795d594fSAndroid Build Coastguard Worker   new (image_info.image_.Begin()) ImageHeader(
2858*795d594fSAndroid Build Coastguard Worker       image_reservation_size,
2859*795d594fSAndroid Build Coastguard Worker       current_component_count,
2860*795d594fSAndroid Build Coastguard Worker       PointerToLowMemUInt32(image_info.image_begin_),
2861*795d594fSAndroid Build Coastguard Worker       image_end,
2862*795d594fSAndroid Build Coastguard Worker       sections.data(),
2863*795d594fSAndroid Build Coastguard Worker       image_info.image_roots_address_,
2864*795d594fSAndroid Build Coastguard Worker       image_info.oat_checksum_,
2865*795d594fSAndroid Build Coastguard Worker       PointerToLowMemUInt32(oat_file_begin),
2866*795d594fSAndroid Build Coastguard Worker       PointerToLowMemUInt32(image_info.oat_data_begin_),
2867*795d594fSAndroid Build Coastguard Worker       PointerToLowMemUInt32(oat_data_end),
2868*795d594fSAndroid Build Coastguard Worker       PointerToLowMemUInt32(oat_file_end),
2869*795d594fSAndroid Build Coastguard Worker       boot_image_begin_,
2870*795d594fSAndroid Build Coastguard Worker       boot_image_size_,
2871*795d594fSAndroid Build Coastguard Worker       boot_image_components,
2872*795d594fSAndroid Build Coastguard Worker       boot_image_checksums,
2873*795d594fSAndroid Build Coastguard Worker       target_ptr_size_);
2874*795d594fSAndroid Build Coastguard Worker }
2875*795d594fSAndroid Build Coastguard Worker 
GetImageMethodAddress(ArtMethod * method) const2876*795d594fSAndroid Build Coastguard Worker ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) const {
2877*795d594fSAndroid Build Coastguard Worker   NativeObjectRelocation relocation = GetNativeRelocation(method);
2878*795d594fSAndroid Build Coastguard Worker   const ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2879*795d594fSAndroid Build Coastguard Worker   CHECK_GE(relocation.offset, image_info.image_end_) << "ArtMethods should be after Objects";
2880*795d594fSAndroid Build Coastguard Worker   return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + relocation.offset);
2881*795d594fSAndroid Build Coastguard Worker }
2882*795d594fSAndroid Build Coastguard Worker 
GetIntrinsicReferenceAddress(uint32_t intrinsic_data)2883*795d594fSAndroid Build Coastguard Worker const void* ImageWriter::GetIntrinsicReferenceAddress(uint32_t intrinsic_data) {
2884*795d594fSAndroid Build Coastguard Worker   DCHECK(compiler_options_.IsBootImage());
2885*795d594fSAndroid Build Coastguard Worker   switch (IntrinsicObjects::DecodePatchType(intrinsic_data)) {
2886*795d594fSAndroid Build Coastguard Worker     case IntrinsicObjects::PatchType::kValueOfArray: {
2887*795d594fSAndroid Build Coastguard Worker       uint32_t index = IntrinsicObjects::DecodePatchIndex(intrinsic_data);
2888*795d594fSAndroid Build Coastguard Worker       const uint8_t* base_address =
2889*795d594fSAndroid Build Coastguard Worker           reinterpret_cast<const uint8_t*>(GetImageAddress(boot_image_live_objects_));
2890*795d594fSAndroid Build Coastguard Worker       MemberOffset data_offset =
2891*795d594fSAndroid Build Coastguard Worker           IntrinsicObjects::GetValueOfArrayDataOffset(boot_image_live_objects_, index);
2892*795d594fSAndroid Build Coastguard Worker       return base_address + data_offset.Uint32Value();
2893*795d594fSAndroid Build Coastguard Worker     }
2894*795d594fSAndroid Build Coastguard Worker     case IntrinsicObjects::PatchType::kValueOfObject: {
2895*795d594fSAndroid Build Coastguard Worker       uint32_t index = IntrinsicObjects::DecodePatchIndex(intrinsic_data);
2896*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Object> value = IntrinsicObjects::GetValueOfObject(boot_image_live_objects_,
2897*795d594fSAndroid Build Coastguard Worker                                                                         /* start_index= */ 0u,
2898*795d594fSAndroid Build Coastguard Worker                                                                         index);
2899*795d594fSAndroid Build Coastguard Worker       return GetImageAddress(value.Ptr());
2900*795d594fSAndroid Build Coastguard Worker     }
2901*795d594fSAndroid Build Coastguard Worker   }
2902*795d594fSAndroid Build Coastguard Worker   LOG(FATAL) << "UNREACHABLE";
2903*795d594fSAndroid Build Coastguard Worker   UNREACHABLE();
2904*795d594fSAndroid Build Coastguard Worker }
2905*795d594fSAndroid Build Coastguard Worker 
2906*795d594fSAndroid Build Coastguard Worker 
2907*795d594fSAndroid Build Coastguard Worker class ImageWriter::FixupRootVisitor : public RootVisitor {
2908*795d594fSAndroid Build Coastguard Worker  public:
FixupRootVisitor(ImageWriter * image_writer)2909*795d594fSAndroid Build Coastguard Worker   explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
2910*795d594fSAndroid Build Coastguard Worker   }
2911*795d594fSAndroid Build Coastguard Worker 
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info)2912*795d594fSAndroid Build Coastguard Worker   void VisitRoots([[maybe_unused]] mirror::Object*** roots,
2913*795d594fSAndroid Build Coastguard Worker                   [[maybe_unused]] size_t count,
2914*795d594fSAndroid Build Coastguard Worker                   [[maybe_unused]] const RootInfo& info) override
2915*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2916*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "Unsupported";
2917*795d594fSAndroid Build Coastguard Worker   }
2918*795d594fSAndroid Build Coastguard Worker 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info)2919*795d594fSAndroid Build Coastguard Worker   void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
2920*795d594fSAndroid Build Coastguard Worker                   size_t count,
2921*795d594fSAndroid Build Coastguard Worker                   [[maybe_unused]] const RootInfo& info) override
2922*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) {
2923*795d594fSAndroid Build Coastguard Worker     for (size_t i = 0; i < count; ++i) {
2924*795d594fSAndroid Build Coastguard Worker       // Copy the reference. Since we do not have the address for recording the relocation,
2925*795d594fSAndroid Build Coastguard Worker       // it needs to be recorded explicitly by the user of FixupRootVisitor.
2926*795d594fSAndroid Build Coastguard Worker       ObjPtr<mirror::Object> old_ptr = roots[i]->AsMirrorPtr();
2927*795d594fSAndroid Build Coastguard Worker       roots[i]->Assign(image_writer_->GetImageAddress(old_ptr.Ptr()));
2928*795d594fSAndroid Build Coastguard Worker     }
2929*795d594fSAndroid Build Coastguard Worker   }
2930*795d594fSAndroid Build Coastguard Worker 
2931*795d594fSAndroid Build Coastguard Worker  private:
2932*795d594fSAndroid Build Coastguard Worker   ImageWriter* const image_writer_;
2933*795d594fSAndroid Build Coastguard Worker };
2934*795d594fSAndroid Build Coastguard Worker 
CopyAndFixupImTable(ImTable * orig,ImTable * copy)2935*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
2936*795d594fSAndroid Build Coastguard Worker   for (size_t i = 0; i < ImTable::kSize; ++i) {
2937*795d594fSAndroid Build Coastguard Worker     ArtMethod* method = orig->Get(i, target_ptr_size_);
2938*795d594fSAndroid Build Coastguard Worker     void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
2939*795d594fSAndroid Build Coastguard Worker     CopyAndFixupPointer(address, method);
2940*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
2941*795d594fSAndroid Build Coastguard Worker   }
2942*795d594fSAndroid Build Coastguard Worker }
2943*795d594fSAndroid Build Coastguard Worker 
CopyAndFixupImtConflictTable(ImtConflictTable * orig,ImtConflictTable * copy)2944*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
2945*795d594fSAndroid Build Coastguard Worker   const size_t count = orig->NumEntries(target_ptr_size_);
2946*795d594fSAndroid Build Coastguard Worker   for (size_t i = 0; i < count; ++i) {
2947*795d594fSAndroid Build Coastguard Worker     ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
2948*795d594fSAndroid Build Coastguard Worker     ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
2949*795d594fSAndroid Build Coastguard Worker     CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
2950*795d594fSAndroid Build Coastguard Worker     CopyAndFixupPointer(
2951*795d594fSAndroid Build Coastguard Worker         copy->AddressOfImplementationMethod(i, target_ptr_size_), implementation_method);
2952*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
2953*795d594fSAndroid Build Coastguard Worker               NativeLocationInImage(interface_method));
2954*795d594fSAndroid Build Coastguard Worker     DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
2955*795d594fSAndroid Build Coastguard Worker               NativeLocationInImage(implementation_method));
2956*795d594fSAndroid Build Coastguard Worker   }
2957*795d594fSAndroid Build Coastguard Worker }
2958*795d594fSAndroid Build Coastguard Worker 
CopyAndFixupNativeData(size_t oat_index)2959*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
2960*795d594fSAndroid Build Coastguard Worker   const ImageInfo& image_info = GetImageInfo(oat_index);
2961*795d594fSAndroid Build Coastguard Worker   // Copy ArtFields and methods to their locations and update the array for convenience.
2962*795d594fSAndroid Build Coastguard Worker   for (auto& pair : native_object_relocations_) {
2963*795d594fSAndroid Build Coastguard Worker     NativeObjectRelocation& relocation = pair.second;
2964*795d594fSAndroid Build Coastguard Worker     // Only work with fields and methods that are in the current oat file.
2965*795d594fSAndroid Build Coastguard Worker     if (relocation.oat_index != oat_index) {
2966*795d594fSAndroid Build Coastguard Worker       continue;
2967*795d594fSAndroid Build Coastguard Worker     }
2968*795d594fSAndroid Build Coastguard Worker     auto* dest = image_info.image_.Begin() + relocation.offset;
2969*795d594fSAndroid Build Coastguard Worker     DCHECK_GE(dest, image_info.image_.Begin() + image_info.image_end_);
2970*795d594fSAndroid Build Coastguard Worker     DCHECK(!IsInBootImage(pair.first));
2971*795d594fSAndroid Build Coastguard Worker     switch (relocation.type) {
2972*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kRuntimeMethod:
2973*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kArtMethodClean:
2974*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kArtMethodDirty: {
2975*795d594fSAndroid Build Coastguard Worker         CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
2976*795d594fSAndroid Build Coastguard Worker                            reinterpret_cast<ArtMethod*>(dest),
2977*795d594fSAndroid Build Coastguard Worker                            oat_index);
2978*795d594fSAndroid Build Coastguard Worker         break;
2979*795d594fSAndroid Build Coastguard Worker       }
2980*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kArtFieldArray: {
2981*795d594fSAndroid Build Coastguard Worker         // Copy and fix up the entire field array.
2982*795d594fSAndroid Build Coastguard Worker         auto* src_array = reinterpret_cast<LengthPrefixedArray<ArtField>*>(pair.first);
2983*795d594fSAndroid Build Coastguard Worker         auto* dest_array = reinterpret_cast<LengthPrefixedArray<ArtField>*>(dest);
2984*795d594fSAndroid Build Coastguard Worker         size_t size = src_array->size();
2985*795d594fSAndroid Build Coastguard Worker         memcpy(dest_array, src_array, LengthPrefixedArray<ArtField>::ComputeSize(size));
2986*795d594fSAndroid Build Coastguard Worker         for (size_t i = 0; i != size; ++i) {
2987*795d594fSAndroid Build Coastguard Worker           CopyAndFixupReference(
2988*795d594fSAndroid Build Coastguard Worker               dest_array->At(i).GetDeclaringClassAddressWithoutBarrier(),
2989*795d594fSAndroid Build Coastguard Worker               src_array->At(i).GetDeclaringClass<kWithoutReadBarrier>());
2990*795d594fSAndroid Build Coastguard Worker         }
2991*795d594fSAndroid Build Coastguard Worker         break;
2992*795d594fSAndroid Build Coastguard Worker       }
2993*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kArtMethodArrayClean:
2994*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kArtMethodArrayDirty: {
2995*795d594fSAndroid Build Coastguard Worker         // For method arrays, copy just the header since the elements will
2996*795d594fSAndroid Build Coastguard Worker         // get copied by their corresponding relocations.
2997*795d594fSAndroid Build Coastguard Worker         size_t size = ArtMethod::Size(target_ptr_size_);
2998*795d594fSAndroid Build Coastguard Worker         size_t alignment = ArtMethod::Alignment(target_ptr_size_);
2999*795d594fSAndroid Build Coastguard Worker         memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
3000*795d594fSAndroid Build Coastguard Worker         // Clear padding to avoid non-deterministic data in the image.
3001*795d594fSAndroid Build Coastguard Worker         // Historical note: We also did that to placate Valgrind.
3002*795d594fSAndroid Build Coastguard Worker         reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
3003*795d594fSAndroid Build Coastguard Worker         break;
3004*795d594fSAndroid Build Coastguard Worker       }
3005*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kIMTable: {
3006*795d594fSAndroid Build Coastguard Worker         ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
3007*795d594fSAndroid Build Coastguard Worker         ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
3008*795d594fSAndroid Build Coastguard Worker         CopyAndFixupImTable(orig_imt, dest_imt);
3009*795d594fSAndroid Build Coastguard Worker         break;
3010*795d594fSAndroid Build Coastguard Worker       }
3011*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kIMTConflictTable: {
3012*795d594fSAndroid Build Coastguard Worker         auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
3013*795d594fSAndroid Build Coastguard Worker         CopyAndFixupImtConflictTable(
3014*795d594fSAndroid Build Coastguard Worker             orig_table,
3015*795d594fSAndroid Build Coastguard Worker             new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
3016*795d594fSAndroid Build Coastguard Worker         break;
3017*795d594fSAndroid Build Coastguard Worker       }
3018*795d594fSAndroid Build Coastguard Worker       case NativeObjectRelocationType::kGcRootPointer: {
3019*795d594fSAndroid Build Coastguard Worker         auto* orig_pointer = reinterpret_cast<GcRoot<mirror::Object>*>(pair.first);
3020*795d594fSAndroid Build Coastguard Worker         auto* dest_pointer = reinterpret_cast<GcRoot<mirror::Object>*>(dest);
3021*795d594fSAndroid Build Coastguard Worker         CopyAndFixupReference(dest_pointer->AddressWithoutBarrier(), orig_pointer->Read());
3022*795d594fSAndroid Build Coastguard Worker         break;
3023*795d594fSAndroid Build Coastguard Worker       }
3024*795d594fSAndroid Build Coastguard Worker     }
3025*795d594fSAndroid Build Coastguard Worker   }
3026*795d594fSAndroid Build Coastguard Worker   // Fixup the image method roots.
3027*795d594fSAndroid Build Coastguard Worker   auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_.Begin());
3028*795d594fSAndroid Build Coastguard Worker   for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
3029*795d594fSAndroid Build Coastguard Worker     ArtMethod* method = image_methods_[i];
3030*795d594fSAndroid Build Coastguard Worker     CHECK(method != nullptr);
3031*795d594fSAndroid Build Coastguard Worker     CopyAndFixupPointer(
3032*795d594fSAndroid Build Coastguard Worker         reinterpret_cast<void**>(&image_header->image_methods_[i]), method, PointerSize::k32);
3033*795d594fSAndroid Build Coastguard Worker   }
3034*795d594fSAndroid Build Coastguard Worker   FixupRootVisitor root_visitor(this);
3035*795d594fSAndroid Build Coastguard Worker 
3036*795d594fSAndroid Build Coastguard Worker   // Write the intern table into the image.
3037*795d594fSAndroid Build Coastguard Worker   if (image_info.intern_table_bytes_ > 0) {
3038*795d594fSAndroid Build Coastguard Worker     const ImageSection& intern_table_section = image_header->GetInternedStringsSection();
3039*795d594fSAndroid Build Coastguard Worker     DCHECK(image_info.intern_table_.has_value());
3040*795d594fSAndroid Build Coastguard Worker     const InternTable::UnorderedSet& intern_table = *image_info.intern_table_;
3041*795d594fSAndroid Build Coastguard Worker     uint8_t* const intern_table_memory_ptr =
3042*795d594fSAndroid Build Coastguard Worker         image_info.image_.Begin() + intern_table_section.Offset();
3043*795d594fSAndroid Build Coastguard Worker     const size_t intern_table_bytes = intern_table.WriteToMemory(intern_table_memory_ptr);
3044*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
3045*795d594fSAndroid Build Coastguard Worker     // Fixup the pointers in the newly written intern table to contain image addresses.
3046*795d594fSAndroid Build Coastguard Worker     InternTable temp_intern_table;
3047*795d594fSAndroid Build Coastguard Worker     // Note that we require that ReadFromMemory does not make an internal copy of the elements so
3048*795d594fSAndroid Build Coastguard Worker     // that the VisitRoots() will update the memory directly rather than the copies.
3049*795d594fSAndroid Build Coastguard Worker     // This also relies on visit roots not doing any verification which could fail after we update
3050*795d594fSAndroid Build Coastguard Worker     // the roots to be the image addresses.
3051*795d594fSAndroid Build Coastguard Worker     temp_intern_table.AddTableFromMemory(intern_table_memory_ptr,
3052*795d594fSAndroid Build Coastguard Worker                                          VoidFunctor(),
3053*795d594fSAndroid Build Coastguard Worker                                          /*is_boot_image=*/ false);
3054*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(temp_intern_table.Size(), intern_table.size());
3055*795d594fSAndroid Build Coastguard Worker     temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
3056*795d594fSAndroid Build Coastguard Worker 
3057*795d594fSAndroid Build Coastguard Worker     if (kIsDebugBuild) {
3058*795d594fSAndroid Build Coastguard Worker       MutexLock lock(Thread::Current(), *Locks::intern_table_lock_);
3059*795d594fSAndroid Build Coastguard Worker       CHECK(!temp_intern_table.strong_interns_.tables_.empty());
3060*795d594fSAndroid Build Coastguard Worker       // The UnorderedSet was inserted at the beginning.
3061*795d594fSAndroid Build Coastguard Worker       CHECK_EQ(temp_intern_table.strong_interns_.tables_[0].Size(), intern_table.size());
3062*795d594fSAndroid Build Coastguard Worker     }
3063*795d594fSAndroid Build Coastguard Worker   }
3064*795d594fSAndroid Build Coastguard Worker 
3065*795d594fSAndroid Build Coastguard Worker   // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
3066*795d594fSAndroid Build Coastguard Worker   // class loaders. Writing multiple class tables into the image is currently unsupported.
3067*795d594fSAndroid Build Coastguard Worker   if (image_info.class_table_bytes_ > 0u) {
3068*795d594fSAndroid Build Coastguard Worker     const ImageSection& class_table_section = image_header->GetClassTableSection();
3069*795d594fSAndroid Build Coastguard Worker     uint8_t* const class_table_memory_ptr =
3070*795d594fSAndroid Build Coastguard Worker         image_info.image_.Begin() + class_table_section.Offset();
3071*795d594fSAndroid Build Coastguard Worker 
3072*795d594fSAndroid Build Coastguard Worker     DCHECK(image_info.class_table_.has_value());
3073*795d594fSAndroid Build Coastguard Worker     const ClassTable::ClassSet& table = *image_info.class_table_;
3074*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(table.size(), image_info.class_table_size_);
3075*795d594fSAndroid Build Coastguard Worker     const size_t class_table_bytes = table.WriteToMemory(class_table_memory_ptr);
3076*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
3077*795d594fSAndroid Build Coastguard Worker 
3078*795d594fSAndroid Build Coastguard Worker     // Fixup the pointers in the newly written class table to contain image addresses. See
3079*795d594fSAndroid Build Coastguard Worker     // above comment for intern tables.
3080*795d594fSAndroid Build Coastguard Worker     ClassTable temp_class_table;
3081*795d594fSAndroid Build Coastguard Worker     temp_class_table.ReadFromMemory(class_table_memory_ptr);
3082*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(), table.size());
3083*795d594fSAndroid Build Coastguard Worker     UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
3084*795d594fSAndroid Build Coastguard Worker     temp_class_table.VisitRoots(visitor);
3085*795d594fSAndroid Build Coastguard Worker 
3086*795d594fSAndroid Build Coastguard Worker     if (kIsDebugBuild) {
3087*795d594fSAndroid Build Coastguard Worker       ReaderMutexLock lock(Thread::Current(), temp_class_table.lock_);
3088*795d594fSAndroid Build Coastguard Worker       CHECK(!temp_class_table.classes_.empty());
3089*795d594fSAndroid Build Coastguard Worker       // The ClassSet was inserted at the beginning.
3090*795d594fSAndroid Build Coastguard Worker       CHECK_EQ(temp_class_table.classes_[0].size(), table.size());
3091*795d594fSAndroid Build Coastguard Worker     }
3092*795d594fSAndroid Build Coastguard Worker   }
3093*795d594fSAndroid Build Coastguard Worker }
3094*795d594fSAndroid Build Coastguard Worker 
CopyAndFixupJniStubMethods(size_t oat_index)3095*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupJniStubMethods(size_t oat_index) {
3096*795d594fSAndroid Build Coastguard Worker   const ImageInfo& image_info = GetImageInfo(oat_index);
3097*795d594fSAndroid Build Coastguard Worker   // Copy method's address to JniStubMethods section.
3098*795d594fSAndroid Build Coastguard Worker   for (auto& pair : jni_stub_map_) {
3099*795d594fSAndroid Build Coastguard Worker     JniStubMethodRelocation& relocation = pair.second.second;
3100*795d594fSAndroid Build Coastguard Worker     // Only work with JNI stubs that are in the current oat file.
3101*795d594fSAndroid Build Coastguard Worker     if (relocation.oat_index != oat_index) {
3102*795d594fSAndroid Build Coastguard Worker       continue;
3103*795d594fSAndroid Build Coastguard Worker     }
3104*795d594fSAndroid Build Coastguard Worker     void** address = reinterpret_cast<void**>(image_info.image_.Begin() + relocation.offset);
3105*795d594fSAndroid Build Coastguard Worker     ArtMethod* method = pair.second.first;
3106*795d594fSAndroid Build Coastguard Worker     CopyAndFixupPointer(address, method);
3107*795d594fSAndroid Build Coastguard Worker   }
3108*795d594fSAndroid Build Coastguard Worker }
3109*795d594fSAndroid Build Coastguard Worker 
CopyAndFixupMethodPointerArray(mirror::PointerArray * arr)3110*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupMethodPointerArray(mirror::PointerArray* arr) {
3111*795d594fSAndroid Build Coastguard Worker   // Pointer arrays are processed early and each is visited just once.
3112*795d594fSAndroid Build Coastguard Worker   // Therefore we know that this array has not been copied yet.
3113*795d594fSAndroid Build Coastguard Worker   mirror::Object* dst = CopyObject</*kCheckIfDone=*/ false>(arr);
3114*795d594fSAndroid Build Coastguard Worker   DCHECK(dst != nullptr);
3115*795d594fSAndroid Build Coastguard Worker   DCHECK(arr->IsIntArray() || arr->IsLongArray())
3116*795d594fSAndroid Build Coastguard Worker       << arr->GetClass<kVerifyNone, kWithoutReadBarrier>()->PrettyClass() << " " << arr;
3117*795d594fSAndroid Build Coastguard Worker   // Fixup int and long pointers for the ArtMethod or ArtField arrays.
3118*795d594fSAndroid Build Coastguard Worker   const size_t num_elements = arr->GetLength();
3119*795d594fSAndroid Build Coastguard Worker   CopyAndFixupReference(dst->GetFieldObjectReferenceAddr<kVerifyNone>(Class::ClassOffset()),
3120*795d594fSAndroid Build Coastguard Worker                         arr->GetClass<kVerifyNone, kWithoutReadBarrier>());
3121*795d594fSAndroid Build Coastguard Worker   auto* dest_array = down_cast<mirror::PointerArray*>(dst);
3122*795d594fSAndroid Build Coastguard Worker   for (size_t i = 0, count = num_elements; i < count; ++i) {
3123*795d594fSAndroid Build Coastguard Worker     void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
3124*795d594fSAndroid Build Coastguard Worker     if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
3125*795d594fSAndroid Build Coastguard Worker       auto it = native_object_relocations_.find(elem);
3126*795d594fSAndroid Build Coastguard Worker       if (UNLIKELY(it == native_object_relocations_.end())) {
3127*795d594fSAndroid Build Coastguard Worker         auto* method = reinterpret_cast<ArtMethod*>(elem);
3128*795d594fSAndroid Build Coastguard Worker         LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
3129*795d594fSAndroid Build Coastguard Worker                    << method << " idx=" << i << "/" << num_elements << " with declaring class "
3130*795d594fSAndroid Build Coastguard Worker                    << Class::PrettyClass(method->GetDeclaringClass<kWithoutReadBarrier>());
3131*795d594fSAndroid Build Coastguard Worker         UNREACHABLE();
3132*795d594fSAndroid Build Coastguard Worker       }
3133*795d594fSAndroid Build Coastguard Worker     }
3134*795d594fSAndroid Build Coastguard Worker     CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
3135*795d594fSAndroid Build Coastguard Worker   }
3136*795d594fSAndroid Build Coastguard Worker }
3137*795d594fSAndroid Build Coastguard Worker 
CopyAndFixupObject(Object * obj)3138*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupObject(Object* obj) {
3139*795d594fSAndroid Build Coastguard Worker   if (!IsImageBinSlotAssigned(obj)) {
3140*795d594fSAndroid Build Coastguard Worker     return;
3141*795d594fSAndroid Build Coastguard Worker   }
3142*795d594fSAndroid Build Coastguard Worker   // Some objects (such as method pointer arrays) may have been processed before.
3143*795d594fSAndroid Build Coastguard Worker   mirror::Object* dst = CopyObject</*kCheckIfDone=*/ true>(obj);
3144*795d594fSAndroid Build Coastguard Worker   if (dst != nullptr) {
3145*795d594fSAndroid Build Coastguard Worker     FixupObject(obj, dst);
3146*795d594fSAndroid Build Coastguard Worker   }
3147*795d594fSAndroid Build Coastguard Worker }
3148*795d594fSAndroid Build Coastguard Worker 
3149*795d594fSAndroid Build Coastguard Worker template <bool kCheckIfDone>
CopyObject(Object * obj)3150*795d594fSAndroid Build Coastguard Worker inline Object* ImageWriter::CopyObject(Object* obj) {
3151*795d594fSAndroid Build Coastguard Worker   size_t oat_index = GetOatIndex(obj);
3152*795d594fSAndroid Build Coastguard Worker   size_t offset = GetImageOffset(obj, oat_index);
3153*795d594fSAndroid Build Coastguard Worker   ImageInfo& image_info = GetImageInfo(oat_index);
3154*795d594fSAndroid Build Coastguard Worker   auto* dst = reinterpret_cast<Object*>(image_info.image_.Begin() + offset);
3155*795d594fSAndroid Build Coastguard Worker   DCHECK_LT(offset, image_info.image_end_);
3156*795d594fSAndroid Build Coastguard Worker   const auto* src = reinterpret_cast<const uint8_t*>(obj);
3157*795d594fSAndroid Build Coastguard Worker 
3158*795d594fSAndroid Build Coastguard Worker   bool done = image_info.image_bitmap_.Set(dst);  // Mark the obj as live.
3159*795d594fSAndroid Build Coastguard Worker   // Check if the object was already copied, unless the caller indicated that it was not.
3160*795d594fSAndroid Build Coastguard Worker   if (kCheckIfDone && done) {
3161*795d594fSAndroid Build Coastguard Worker     return nullptr;
3162*795d594fSAndroid Build Coastguard Worker   }
3163*795d594fSAndroid Build Coastguard Worker   DCHECK(!done);
3164*795d594fSAndroid Build Coastguard Worker 
3165*795d594fSAndroid Build Coastguard Worker   const size_t n = obj->SizeOf();
3166*795d594fSAndroid Build Coastguard Worker 
3167*795d594fSAndroid Build Coastguard Worker   if (kIsDebugBuild && region_size_ != 0u) {
3168*795d594fSAndroid Build Coastguard Worker     const size_t offset_after_header = offset - sizeof(ImageHeader);
3169*795d594fSAndroid Build Coastguard Worker     const size_t next_region = RoundUp(offset_after_header, region_size_);
3170*795d594fSAndroid Build Coastguard Worker     if (offset_after_header != next_region) {
3171*795d594fSAndroid Build Coastguard Worker       // If the object is not on a region bondary, it must not be cross region.
3172*795d594fSAndroid Build Coastguard Worker       CHECK_LT(offset_after_header, next_region)
3173*795d594fSAndroid Build Coastguard Worker           << "offset_after_header=" << offset_after_header << " size=" << n;
3174*795d594fSAndroid Build Coastguard Worker       CHECK_LE(offset_after_header + n, next_region)
3175*795d594fSAndroid Build Coastguard Worker           << "offset_after_header=" << offset_after_header << " size=" << n;
3176*795d594fSAndroid Build Coastguard Worker     }
3177*795d594fSAndroid Build Coastguard Worker   }
3178*795d594fSAndroid Build Coastguard Worker   DCHECK_LE(offset + n, image_info.image_.Size());
3179*795d594fSAndroid Build Coastguard Worker   memcpy(dst, src, n);
3180*795d594fSAndroid Build Coastguard Worker 
3181*795d594fSAndroid Build Coastguard Worker   // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
3182*795d594fSAndroid Build Coastguard Worker   // word.
3183*795d594fSAndroid Build Coastguard Worker   const auto it = saved_hashcode_map_.find(obj);
3184*795d594fSAndroid Build Coastguard Worker   dst->SetLockWord(it != saved_hashcode_map_.end() ?
3185*795d594fSAndroid Build Coastguard Worker       LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
3186*795d594fSAndroid Build Coastguard Worker   if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
3187*795d594fSAndroid Build Coastguard Worker     // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
3188*795d594fSAndroid Build Coastguard Worker     // safe since we mark all of the objects that may reference non immune objects as gray.
3189*795d594fSAndroid Build Coastguard Worker     CHECK(dst->AtomicSetMarkBit(0, 1));
3190*795d594fSAndroid Build Coastguard Worker   }
3191*795d594fSAndroid Build Coastguard Worker   return dst;
3192*795d594fSAndroid Build Coastguard Worker }
3193*795d594fSAndroid Build Coastguard Worker 
3194*795d594fSAndroid Build Coastguard Worker // Rewrite all the references in the copied object to point to their image address equivalent
3195*795d594fSAndroid Build Coastguard Worker class ImageWriter::FixupVisitor {
3196*795d594fSAndroid Build Coastguard Worker  public:
FixupVisitor(ImageWriter * image_writer,Object * copy)3197*795d594fSAndroid Build Coastguard Worker   FixupVisitor(ImageWriter* image_writer, Object* copy)
3198*795d594fSAndroid Build Coastguard Worker       : image_writer_(image_writer), copy_(copy) {
3199*795d594fSAndroid Build Coastguard Worker   }
3200*795d594fSAndroid Build Coastguard Worker 
3201*795d594fSAndroid Build Coastguard Worker   // We do not visit native roots. These are handled with other logic.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const3202*795d594fSAndroid Build Coastguard Worker   void VisitRootIfNonNull(
3203*795d594fSAndroid Build Coastguard Worker       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {
3204*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "UNREACHABLE";
3205*795d594fSAndroid Build Coastguard Worker   }
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const3206*795d594fSAndroid Build Coastguard Worker   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {
3207*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "UNREACHABLE";
3208*795d594fSAndroid Build Coastguard Worker   }
3209*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<Object> obj,MemberOffset offset,bool is_static) const3210*795d594fSAndroid Build Coastguard Worker   void operator()(ObjPtr<Object> obj, MemberOffset offset, [[maybe_unused]] bool is_static) const
3211*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
3212*795d594fSAndroid Build Coastguard Worker     ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone, kWithoutReadBarrier>(offset);
3213*795d594fSAndroid Build Coastguard Worker     // Copy the reference and record the fixup if necessary.
3214*795d594fSAndroid Build Coastguard Worker     image_writer_->CopyAndFixupReference(
3215*795d594fSAndroid Build Coastguard Worker         copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset), ref);
3216*795d594fSAndroid Build Coastguard Worker   }
3217*795d594fSAndroid Build Coastguard Worker 
3218*795d594fSAndroid Build Coastguard Worker   // java.lang.ref.Reference visitor.
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const3219*795d594fSAndroid Build Coastguard Worker   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
3220*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
3221*795d594fSAndroid Build Coastguard Worker     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
3222*795d594fSAndroid Build Coastguard Worker   }
3223*795d594fSAndroid Build Coastguard Worker 
3224*795d594fSAndroid Build Coastguard Worker  protected:
3225*795d594fSAndroid Build Coastguard Worker   ImageWriter* const image_writer_;
3226*795d594fSAndroid Build Coastguard Worker   mirror::Object* const copy_;
3227*795d594fSAndroid Build Coastguard Worker };
3228*795d594fSAndroid Build Coastguard Worker 
CopyAndFixupObjects()3229*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupObjects() {
3230*795d594fSAndroid Build Coastguard Worker   // Copy and fix up pointer arrays first as they require special treatment.
3231*795d594fSAndroid Build Coastguard Worker   auto method_pointer_array_visitor =
3232*795d594fSAndroid Build Coastguard Worker       [&](ObjPtr<mirror::PointerArray> pointer_array) REQUIRES_SHARED(Locks::mutator_lock_) {
3233*795d594fSAndroid Build Coastguard Worker         CopyAndFixupMethodPointerArray(pointer_array.Ptr());
3234*795d594fSAndroid Build Coastguard Worker       };
3235*795d594fSAndroid Build Coastguard Worker   for (ImageInfo& image_info : image_infos_) {
3236*795d594fSAndroid Build Coastguard Worker     if (image_info.class_table_size_ != 0u) {
3237*795d594fSAndroid Build Coastguard Worker       DCHECK(image_info.class_table_.has_value());
3238*795d594fSAndroid Build Coastguard Worker       for (const ClassTable::TableSlot& slot : *image_info.class_table_) {
3239*795d594fSAndroid Build Coastguard Worker         ObjPtr<mirror::Class> klass = slot.Read<kWithoutReadBarrier>();
3240*795d594fSAndroid Build Coastguard Worker         DCHECK(klass != nullptr);
3241*795d594fSAndroid Build Coastguard Worker         // Do not process boot image classes present in app image class table.
3242*795d594fSAndroid Build Coastguard Worker         DCHECK(!IsInBootImage(klass.Ptr()) || compiler_options_.IsAppImage());
3243*795d594fSAndroid Build Coastguard Worker         if (!IsInBootImage(klass.Ptr())) {
3244*795d594fSAndroid Build Coastguard Worker           // Do not fix up method pointer arrays inherited from superclass. If they are part
3245*795d594fSAndroid Build Coastguard Worker           // of the current image, they were or shall be copied when visiting the superclass.
3246*795d594fSAndroid Build Coastguard Worker           VisitNewMethodPointerArrays(klass, method_pointer_array_visitor);
3247*795d594fSAndroid Build Coastguard Worker         }
3248*795d594fSAndroid Build Coastguard Worker       }
3249*795d594fSAndroid Build Coastguard Worker     }
3250*795d594fSAndroid Build Coastguard Worker   }
3251*795d594fSAndroid Build Coastguard Worker 
3252*795d594fSAndroid Build Coastguard Worker   auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
3253*795d594fSAndroid Build Coastguard Worker     DCHECK(obj != nullptr);
3254*795d594fSAndroid Build Coastguard Worker     CopyAndFixupObject(obj);
3255*795d594fSAndroid Build Coastguard Worker   };
3256*795d594fSAndroid Build Coastguard Worker   Runtime::Current()->GetHeap()->VisitObjects(visitor);
3257*795d594fSAndroid Build Coastguard Worker 
3258*795d594fSAndroid Build Coastguard Worker   // Fill the padding objects since they are required for in order traversal of the image space.
3259*795d594fSAndroid Build Coastguard Worker   for (ImageInfo& image_info : image_infos_) {
3260*795d594fSAndroid Build Coastguard Worker     for (const size_t start_offset : image_info.padding_offsets_) {
3261*795d594fSAndroid Build Coastguard Worker       const size_t offset_after_header = start_offset - sizeof(ImageHeader);
3262*795d594fSAndroid Build Coastguard Worker       size_t remaining_space =
3263*795d594fSAndroid Build Coastguard Worker           RoundUp(offset_after_header + 1u, region_size_) - offset_after_header;
3264*795d594fSAndroid Build Coastguard Worker       DCHECK_NE(remaining_space, 0u);
3265*795d594fSAndroid Build Coastguard Worker       DCHECK_LT(remaining_space, region_size_);
3266*795d594fSAndroid Build Coastguard Worker       Object* dst = reinterpret_cast<Object*>(image_info.image_.Begin() + start_offset);
3267*795d594fSAndroid Build Coastguard Worker       ObjPtr<Class> object_class = GetClassRoot<mirror::Object, kWithoutReadBarrier>();
3268*795d594fSAndroid Build Coastguard Worker       DCHECK_ALIGNED_PARAM(remaining_space, object_class->GetObjectSize());
3269*795d594fSAndroid Build Coastguard Worker       Object* end = dst + remaining_space / object_class->GetObjectSize();
3270*795d594fSAndroid Build Coastguard Worker       Class* image_object_class = GetImageAddress(object_class.Ptr());
3271*795d594fSAndroid Build Coastguard Worker       while (dst != end) {
3272*795d594fSAndroid Build Coastguard Worker         dst->SetClass<kVerifyNone>(image_object_class);
3273*795d594fSAndroid Build Coastguard Worker         dst->SetLockWord<kVerifyNone>(LockWord::Default(), /*as_volatile=*/ false);
3274*795d594fSAndroid Build Coastguard Worker         image_info.image_bitmap_.Set(dst);  // Mark the obj as live.
3275*795d594fSAndroid Build Coastguard Worker         ++dst;
3276*795d594fSAndroid Build Coastguard Worker       }
3277*795d594fSAndroid Build Coastguard Worker     }
3278*795d594fSAndroid Build Coastguard Worker   }
3279*795d594fSAndroid Build Coastguard Worker 
3280*795d594fSAndroid Build Coastguard Worker   // We no longer need the hashcode map, values have already been copied to target objects.
3281*795d594fSAndroid Build Coastguard Worker   saved_hashcode_map_.clear();
3282*795d594fSAndroid Build Coastguard Worker }
3283*795d594fSAndroid Build Coastguard Worker 
3284*795d594fSAndroid Build Coastguard Worker class ImageWriter::FixupClassVisitor final : public FixupVisitor {
3285*795d594fSAndroid Build Coastguard Worker  public:
FixupClassVisitor(ImageWriter * image_writer,Object * copy)3286*795d594fSAndroid Build Coastguard Worker   FixupClassVisitor(ImageWriter* image_writer, Object* copy)
3287*795d594fSAndroid Build Coastguard Worker       : FixupVisitor(image_writer, copy) {}
3288*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<Object> obj,MemberOffset offset,bool is_static) const3289*795d594fSAndroid Build Coastguard Worker   void operator()(ObjPtr<Object> obj, MemberOffset offset, [[maybe_unused]] bool is_static) const
3290*795d594fSAndroid Build Coastguard Worker       REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
3291*795d594fSAndroid Build Coastguard Worker     DCHECK(obj->IsClass());
3292*795d594fSAndroid Build Coastguard Worker     FixupVisitor::operator()(obj, offset, /*is_static*/false);
3293*795d594fSAndroid Build Coastguard Worker   }
3294*795d594fSAndroid Build Coastguard Worker 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const3295*795d594fSAndroid Build Coastguard Worker   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass,
3296*795d594fSAndroid Build Coastguard Worker                   [[maybe_unused]] ObjPtr<mirror::Reference> ref) const
3297*795d594fSAndroid Build Coastguard Worker       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
3298*795d594fSAndroid Build Coastguard Worker     LOG(FATAL) << "Reference not expected here.";
3299*795d594fSAndroid Build Coastguard Worker   }
3300*795d594fSAndroid Build Coastguard Worker };
3301*795d594fSAndroid Build Coastguard Worker 
GetNativeRelocation(void * obj) const3302*795d594fSAndroid Build Coastguard Worker ImageWriter::NativeObjectRelocation ImageWriter::GetNativeRelocation(void* obj) const {
3303*795d594fSAndroid Build Coastguard Worker   DCHECK(obj != nullptr);
3304*795d594fSAndroid Build Coastguard Worker   DCHECK(!IsInBootImage(obj));
3305*795d594fSAndroid Build Coastguard Worker   auto it = native_object_relocations_.find(obj);
3306*795d594fSAndroid Build Coastguard Worker   CHECK(it != native_object_relocations_.end()) << obj << " spaces "
3307*795d594fSAndroid Build Coastguard Worker       << Runtime::Current()->GetHeap()->DumpSpaces();
3308*795d594fSAndroid Build Coastguard Worker   return it->second;
3309*795d594fSAndroid Build Coastguard Worker }
3310*795d594fSAndroid Build Coastguard Worker 
3311*795d594fSAndroid Build Coastguard Worker template <typename T>
PrettyPrint(T * ptr)3312*795d594fSAndroid Build Coastguard Worker std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
3313*795d594fSAndroid Build Coastguard Worker   std::ostringstream oss;
3314*795d594fSAndroid Build Coastguard Worker   oss << ptr;
3315*795d594fSAndroid Build Coastguard Worker   return oss.str();
3316*795d594fSAndroid Build Coastguard Worker }
3317*795d594fSAndroid Build Coastguard Worker 
3318*795d594fSAndroid Build Coastguard Worker template <>
PrettyPrint(ArtMethod * method)3319*795d594fSAndroid Build Coastguard Worker std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
3320*795d594fSAndroid Build Coastguard Worker   return ArtMethod::PrettyMethod(method);
3321*795d594fSAndroid Build Coastguard Worker }
3322*795d594fSAndroid Build Coastguard Worker 
3323*795d594fSAndroid Build Coastguard Worker template <typename T>
NativeLocationInImage(T * obj)3324*795d594fSAndroid Build Coastguard Worker T* ImageWriter::NativeLocationInImage(T* obj) {
3325*795d594fSAndroid Build Coastguard Worker   if (obj == nullptr || IsInBootImage(obj)) {
3326*795d594fSAndroid Build Coastguard Worker     return obj;
3327*795d594fSAndroid Build Coastguard Worker   } else {
3328*795d594fSAndroid Build Coastguard Worker     NativeObjectRelocation relocation = GetNativeRelocation(obj);
3329*795d594fSAndroid Build Coastguard Worker     const ImageInfo& image_info = GetImageInfo(relocation.oat_index);
3330*795d594fSAndroid Build Coastguard Worker     return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
3331*795d594fSAndroid Build Coastguard Worker   }
3332*795d594fSAndroid Build Coastguard Worker }
3333*795d594fSAndroid Build Coastguard Worker 
NativeLocationInImage(ArtField * src_field)3334*795d594fSAndroid Build Coastguard Worker ArtField* ImageWriter::NativeLocationInImage(ArtField* src_field) {
3335*795d594fSAndroid Build Coastguard Worker   // Fields are not individually stored in the native relocation map. Use the field array.
3336*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::Class> declaring_class = src_field->GetDeclaringClass<kWithoutReadBarrier>();
3337*795d594fSAndroid Build Coastguard Worker   LengthPrefixedArray<ArtField>* src_fields =
3338*795d594fSAndroid Build Coastguard Worker       src_field->IsStatic() ? declaring_class->GetSFieldsPtr() : declaring_class->GetIFieldsPtr();
3339*795d594fSAndroid Build Coastguard Worker   DCHECK(src_fields != nullptr);
3340*795d594fSAndroid Build Coastguard Worker   LengthPrefixedArray<ArtField>* dst_fields = NativeLocationInImage(src_fields);
3341*795d594fSAndroid Build Coastguard Worker   DCHECK(dst_fields != nullptr);
3342*795d594fSAndroid Build Coastguard Worker   size_t field_offset =
3343*795d594fSAndroid Build Coastguard Worker       reinterpret_cast<uint8_t*>(src_field) - reinterpret_cast<uint8_t*>(src_fields);
3344*795d594fSAndroid Build Coastguard Worker   return reinterpret_cast<ArtField*>(reinterpret_cast<uint8_t*>(dst_fields) + field_offset);
3345*795d594fSAndroid Build Coastguard Worker }
3346*795d594fSAndroid Build Coastguard Worker 
3347*795d594fSAndroid Build Coastguard Worker class ImageWriter::NativeLocationVisitor {
3348*795d594fSAndroid Build Coastguard Worker  public:
NativeLocationVisitor(ImageWriter * image_writer)3349*795d594fSAndroid Build Coastguard Worker   explicit NativeLocationVisitor(ImageWriter* image_writer)
3350*795d594fSAndroid Build Coastguard Worker       : image_writer_(image_writer) {}
3351*795d594fSAndroid Build Coastguard Worker 
3352*795d594fSAndroid Build Coastguard Worker   template <typename T>
operator ()(T * ptr,void ** dest_addr) const3353*795d594fSAndroid Build Coastguard Worker   T* operator()(T* ptr, void** dest_addr) const REQUIRES_SHARED(Locks::mutator_lock_) {
3354*795d594fSAndroid Build Coastguard Worker     if (ptr != nullptr) {
3355*795d594fSAndroid Build Coastguard Worker       image_writer_->CopyAndFixupPointer(dest_addr, ptr);
3356*795d594fSAndroid Build Coastguard Worker     }
3357*795d594fSAndroid Build Coastguard Worker     // TODO: The caller shall overwrite the value stored by CopyAndFixupPointer()
3358*795d594fSAndroid Build Coastguard Worker     // with the value we return here. We should try to avoid the duplicate work.
3359*795d594fSAndroid Build Coastguard Worker     return image_writer_->NativeLocationInImage(ptr);
3360*795d594fSAndroid Build Coastguard Worker   }
3361*795d594fSAndroid Build Coastguard Worker 
3362*795d594fSAndroid Build Coastguard Worker  private:
3363*795d594fSAndroid Build Coastguard Worker   ImageWriter* const image_writer_;
3364*795d594fSAndroid Build Coastguard Worker };
3365*795d594fSAndroid Build Coastguard Worker 
FixupClass(mirror::Class * orig,mirror::Class * copy)3366*795d594fSAndroid Build Coastguard Worker void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
3367*795d594fSAndroid Build Coastguard Worker   orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
3368*795d594fSAndroid Build Coastguard Worker   FixupClassVisitor visitor(this, copy);
3369*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::Object>(orig)->VisitReferences<
3370*795d594fSAndroid Build Coastguard Worker       /*kVisitNativeRoots=*/ false, kVerifyNone, kWithoutReadBarrier>(visitor, visitor);
3371*795d594fSAndroid Build Coastguard Worker 
3372*795d594fSAndroid Build Coastguard Worker   if (kBitstringSubtypeCheckEnabled && !compiler_options_.IsBootImage()) {
3373*795d594fSAndroid Build Coastguard Worker     // When we call SubtypeCheck::EnsureInitialize, it Assigns new bitstring
3374*795d594fSAndroid Build Coastguard Worker     // values to the parent of that class.
3375*795d594fSAndroid Build Coastguard Worker     //
3376*795d594fSAndroid Build Coastguard Worker     // Every time this happens, the parent class has to mutate to increment
3377*795d594fSAndroid Build Coastguard Worker     // the "Next" value.
3378*795d594fSAndroid Build Coastguard Worker     //
3379*795d594fSAndroid Build Coastguard Worker     // If any of these parents are in the boot image, the changes [in the parents]
3380*795d594fSAndroid Build Coastguard Worker     // would be lost when the app image is reloaded.
3381*795d594fSAndroid Build Coastguard Worker     //
3382*795d594fSAndroid Build Coastguard Worker     // To prevent newly loaded classes (not in the app image) from being reassigned
3383*795d594fSAndroid Build Coastguard Worker     // the same bitstring value as an existing app image class, uninitialize
3384*795d594fSAndroid Build Coastguard Worker     // all the classes in the app image.
3385*795d594fSAndroid Build Coastguard Worker     //
3386*795d594fSAndroid Build Coastguard Worker     // On startup, the class linker will then re-initialize all the app
3387*795d594fSAndroid Build Coastguard Worker     // image bitstrings. See also ClassLinker::AddImageSpace.
3388*795d594fSAndroid Build Coastguard Worker     //
3389*795d594fSAndroid Build Coastguard Worker     // FIXME: Deal with boot image extensions.
3390*795d594fSAndroid Build Coastguard Worker     MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
3391*795d594fSAndroid Build Coastguard Worker     // Lock every time to prevent a dcheck failure when we suspend with the lock held.
3392*795d594fSAndroid Build Coastguard Worker     SubtypeCheck<mirror::Class*>::ForceUninitialize(copy);
3393*795d594fSAndroid Build Coastguard Worker   }
3394*795d594fSAndroid Build Coastguard Worker 
3395*795d594fSAndroid Build Coastguard Worker   // Remove the clinitThreadId. This is required for image determinism.
3396*795d594fSAndroid Build Coastguard Worker   copy->SetClinitThreadId(static_cast<pid_t>(0));
3397*795d594fSAndroid Build Coastguard Worker   // We never emit kRetryVerificationAtRuntime, instead we mark the class as
3398*795d594fSAndroid Build Coastguard Worker   // resolved and the class will therefore be re-verified at runtime.
3399*795d594fSAndroid Build Coastguard Worker   if (orig->ShouldVerifyAtRuntime()) {
3400*795d594fSAndroid Build Coastguard Worker     copy->SetStatusInternal(ClassStatus::kResolved);
3401*795d594fSAndroid Build Coastguard Worker   }
3402*795d594fSAndroid Build Coastguard Worker }
3403*795d594fSAndroid Build Coastguard Worker 
FixupObject(Object * orig,Object * copy)3404*795d594fSAndroid Build Coastguard Worker void ImageWriter::FixupObject(Object* orig, Object* copy) {
3405*795d594fSAndroid Build Coastguard Worker   DCHECK(orig != nullptr);
3406*795d594fSAndroid Build Coastguard Worker   DCHECK(copy != nullptr);
3407*795d594fSAndroid Build Coastguard Worker   if (kUseBakerReadBarrier) {
3408*795d594fSAndroid Build Coastguard Worker     orig->AssertReadBarrierState();
3409*795d594fSAndroid Build Coastguard Worker   }
3410*795d594fSAndroid Build Coastguard Worker   ObjPtr<mirror::Class> klass = orig->GetClass<kVerifyNone, kWithoutReadBarrier>();
3411*795d594fSAndroid Build Coastguard Worker   if (klass->IsClassClass()) {
3412*795d594fSAndroid Build Coastguard Worker     FixupClass(orig->AsClass<kVerifyNone>().Ptr(), down_cast<mirror::Class*>(copy));
3413*795d594fSAndroid Build Coastguard Worker   } else {
3414*795d594fSAndroid Build Coastguard Worker     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
3415*795d594fSAndroid Build Coastguard Worker         Runtime::Current()->GetClassLinker()->GetClassRoots<kWithoutReadBarrier>();
3416*795d594fSAndroid Build Coastguard Worker     if (klass == GetClassRoot<mirror::String, kWithoutReadBarrier>(class_roots)) {
3417*795d594fSAndroid Build Coastguard Worker       // Make sure all image strings have the hash code calculated, even if they are not interned.
3418*795d594fSAndroid Build Coastguard Worker       down_cast<mirror::String*>(copy)->GetHashCode();
3419*795d594fSAndroid Build Coastguard Worker     } else if (klass == GetClassRoot<mirror::Method, kWithoutReadBarrier>(class_roots) ||
3420*795d594fSAndroid Build Coastguard Worker         klass == GetClassRoot<mirror::Constructor, kWithoutReadBarrier>(class_roots)) {
3421*795d594fSAndroid Build Coastguard Worker       // Need to update the ArtMethod.
3422*795d594fSAndroid Build Coastguard Worker       auto* dest = down_cast<mirror::Executable*>(copy);
3423*795d594fSAndroid Build Coastguard Worker       auto* src = down_cast<mirror::Executable*>(orig);
3424*795d594fSAndroid Build Coastguard Worker       ArtMethod* src_method = src->GetArtMethod();
3425*795d594fSAndroid Build Coastguard Worker       CopyAndFixupPointer(dest, mirror::Executable::ArtMethodOffset(), src_method);
3426*795d594fSAndroid Build Coastguard Worker     } else if (klass == GetClassRoot<mirror::FieldVarHandle, kWithoutReadBarrier>(class_roots) ||
3427*795d594fSAndroid Build Coastguard Worker          klass == GetClassRoot<mirror::StaticFieldVarHandle, kWithoutReadBarrier>(class_roots)) {
3428*795d594fSAndroid Build Coastguard Worker       // Need to update the ArtField.
3429*795d594fSAndroid Build Coastguard Worker       auto* dest = down_cast<mirror::FieldVarHandle*>(copy);
3430*795d594fSAndroid Build Coastguard Worker       auto* src = down_cast<mirror::FieldVarHandle*>(orig);
3431*795d594fSAndroid Build Coastguard Worker       ArtField* src_field = src->GetArtField();
3432*795d594fSAndroid Build Coastguard Worker       CopyAndFixupPointer(dest, mirror::FieldVarHandle::ArtFieldOffset(), src_field);
3433*795d594fSAndroid Build Coastguard Worker     } else if (klass == GetClassRoot<mirror::DexCache, kWithoutReadBarrier>(class_roots)) {
3434*795d594fSAndroid Build Coastguard Worker       down_cast<mirror::DexCache*>(copy)->SetDexFile(nullptr);
3435*795d594fSAndroid Build Coastguard Worker       down_cast<mirror::DexCache*>(copy)->ResetNativeArrays();
3436*795d594fSAndroid Build Coastguard Worker     } else if (klass->IsClassLoaderClass()) {
3437*795d594fSAndroid Build Coastguard Worker       mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
3438*795d594fSAndroid Build Coastguard Worker       // If src is a ClassLoader, set the class table to null so that it gets recreated by the
3439*795d594fSAndroid Build Coastguard Worker       // ClassLinker.
3440*795d594fSAndroid Build Coastguard Worker       copy_loader->SetClassTable(nullptr);
3441*795d594fSAndroid Build Coastguard Worker       // Also set allocator to null to be safe. The allocator is created when we create the class
3442*795d594fSAndroid Build Coastguard Worker       // table. We also never expect to unload things in the image since they are held live as
3443*795d594fSAndroid Build Coastguard Worker       // roots.
3444*795d594fSAndroid Build Coastguard Worker       copy_loader->SetAllocator(nullptr);
3445*795d594fSAndroid Build Coastguard Worker     }
3446*795d594fSAndroid Build Coastguard Worker     FixupVisitor visitor(this, copy);
3447*795d594fSAndroid Build Coastguard Worker     orig->VisitReferences</*kVisitNativeRoots=*/ false, kVerifyNone, kWithoutReadBarrier>(
3448*795d594fSAndroid Build Coastguard Worker         visitor, visitor);
3449*795d594fSAndroid Build Coastguard Worker   }
3450*795d594fSAndroid Build Coastguard Worker }
3451*795d594fSAndroid Build Coastguard Worker 
GetOatAddress(StubType type) const3452*795d594fSAndroid Build Coastguard Worker const uint8_t* ImageWriter::GetOatAddress(StubType type) const {
3453*795d594fSAndroid Build Coastguard Worker   DCHECK_LE(type, StubType::kLast);
3454*795d594fSAndroid Build Coastguard Worker   // If we are compiling a boot image extension or app image,
3455*795d594fSAndroid Build Coastguard Worker   // we need to use the stubs of the primary boot image.
3456*795d594fSAndroid Build Coastguard Worker   if (!compiler_options_.IsBootImage()) {
3457*795d594fSAndroid Build Coastguard Worker     // Use the current image pointers.
3458*795d594fSAndroid Build Coastguard Worker     const std::vector<gc::space::ImageSpace*>& image_spaces =
3459*795d594fSAndroid Build Coastguard Worker         Runtime::Current()->GetHeap()->GetBootImageSpaces();
3460*795d594fSAndroid Build Coastguard Worker     DCHECK(!image_spaces.empty());
3461*795d594fSAndroid Build Coastguard Worker     const OatFile* oat_file = image_spaces[0]->GetOatFile();
3462*795d594fSAndroid Build Coastguard Worker     CHECK(oat_file != nullptr);
3463*795d594fSAndroid Build Coastguard Worker     const OatHeader& header = oat_file->GetOatHeader();
3464*795d594fSAndroid Build Coastguard Worker     return header.GetOatAddress(type);
3465*795d594fSAndroid Build Coastguard Worker   }
3466*795d594fSAndroid Build Coastguard Worker   const ImageInfo& primary_image_info = GetImageInfo(0);
3467*795d594fSAndroid Build Coastguard Worker   return GetOatAddressForOffset(primary_image_info.GetStubOffset(type), primary_image_info);
3468*795d594fSAndroid Build Coastguard Worker }
3469*795d594fSAndroid Build Coastguard Worker 
GetQuickCode(ArtMethod * method,const ImageInfo & image_info)3470*795d594fSAndroid Build Coastguard Worker const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, const ImageInfo& image_info) {
3471*795d594fSAndroid Build Coastguard Worker   DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
3472*795d594fSAndroid Build Coastguard Worker   DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
3473*795d594fSAndroid Build Coastguard Worker   DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
3474*795d594fSAndroid Build Coastguard Worker   DCHECK(method->IsInvokable()) << method->PrettyMethod();
3475*795d594fSAndroid Build Coastguard Worker   DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
3476*795d594fSAndroid Build Coastguard Worker 
3477*795d594fSAndroid Build Coastguard Worker   // Use original code if it exists. Otherwise, set the code pointer to the resolution
3478*795d594fSAndroid Build Coastguard Worker   // trampoline.
3479*795d594fSAndroid Build Coastguard Worker 
3480*795d594fSAndroid Build Coastguard Worker   // Quick entrypoint:
3481*795d594fSAndroid Build Coastguard Worker   const void* quick_oat_entry_point =
3482*795d594fSAndroid Build Coastguard Worker       method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
3483*795d594fSAndroid Build Coastguard Worker   const uint8_t* quick_code;
3484*795d594fSAndroid Build Coastguard Worker 
3485*795d594fSAndroid Build Coastguard Worker   if (UNLIKELY(IsInBootImage(method->GetDeclaringClass<kWithoutReadBarrier>().Ptr()))) {
3486*795d594fSAndroid Build Coastguard Worker     DCHECK(method->IsCopied());
3487*795d594fSAndroid Build Coastguard Worker     // If the code is not in the oat file corresponding to this image (e.g. default methods)
3488*795d594fSAndroid Build Coastguard Worker     quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
3489*795d594fSAndroid Build Coastguard Worker   } else {
3490*795d594fSAndroid Build Coastguard Worker     uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
3491*795d594fSAndroid Build Coastguard Worker     quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
3492*795d594fSAndroid Build Coastguard Worker   }
3493*795d594fSAndroid Build Coastguard Worker 
3494*795d594fSAndroid Build Coastguard Worker   bool still_needs_clinit_check = method->StillNeedsClinitCheck<kWithoutReadBarrier>();
3495*795d594fSAndroid Build Coastguard Worker 
3496*795d594fSAndroid Build Coastguard Worker   if (quick_code == nullptr) {
3497*795d594fSAndroid Build Coastguard Worker     // If we don't have code, use generic jni / interpreter.
3498*795d594fSAndroid Build Coastguard Worker     if (method->IsNative()) {
3499*795d594fSAndroid Build Coastguard Worker       // The generic JNI trampolines performs class initialization check if needed.
3500*795d594fSAndroid Build Coastguard Worker       quick_code = GetOatAddress(StubType::kQuickGenericJNITrampoline);
3501*795d594fSAndroid Build Coastguard Worker     } else if (CanMethodUseNterp(method, compiler_options_.GetInstructionSet())) {
3502*795d594fSAndroid Build Coastguard Worker       // The nterp trampoline doesn't do initialization checks, so install the
3503*795d594fSAndroid Build Coastguard Worker       // resolution stub if needed.
3504*795d594fSAndroid Build Coastguard Worker       if (still_needs_clinit_check) {
3505*795d594fSAndroid Build Coastguard Worker         quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3506*795d594fSAndroid Build Coastguard Worker       } else {
3507*795d594fSAndroid Build Coastguard Worker         quick_code = GetOatAddress(StubType::kNterpTrampoline);
3508*795d594fSAndroid Build Coastguard Worker       }
3509*795d594fSAndroid Build Coastguard Worker     } else {
3510*795d594fSAndroid Build Coastguard Worker       // The interpreter brige performs class initialization check if needed.
3511*795d594fSAndroid Build Coastguard Worker       quick_code = GetOatAddress(StubType::kQuickToInterpreterBridge);
3512*795d594fSAndroid Build Coastguard Worker     }
3513*795d594fSAndroid Build Coastguard Worker   } else if (still_needs_clinit_check && !compiler_options_.ShouldCompileWithClinitCheck(method)) {
3514*795d594fSAndroid Build Coastguard Worker     // If we do have code but the method needs a class initialization check before calling
3515*795d594fSAndroid Build Coastguard Worker     // that code, install the resolution stub that will perform the check.
3516*795d594fSAndroid Build Coastguard Worker     quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3517*795d594fSAndroid Build Coastguard Worker   }
3518*795d594fSAndroid Build Coastguard Worker   return quick_code;
3519*795d594fSAndroid Build Coastguard Worker }
3520*795d594fSAndroid Build Coastguard Worker 
ResetNterpFastPathFlags(uint32_t access_flags,ArtMethod * orig,InstructionSet isa)3521*795d594fSAndroid Build Coastguard Worker static inline uint32_t ResetNterpFastPathFlags(
3522*795d594fSAndroid Build Coastguard Worker     uint32_t access_flags, ArtMethod* orig, InstructionSet isa)
3523*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
3524*795d594fSAndroid Build Coastguard Worker   DCHECK(orig != nullptr);
3525*795d594fSAndroid Build Coastguard Worker   DCHECK(!orig->IsProxyMethod());  // `UnstartedRuntime` does not support creating proxy classes.
3526*795d594fSAndroid Build Coastguard Worker   DCHECK(!orig->IsRuntimeMethod());
3527*795d594fSAndroid Build Coastguard Worker 
3528*795d594fSAndroid Build Coastguard Worker   // Clear old nterp fast path flags.
3529*795d594fSAndroid Build Coastguard Worker   access_flags = ArtMethod::ClearNterpFastPathFlags(access_flags);
3530*795d594fSAndroid Build Coastguard Worker 
3531*795d594fSAndroid Build Coastguard Worker   // Check if nterp fast paths are available on the target ISA.
3532*795d594fSAndroid Build Coastguard Worker   std::string_view shorty = orig->GetShortyView();  // Use orig, copy's class not yet ready.
3533*795d594fSAndroid Build Coastguard Worker   uint32_t new_nterp_flags = GetNterpFastPathFlags(shorty, access_flags, isa);
3534*795d594fSAndroid Build Coastguard Worker 
3535*795d594fSAndroid Build Coastguard Worker   // Add the new nterp fast path flags, if any.
3536*795d594fSAndroid Build Coastguard Worker   return access_flags | new_nterp_flags;
3537*795d594fSAndroid Build Coastguard Worker }
3538*795d594fSAndroid Build Coastguard Worker 
CopyAndFixupMethod(ArtMethod * orig,ArtMethod * copy,size_t oat_index)3539*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
3540*795d594fSAndroid Build Coastguard Worker                                      ArtMethod* copy,
3541*795d594fSAndroid Build Coastguard Worker                                      size_t oat_index) {
3542*795d594fSAndroid Build Coastguard Worker   memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
3543*795d594fSAndroid Build Coastguard Worker 
3544*795d594fSAndroid Build Coastguard Worker   CopyAndFixupReference(copy->GetDeclaringClassAddressWithoutBarrier(),
3545*795d594fSAndroid Build Coastguard Worker                         orig->GetDeclaringClassUnchecked<kWithoutReadBarrier>());
3546*795d594fSAndroid Build Coastguard Worker 
3547*795d594fSAndroid Build Coastguard Worker   if (!orig->IsRuntimeMethod()) {
3548*795d594fSAndroid Build Coastguard Worker     uint32_t access_flags = orig->GetAccessFlags();
3549*795d594fSAndroid Build Coastguard Worker     if (ArtMethod::IsAbstract(access_flags)) {
3550*795d594fSAndroid Build Coastguard Worker       // Ignore the single-implementation info for abstract method.
3551*795d594fSAndroid Build Coastguard Worker       // TODO: handle fixup of single-implementation method for abstract method.
3552*795d594fSAndroid Build Coastguard Worker       access_flags = ArtMethod::SetHasSingleImplementation(access_flags, /*single_impl=*/ false);
3553*795d594fSAndroid Build Coastguard Worker       copy->SetSingleImplementation(nullptr, target_ptr_size_);
3554*795d594fSAndroid Build Coastguard Worker     } else if (mark_memory_shared_methods_ && LIKELY(!ArtMethod::IsIntrinsic(access_flags))) {
3555*795d594fSAndroid Build Coastguard Worker       access_flags = ArtMethod::SetMemorySharedMethod(access_flags);
3556*795d594fSAndroid Build Coastguard Worker       copy->SetHotCounter();
3557*795d594fSAndroid Build Coastguard Worker     }
3558*795d594fSAndroid Build Coastguard Worker 
3559*795d594fSAndroid Build Coastguard Worker     InstructionSet isa = compiler_options_.GetInstructionSet();
3560*795d594fSAndroid Build Coastguard Worker     if (isa != kRuntimeISA) {
3561*795d594fSAndroid Build Coastguard Worker       access_flags = ResetNterpFastPathFlags(access_flags, orig, isa);
3562*795d594fSAndroid Build Coastguard Worker     } else {
3563*795d594fSAndroid Build Coastguard Worker       DCHECK_EQ(access_flags, ResetNterpFastPathFlags(access_flags, orig, isa));
3564*795d594fSAndroid Build Coastguard Worker     }
3565*795d594fSAndroid Build Coastguard Worker     copy->SetAccessFlags(access_flags);
3566*795d594fSAndroid Build Coastguard Worker   }
3567*795d594fSAndroid Build Coastguard Worker 
3568*795d594fSAndroid Build Coastguard Worker   // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
3569*795d594fSAndroid Build Coastguard Worker   // oat_begin_
3570*795d594fSAndroid Build Coastguard Worker 
3571*795d594fSAndroid Build Coastguard Worker   // The resolution method has a special trampoline to call.
3572*795d594fSAndroid Build Coastguard Worker   Runtime* runtime = Runtime::Current();
3573*795d594fSAndroid Build Coastguard Worker   const void* quick_code;
3574*795d594fSAndroid Build Coastguard Worker   if (orig->IsRuntimeMethod()) {
3575*795d594fSAndroid Build Coastguard Worker     ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
3576*795d594fSAndroid Build Coastguard Worker     if (orig_table != nullptr) {
3577*795d594fSAndroid Build Coastguard Worker       // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
3578*795d594fSAndroid Build Coastguard Worker       quick_code = GetOatAddress(StubType::kQuickIMTConflictTrampoline);
3579*795d594fSAndroid Build Coastguard Worker       CopyAndFixupPointer(copy, ArtMethod::DataOffset(target_ptr_size_), orig_table);
3580*795d594fSAndroid Build Coastguard Worker     } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
3581*795d594fSAndroid Build Coastguard Worker       quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3582*795d594fSAndroid Build Coastguard Worker       // Set JNI entrypoint for resolving @CriticalNative methods called from compiled code .
3583*795d594fSAndroid Build Coastguard Worker       const void* jni_code = GetOatAddress(StubType::kJNIDlsymLookupCriticalTrampoline);
3584*795d594fSAndroid Build Coastguard Worker       copy->SetEntryPointFromJniPtrSize(jni_code, target_ptr_size_);
3585*795d594fSAndroid Build Coastguard Worker     } else {
3586*795d594fSAndroid Build Coastguard Worker       bool found_one = false;
3587*795d594fSAndroid Build Coastguard Worker       for (size_t i = 0; i < static_cast<size_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
3588*795d594fSAndroid Build Coastguard Worker         auto idx = static_cast<CalleeSaveType>(i);
3589*795d594fSAndroid Build Coastguard Worker         if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
3590*795d594fSAndroid Build Coastguard Worker           found_one = true;
3591*795d594fSAndroid Build Coastguard Worker           break;
3592*795d594fSAndroid Build Coastguard Worker         }
3593*795d594fSAndroid Build Coastguard Worker       }
3594*795d594fSAndroid Build Coastguard Worker       CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
3595*795d594fSAndroid Build Coastguard Worker       CHECK(copy->IsRuntimeMethod());
3596*795d594fSAndroid Build Coastguard Worker       CHECK(copy->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_) == nullptr);
3597*795d594fSAndroid Build Coastguard Worker       quick_code = nullptr;
3598*795d594fSAndroid Build Coastguard Worker     }
3599*795d594fSAndroid Build Coastguard Worker   } else {
3600*795d594fSAndroid Build Coastguard Worker     // We assume all methods have code. If they don't currently then we set them to the use the
3601*795d594fSAndroid Build Coastguard Worker     // resolution trampoline. Abstract methods never have code and so we need to make sure their
3602*795d594fSAndroid Build Coastguard Worker     // use results in an AbstractMethodError. We use the interpreter to achieve this.
3603*795d594fSAndroid Build Coastguard Worker     if (UNLIKELY(!orig->IsInvokable())) {
3604*795d594fSAndroid Build Coastguard Worker       quick_code = GetOatAddress(StubType::kQuickToInterpreterBridge);
3605*795d594fSAndroid Build Coastguard Worker     } else {
3606*795d594fSAndroid Build Coastguard Worker       const ImageInfo& image_info = image_infos_[oat_index];
3607*795d594fSAndroid Build Coastguard Worker       quick_code = GetQuickCode(orig, image_info);
3608*795d594fSAndroid Build Coastguard Worker 
3609*795d594fSAndroid Build Coastguard Worker       // JNI entrypoint:
3610*795d594fSAndroid Build Coastguard Worker       if (orig->IsNative()) {
3611*795d594fSAndroid Build Coastguard Worker         // Find boot JNI stub for those methods that skipped AOT compilation and don't need
3612*795d594fSAndroid Build Coastguard Worker         // clinit check.
3613*795d594fSAndroid Build Coastguard Worker         bool still_needs_clinit_check = orig->StillNeedsClinitCheck<kWithoutReadBarrier>();
3614*795d594fSAndroid Build Coastguard Worker         if (!still_needs_clinit_check &&
3615*795d594fSAndroid Build Coastguard Worker             !compiler_options_.IsBootImage() &&
3616*795d594fSAndroid Build Coastguard Worker             quick_code == GetOatAddress(StubType::kQuickGenericJNITrampoline)) {
3617*795d594fSAndroid Build Coastguard Worker           ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3618*795d594fSAndroid Build Coastguard Worker           const void* boot_jni_stub = class_linker->FindBootJniStub(orig);
3619*795d594fSAndroid Build Coastguard Worker           if (boot_jni_stub != nullptr) {
3620*795d594fSAndroid Build Coastguard Worker             quick_code = boot_jni_stub;
3621*795d594fSAndroid Build Coastguard Worker           }
3622*795d594fSAndroid Build Coastguard Worker         }
3623*795d594fSAndroid Build Coastguard Worker         // The native method's pointer is set to a stub to lookup via dlsym.
3624*795d594fSAndroid Build Coastguard Worker         // Note this is not the code_ pointer, that is handled above.
3625*795d594fSAndroid Build Coastguard Worker         StubType stub_type = orig->IsCriticalNative() ? StubType::kJNIDlsymLookupCriticalTrampoline
3626*795d594fSAndroid Build Coastguard Worker                                                       : StubType::kJNIDlsymLookupTrampoline;
3627*795d594fSAndroid Build Coastguard Worker         copy->SetEntryPointFromJniPtrSize(GetOatAddress(stub_type), target_ptr_size_);
3628*795d594fSAndroid Build Coastguard Worker       } else if (!orig->HasCodeItem()) {
3629*795d594fSAndroid Build Coastguard Worker         CHECK(copy->GetDataPtrSize(target_ptr_size_) == nullptr);
3630*795d594fSAndroid Build Coastguard Worker       } else {
3631*795d594fSAndroid Build Coastguard Worker         CHECK(copy->GetDataPtrSize(target_ptr_size_) != nullptr);
3632*795d594fSAndroid Build Coastguard Worker       }
3633*795d594fSAndroid Build Coastguard Worker     }
3634*795d594fSAndroid Build Coastguard Worker   }
3635*795d594fSAndroid Build Coastguard Worker   if (quick_code != nullptr) {
3636*795d594fSAndroid Build Coastguard Worker     copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
3637*795d594fSAndroid Build Coastguard Worker   }
3638*795d594fSAndroid Build Coastguard Worker }
3639*795d594fSAndroid Build Coastguard Worker 
GetBinSizeSum(Bin up_to) const3640*795d594fSAndroid Build Coastguard Worker size_t ImageWriter::ImageInfo::GetBinSizeSum(Bin up_to) const {
3641*795d594fSAndroid Build Coastguard Worker   DCHECK_LE(static_cast<size_t>(up_to), kNumberOfBins);
3642*795d594fSAndroid Build Coastguard Worker   return std::accumulate(&bin_slot_sizes_[0],
3643*795d594fSAndroid Build Coastguard Worker                          &bin_slot_sizes_[0] + static_cast<size_t>(up_to),
3644*795d594fSAndroid Build Coastguard Worker                          /*init*/ static_cast<size_t>(0));
3645*795d594fSAndroid Build Coastguard Worker }
3646*795d594fSAndroid Build Coastguard Worker 
BinSlot(uint32_t lockword)3647*795d594fSAndroid Build Coastguard Worker ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
3648*795d594fSAndroid Build Coastguard Worker   // These values may need to get updated if more bins are added to the enum Bin
3649*795d594fSAndroid Build Coastguard Worker   static_assert(kBinBits == 3, "wrong number of bin bits");
3650*795d594fSAndroid Build Coastguard Worker   static_assert(kBinShift == 27, "wrong number of shift");
3651*795d594fSAndroid Build Coastguard Worker   static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
3652*795d594fSAndroid Build Coastguard Worker 
3653*795d594fSAndroid Build Coastguard Worker   DCHECK_LT(GetBin(), Bin::kMirrorCount);
3654*795d594fSAndroid Build Coastguard Worker   DCHECK_ALIGNED(GetOffset(), kObjectAlignment);
3655*795d594fSAndroid Build Coastguard Worker }
3656*795d594fSAndroid Build Coastguard Worker 
BinSlot(Bin bin,uint32_t index)3657*795d594fSAndroid Build Coastguard Worker ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
3658*795d594fSAndroid Build Coastguard Worker     : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
3659*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(index, GetOffset());
3660*795d594fSAndroid Build Coastguard Worker }
3661*795d594fSAndroid Build Coastguard Worker 
GetBin() const3662*795d594fSAndroid Build Coastguard Worker ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
3663*795d594fSAndroid Build Coastguard Worker   return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
3664*795d594fSAndroid Build Coastguard Worker }
3665*795d594fSAndroid Build Coastguard Worker 
GetOffset() const3666*795d594fSAndroid Build Coastguard Worker uint32_t ImageWriter::BinSlot::GetOffset() const {
3667*795d594fSAndroid Build Coastguard Worker   return lockword_ & ~kBinMask;
3668*795d594fSAndroid Build Coastguard Worker }
3669*795d594fSAndroid Build Coastguard Worker 
BinTypeForNativeRelocationType(NativeObjectRelocationType type)3670*795d594fSAndroid Build Coastguard Worker ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
3671*795d594fSAndroid Build Coastguard Worker   switch (type) {
3672*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kArtFieldArray:
3673*795d594fSAndroid Build Coastguard Worker       return Bin::kArtField;
3674*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kArtMethodClean:
3675*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kArtMethodArrayClean:
3676*795d594fSAndroid Build Coastguard Worker       return Bin::kArtMethodClean;
3677*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kArtMethodDirty:
3678*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kArtMethodArrayDirty:
3679*795d594fSAndroid Build Coastguard Worker       return Bin::kArtMethodDirty;
3680*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kRuntimeMethod:
3681*795d594fSAndroid Build Coastguard Worker       return Bin::kRuntimeMethod;
3682*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kIMTable:
3683*795d594fSAndroid Build Coastguard Worker       return Bin::kImTable;
3684*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kIMTConflictTable:
3685*795d594fSAndroid Build Coastguard Worker       return Bin::kIMTConflictTable;
3686*795d594fSAndroid Build Coastguard Worker     case NativeObjectRelocationType::kGcRootPointer:
3687*795d594fSAndroid Build Coastguard Worker       return Bin::kMetadata;
3688*795d594fSAndroid Build Coastguard Worker   }
3689*795d594fSAndroid Build Coastguard Worker }
3690*795d594fSAndroid Build Coastguard Worker 
GetOatIndex(mirror::Object * obj) const3691*795d594fSAndroid Build Coastguard Worker size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
3692*795d594fSAndroid Build Coastguard Worker   if (!IsMultiImage()) {
3693*795d594fSAndroid Build Coastguard Worker     DCHECK(oat_index_map_.empty());
3694*795d594fSAndroid Build Coastguard Worker     return GetDefaultOatIndex();
3695*795d594fSAndroid Build Coastguard Worker   }
3696*795d594fSAndroid Build Coastguard Worker   auto it = oat_index_map_.find(obj);
3697*795d594fSAndroid Build Coastguard Worker   DCHECK(it != oat_index_map_.end()) << obj;
3698*795d594fSAndroid Build Coastguard Worker   return it->second;
3699*795d594fSAndroid Build Coastguard Worker }
3700*795d594fSAndroid Build Coastguard Worker 
GetOatIndexForDexFile(const DexFile * dex_file) const3701*795d594fSAndroid Build Coastguard Worker size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
3702*795d594fSAndroid Build Coastguard Worker   if (!IsMultiImage()) {
3703*795d594fSAndroid Build Coastguard Worker     return GetDefaultOatIndex();
3704*795d594fSAndroid Build Coastguard Worker   }
3705*795d594fSAndroid Build Coastguard Worker   auto it = dex_file_oat_index_map_.find(dex_file);
3706*795d594fSAndroid Build Coastguard Worker   DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
3707*795d594fSAndroid Build Coastguard Worker   return it->second;
3708*795d594fSAndroid Build Coastguard Worker }
3709*795d594fSAndroid Build Coastguard Worker 
GetOatIndexForClass(ObjPtr<mirror::Class> klass) const3710*795d594fSAndroid Build Coastguard Worker size_t ImageWriter::GetOatIndexForClass(ObjPtr<mirror::Class> klass) const {
3711*795d594fSAndroid Build Coastguard Worker   while (klass->IsArrayClass()) {
3712*795d594fSAndroid Build Coastguard Worker     klass = klass->GetComponentType<kVerifyNone, kWithoutReadBarrier>();
3713*795d594fSAndroid Build Coastguard Worker   }
3714*795d594fSAndroid Build Coastguard Worker   if (UNLIKELY(klass->IsPrimitive())) {
3715*795d594fSAndroid Build Coastguard Worker     DCHECK((klass->GetDexCache<kVerifyNone, kWithoutReadBarrier>()) == nullptr);
3716*795d594fSAndroid Build Coastguard Worker     return GetDefaultOatIndex();
3717*795d594fSAndroid Build Coastguard Worker   } else {
3718*795d594fSAndroid Build Coastguard Worker     DCHECK((klass->GetDexCache<kVerifyNone, kWithoutReadBarrier>()) != nullptr);
3719*795d594fSAndroid Build Coastguard Worker     return GetOatIndexForDexFile(&klass->GetDexFile());
3720*795d594fSAndroid Build Coastguard Worker   }
3721*795d594fSAndroid Build Coastguard Worker }
3722*795d594fSAndroid Build Coastguard Worker 
UpdateOatFileLayout(size_t oat_index,size_t oat_loaded_size,size_t oat_data_offset,size_t oat_data_size)3723*795d594fSAndroid Build Coastguard Worker void ImageWriter::UpdateOatFileLayout(size_t oat_index,
3724*795d594fSAndroid Build Coastguard Worker                                       size_t oat_loaded_size,
3725*795d594fSAndroid Build Coastguard Worker                                       size_t oat_data_offset,
3726*795d594fSAndroid Build Coastguard Worker                                       size_t oat_data_size) {
3727*795d594fSAndroid Build Coastguard Worker   DCHECK_GE(oat_loaded_size, oat_data_offset);
3728*795d594fSAndroid Build Coastguard Worker   DCHECK_GE(oat_loaded_size - oat_data_offset, oat_data_size);
3729*795d594fSAndroid Build Coastguard Worker 
3730*795d594fSAndroid Build Coastguard Worker   const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
3731*795d594fSAndroid Build Coastguard Worker   DCHECK(images_end != nullptr);  // Image space must be ready.
3732*795d594fSAndroid Build Coastguard Worker   for (const ImageInfo& info : image_infos_) {
3733*795d594fSAndroid Build Coastguard Worker     DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
3734*795d594fSAndroid Build Coastguard Worker   }
3735*795d594fSAndroid Build Coastguard Worker 
3736*795d594fSAndroid Build Coastguard Worker   ImageInfo& cur_image_info = GetImageInfo(oat_index);
3737*795d594fSAndroid Build Coastguard Worker   cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
3738*795d594fSAndroid Build Coastguard Worker   cur_image_info.oat_loaded_size_ = oat_loaded_size;
3739*795d594fSAndroid Build Coastguard Worker   cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
3740*795d594fSAndroid Build Coastguard Worker   cur_image_info.oat_size_ = oat_data_size;
3741*795d594fSAndroid Build Coastguard Worker 
3742*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsAppImage()) {
3743*795d594fSAndroid Build Coastguard Worker     CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
3744*795d594fSAndroid Build Coastguard Worker     return;
3745*795d594fSAndroid Build Coastguard Worker   }
3746*795d594fSAndroid Build Coastguard Worker 
3747*795d594fSAndroid Build Coastguard Worker   // Update the oat_offset of the next image info.
3748*795d594fSAndroid Build Coastguard Worker   if (oat_index + 1u != oat_filenames_.size()) {
3749*795d594fSAndroid Build Coastguard Worker     // There is a following one.
3750*795d594fSAndroid Build Coastguard Worker     ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
3751*795d594fSAndroid Build Coastguard Worker     next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
3752*795d594fSAndroid Build Coastguard Worker   }
3753*795d594fSAndroid Build Coastguard Worker }
3754*795d594fSAndroid Build Coastguard Worker 
UpdateOatFileHeader(size_t oat_index,const OatHeader & oat_header)3755*795d594fSAndroid Build Coastguard Worker void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
3756*795d594fSAndroid Build Coastguard Worker   ImageInfo& cur_image_info = GetImageInfo(oat_index);
3757*795d594fSAndroid Build Coastguard Worker   cur_image_info.oat_checksum_ = oat_header.GetChecksum();
3758*795d594fSAndroid Build Coastguard Worker 
3759*795d594fSAndroid Build Coastguard Worker   if (oat_index == GetDefaultOatIndex()) {
3760*795d594fSAndroid Build Coastguard Worker     // Primary oat file, read the trampolines.
3761*795d594fSAndroid Build Coastguard Worker     cur_image_info.SetStubOffset(StubType::kJNIDlsymLookupTrampoline,
3762*795d594fSAndroid Build Coastguard Worker                                  oat_header.GetJniDlsymLookupTrampolineOffset());
3763*795d594fSAndroid Build Coastguard Worker     cur_image_info.SetStubOffset(StubType::kJNIDlsymLookupCriticalTrampoline,
3764*795d594fSAndroid Build Coastguard Worker                                  oat_header.GetJniDlsymLookupCriticalTrampolineOffset());
3765*795d594fSAndroid Build Coastguard Worker     cur_image_info.SetStubOffset(StubType::kQuickGenericJNITrampoline,
3766*795d594fSAndroid Build Coastguard Worker                                  oat_header.GetQuickGenericJniTrampolineOffset());
3767*795d594fSAndroid Build Coastguard Worker     cur_image_info.SetStubOffset(StubType::kQuickIMTConflictTrampoline,
3768*795d594fSAndroid Build Coastguard Worker                                  oat_header.GetQuickImtConflictTrampolineOffset());
3769*795d594fSAndroid Build Coastguard Worker     cur_image_info.SetStubOffset(StubType::kQuickResolutionTrampoline,
3770*795d594fSAndroid Build Coastguard Worker                                  oat_header.GetQuickResolutionTrampolineOffset());
3771*795d594fSAndroid Build Coastguard Worker     cur_image_info.SetStubOffset(StubType::kQuickToInterpreterBridge,
3772*795d594fSAndroid Build Coastguard Worker                                  oat_header.GetQuickToInterpreterBridgeOffset());
3773*795d594fSAndroid Build Coastguard Worker     cur_image_info.SetStubOffset(StubType::kNterpTrampoline,
3774*795d594fSAndroid Build Coastguard Worker                                  oat_header.GetNterpTrampolineOffset());
3775*795d594fSAndroid Build Coastguard Worker   }
3776*795d594fSAndroid Build Coastguard Worker }
3777*795d594fSAndroid Build Coastguard Worker 
ImageWriter(const CompilerOptions & compiler_options,uintptr_t image_begin,ImageHeader::StorageMode image_storage_mode,const std::vector<std::string> & oat_filenames,const HashMap<const DexFile *,size_t> & dex_file_oat_index_map,jobject class_loader,const std::vector<std::string> * dirty_image_objects)3778*795d594fSAndroid Build Coastguard Worker ImageWriter::ImageWriter(const CompilerOptions& compiler_options,
3779*795d594fSAndroid Build Coastguard Worker                          uintptr_t image_begin,
3780*795d594fSAndroid Build Coastguard Worker                          ImageHeader::StorageMode image_storage_mode,
3781*795d594fSAndroid Build Coastguard Worker                          const std::vector<std::string>& oat_filenames,
3782*795d594fSAndroid Build Coastguard Worker                          const HashMap<const DexFile*, size_t>& dex_file_oat_index_map,
3783*795d594fSAndroid Build Coastguard Worker                          jobject class_loader,
3784*795d594fSAndroid Build Coastguard Worker                          const std::vector<std::string>* dirty_image_objects)
3785*795d594fSAndroid Build Coastguard Worker     : compiler_options_(compiler_options),
3786*795d594fSAndroid Build Coastguard Worker       target_ptr_size_(InstructionSetPointerSize(compiler_options.GetInstructionSet())),
3787*795d594fSAndroid Build Coastguard Worker       // If we're compiling a boot image and we have a profile, set methods as being shared
3788*795d594fSAndroid Build Coastguard Worker       // memory (to avoid dirtying them with hotness counter). We expect important methods
3789*795d594fSAndroid Build Coastguard Worker       // to be AOT, and non-important methods to be run in the interpreter.
3790*795d594fSAndroid Build Coastguard Worker       mark_memory_shared_methods_(
3791*795d594fSAndroid Build Coastguard Worker           CompilerFilter::DependsOnProfile(compiler_options_.GetCompilerFilter()) &&
3792*795d594fSAndroid Build Coastguard Worker               (compiler_options_.IsBootImage() || compiler_options_.IsBootImageExtension())),
3793*795d594fSAndroid Build Coastguard Worker       boot_image_begin_(Runtime::Current()->GetHeap()->GetBootImagesStartAddress()),
3794*795d594fSAndroid Build Coastguard Worker       boot_image_size_(Runtime::Current()->GetHeap()->GetBootImagesSize()),
3795*795d594fSAndroid Build Coastguard Worker       global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
3796*795d594fSAndroid Build Coastguard Worker       image_objects_offset_begin_(0),
3797*795d594fSAndroid Build Coastguard Worker       image_infos_(oat_filenames.size()),
3798*795d594fSAndroid Build Coastguard Worker       jni_stub_map_(JniStubKeyHash(compiler_options.GetInstructionSet()),
3799*795d594fSAndroid Build Coastguard Worker                     JniStubKeyEquals(compiler_options.GetInstructionSet())),
3800*795d594fSAndroid Build Coastguard Worker       dirty_methods_(0u),
3801*795d594fSAndroid Build Coastguard Worker       clean_methods_(0u),
3802*795d594fSAndroid Build Coastguard Worker       app_class_loader_(class_loader),
3803*795d594fSAndroid Build Coastguard Worker       boot_image_live_objects_(nullptr),
3804*795d594fSAndroid Build Coastguard Worker       image_roots_(),
3805*795d594fSAndroid Build Coastguard Worker       image_storage_mode_(image_storage_mode),
3806*795d594fSAndroid Build Coastguard Worker       oat_filenames_(oat_filenames),
3807*795d594fSAndroid Build Coastguard Worker       dex_file_oat_index_map_(dex_file_oat_index_map),
3808*795d594fSAndroid Build Coastguard Worker       dirty_image_objects_(dirty_image_objects) {
3809*795d594fSAndroid Build Coastguard Worker   DCHECK(compiler_options.IsBootImage() ||
3810*795d594fSAndroid Build Coastguard Worker          compiler_options.IsBootImageExtension() ||
3811*795d594fSAndroid Build Coastguard Worker          compiler_options.IsAppImage());
3812*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(compiler_options.IsBootImage(), boot_image_begin_ == 0u);
3813*795d594fSAndroid Build Coastguard Worker   DCHECK_EQ(compiler_options.IsBootImage(), boot_image_size_ == 0u);
3814*795d594fSAndroid Build Coastguard Worker   CHECK_NE(image_begin, 0U);
3815*795d594fSAndroid Build Coastguard Worker   std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
3816*795d594fSAndroid Build Coastguard Worker   CHECK_EQ(compiler_options.IsBootImage(),
3817*795d594fSAndroid Build Coastguard Worker            Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
3818*795d594fSAndroid Build Coastguard Worker       << "Compiling a boot image should occur iff there are no boot image spaces loaded";
3819*795d594fSAndroid Build Coastguard Worker   if (compiler_options_.IsAppImage()) {
3820*795d594fSAndroid Build Coastguard Worker     // Make sure objects are not crossing region boundaries for app images.
3821*795d594fSAndroid Build Coastguard Worker     region_size_ = gc::space::RegionSpace::kRegionSize;
3822*795d594fSAndroid Build Coastguard Worker   }
3823*795d594fSAndroid Build Coastguard Worker }
3824*795d594fSAndroid Build Coastguard Worker 
~ImageWriter()3825*795d594fSAndroid Build Coastguard Worker ImageWriter::~ImageWriter() {
3826*795d594fSAndroid Build Coastguard Worker   if (!image_roots_.empty()) {
3827*795d594fSAndroid Build Coastguard Worker     Thread* self = Thread::Current();
3828*795d594fSAndroid Build Coastguard Worker     JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
3829*795d594fSAndroid Build Coastguard Worker     for (jobject image_roots : image_roots_) {
3830*795d594fSAndroid Build Coastguard Worker       vm->DeleteGlobalRef(self, image_roots);
3831*795d594fSAndroid Build Coastguard Worker     }
3832*795d594fSAndroid Build Coastguard Worker   }
3833*795d594fSAndroid Build Coastguard Worker }
3834*795d594fSAndroid Build Coastguard Worker 
ImageInfo()3835*795d594fSAndroid Build Coastguard Worker ImageWriter::ImageInfo::ImageInfo()
3836*795d594fSAndroid Build Coastguard Worker     : intern_table_(),
3837*795d594fSAndroid Build Coastguard Worker       class_table_() {}
3838*795d594fSAndroid Build Coastguard Worker 
3839*795d594fSAndroid Build Coastguard Worker template <typename DestType>
CopyAndFixupReference(DestType * dest,ObjPtr<mirror::Object> src)3840*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupReference(DestType* dest, ObjPtr<mirror::Object> src) {
3841*795d594fSAndroid Build Coastguard Worker   static_assert(std::is_same<DestType, mirror::CompressedReference<mirror::Object>>::value ||
3842*795d594fSAndroid Build Coastguard Worker                     std::is_same<DestType, mirror::HeapReference<mirror::Object>>::value,
3843*795d594fSAndroid Build Coastguard Worker                 "DestType must be a Compressed-/HeapReference<Object>.");
3844*795d594fSAndroid Build Coastguard Worker   dest->Assign(GetImageAddress(src.Ptr()));
3845*795d594fSAndroid Build Coastguard Worker }
3846*795d594fSAndroid Build Coastguard Worker 
3847*795d594fSAndroid Build Coastguard Worker template <typename ValueType>
CopyAndFixupPointer(void ** target,ValueType src_value,PointerSize pointer_size)3848*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupPointer(
3849*795d594fSAndroid Build Coastguard Worker     void** target, ValueType src_value, PointerSize pointer_size) {
3850*795d594fSAndroid Build Coastguard Worker   DCHECK(src_value != nullptr);
3851*795d594fSAndroid Build Coastguard Worker   void* new_value = NativeLocationInImage(src_value);
3852*795d594fSAndroid Build Coastguard Worker   DCHECK(new_value != nullptr);
3853*795d594fSAndroid Build Coastguard Worker   if (pointer_size == PointerSize::k32) {
3854*795d594fSAndroid Build Coastguard Worker     *reinterpret_cast<uint32_t*>(target) = reinterpret_cast32<uint32_t>(new_value);
3855*795d594fSAndroid Build Coastguard Worker   } else {
3856*795d594fSAndroid Build Coastguard Worker     *reinterpret_cast<uint64_t*>(target) = reinterpret_cast64<uint64_t>(new_value);
3857*795d594fSAndroid Build Coastguard Worker   }
3858*795d594fSAndroid Build Coastguard Worker }
3859*795d594fSAndroid Build Coastguard Worker 
3860*795d594fSAndroid Build Coastguard Worker template <typename ValueType>
CopyAndFixupPointer(void ** target,ValueType src_value)3861*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupPointer(void** target, ValueType src_value)
3862*795d594fSAndroid Build Coastguard Worker     REQUIRES_SHARED(Locks::mutator_lock_) {
3863*795d594fSAndroid Build Coastguard Worker   CopyAndFixupPointer(target, src_value, target_ptr_size_);
3864*795d594fSAndroid Build Coastguard Worker }
3865*795d594fSAndroid Build Coastguard Worker 
3866*795d594fSAndroid Build Coastguard Worker template <typename ValueType>
CopyAndFixupPointer(void * object,MemberOffset offset,ValueType src_value,PointerSize pointer_size)3867*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupPointer(
3868*795d594fSAndroid Build Coastguard Worker     void* object, MemberOffset offset, ValueType src_value, PointerSize pointer_size) {
3869*795d594fSAndroid Build Coastguard Worker   void** target =
3870*795d594fSAndroid Build Coastguard Worker       reinterpret_cast<void**>(reinterpret_cast<uint8_t*>(object) + offset.Uint32Value());
3871*795d594fSAndroid Build Coastguard Worker   return CopyAndFixupPointer(target, src_value, pointer_size);
3872*795d594fSAndroid Build Coastguard Worker }
3873*795d594fSAndroid Build Coastguard Worker 
3874*795d594fSAndroid Build Coastguard Worker template <typename ValueType>
CopyAndFixupPointer(void * object,MemberOffset offset,ValueType src_value)3875*795d594fSAndroid Build Coastguard Worker void ImageWriter::CopyAndFixupPointer(void* object, MemberOffset offset, ValueType src_value) {
3876*795d594fSAndroid Build Coastguard Worker   return CopyAndFixupPointer(object, offset, src_value, target_ptr_size_);
3877*795d594fSAndroid Build Coastguard Worker }
3878*795d594fSAndroid Build Coastguard Worker 
3879*795d594fSAndroid Build Coastguard Worker }  // namespace linker
3880*795d594fSAndroid Build Coastguard Worker }  // namespace art
3881