1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #include "lambda/closure_builder.h"
17 
18 #include "base/macros.h"
19 #include "base/value_object.h"
20 #include "lambda/art_lambda_method.h"
21 #include "lambda/closure.h"
22 #include "lambda/shorty_field_type.h"
23 #include "runtime/mirror/object_reference.h"
24 
25 #include <stdint.h>
26 #include <vector>
27 
28 namespace art {
29 namespace lambda {
30 
31 /*
32  * GC support TODOs:
33  * (Although there's some code for storing objects, it is UNIMPLEMENTED(FATAL) because it is
34  * incomplete).
35  *
36  * 1) GC needs to be able to traverse the Closure and visit any references.
37  *    It might be possible to get away with global roots in the short term.
38  *
39  * 2) Add brooks read barrier support. We can store the black/gray/white bits
40  *    in the lower 2 bits of the lambda art method pointer. Whenever a closure is copied
41  *    [to the stack] we'd need to add a cold path to turn it black.
42  *    (since there's only 3 colors, I can use the 4th value to indicate no-refs).
43  *    e.g. 0x0 = gray, 0x1 = white, 0x2 = black, 0x3 = no-nested-references
44  *    - Alternatively the GC can mark reference-less closures as always-black,
45  *      although it would need extra work to check for references.
46  */
47 
CaptureVariableObject(mirror::Object * object)48 void ClosureBuilder::CaptureVariableObject(mirror::Object* object) {
49   auto compressed_reference = mirror::CompressedReference<mirror::Object>::FromMirrorPtr(object);
50   ShortyFieldTypeTraits::MaxType storage = 0;
51 
52   static_assert(sizeof(storage) >= sizeof(compressed_reference),
53                 "not enough room to store a compressed reference");
54   memcpy(&storage, &compressed_reference, sizeof(compressed_reference));
55 
56   values_.push_back(storage);
57   size_ += kObjectReferenceSize;
58 
59   static_assert(kObjectReferenceSize == sizeof(compressed_reference), "reference size mismatch");
60 
61   // TODO: needs more work to support concurrent GC
62   if (kIsDebugBuild) {
63     if (kUseReadBarrier) {
64       UNIMPLEMENTED(FATAL) << "can't yet safely capture objects with read barrier";
65     }
66   }
67 
68   shorty_types_ += ShortyFieldType::kObject;
69 }
70 
CaptureVariableLambda(Closure * closure)71 void ClosureBuilder::CaptureVariableLambda(Closure* closure) {
72   DCHECK(closure != nullptr);  // null closures not allowed, target method must be null instead.
73   values_.push_back(reinterpret_cast<ShortyFieldTypeTraits::MaxType>(closure));
74 
75   if (LIKELY(is_dynamic_size_ == false)) {
76     // Write in the extra bytes to store the dynamic size the first time.
77     is_dynamic_size_ = true;
78     size_ += sizeof(Closure::captured_[0].dynamic_.size_);
79   }
80 
81   // A closure may be sized dynamically, so always query it for the true size.
82   size_ += closure->GetSize();
83 
84   shorty_types_ += ShortyFieldType::kLambda;
85 }
86 
GetSize() const87 size_t ClosureBuilder::GetSize() const {
88   return size_;
89 }
90 
GetCaptureCount() const91 size_t ClosureBuilder::GetCaptureCount() const {
92   DCHECK_EQ(values_.size(), shorty_types_.size());
93   return values_.size();
94 }
95 
GetCapturedVariableShortyTypes() const96 const std::string& ClosureBuilder::GetCapturedVariableShortyTypes() const {
97   DCHECK_EQ(values_.size(), shorty_types_.size());
98   return shorty_types_;
99 }
100 
CreateInPlace(void * memory,ArtLambdaMethod * target_method) const101 Closure* ClosureBuilder::CreateInPlace(void* memory, ArtLambdaMethod* target_method) const {
102   DCHECK(memory != nullptr);
103   DCHECK(target_method != nullptr);
104   DCHECK_EQ(is_dynamic_size_, target_method->IsDynamicSize());
105 
106   CHECK_EQ(target_method->GetNumberOfCapturedVariables(), values_.size())
107     << "number of variables captured at runtime does not match "
108     << "number of variables captured at compile time";
109 
110   Closure* closure = new (memory) Closure;
111   closure->lambda_info_ = target_method;
112 
113   static_assert(offsetof(Closure, captured_) == kInitialSize, "wrong initial size");
114 
115   size_t written_size;
116   if (UNLIKELY(is_dynamic_size_)) {
117     // The closure size must be set dynamically (i.e. nested lambdas).
118     closure->captured_[0].dynamic_.size_ = GetSize();
119     size_t header_size = offsetof(Closure, captured_[0].dynamic_.variables_);
120     DCHECK_LE(header_size, GetSize());
121     size_t variables_size = GetSize() - header_size;
122     written_size =
123         WriteValues(target_method,
124                     closure->captured_[0].dynamic_.variables_,
125                     header_size,
126                     variables_size);
127   } else {
128     // The closure size is known statically (i.e. no nested lambdas).
129     DCHECK(GetSize() == target_method->GetStaticClosureSize());
130     size_t header_size = offsetof(Closure, captured_[0].static_variables_);
131     DCHECK_LE(header_size, GetSize());
132     size_t variables_size = GetSize() - header_size;
133     written_size =
134         WriteValues(target_method,
135                     closure->captured_[0].static_variables_,
136                     header_size,
137                     variables_size);
138   }
139 
140   DCHECK_EQ(written_size, closure->GetSize());
141 
142   return closure;
143 }
144 
WriteValues(ArtLambdaMethod * target_method,uint8_t variables[],size_t header_size,size_t variables_size) const145 size_t ClosureBuilder::WriteValues(ArtLambdaMethod* target_method,
146                                    uint8_t variables[],
147                                    size_t header_size,
148                                    size_t variables_size) const {
149   size_t total_size = header_size;
150   const char* shorty_types = target_method->GetCapturedVariablesShortyTypeDescriptor();
151   DCHECK_STREQ(shorty_types, shorty_types_.c_str());
152 
153   size_t variables_offset = 0;
154   size_t remaining_size = variables_size;
155 
156   const size_t shorty_count = target_method->GetNumberOfCapturedVariables();
157   DCHECK_EQ(shorty_count, GetCaptureCount());
158 
159   for (size_t i = 0; i < shorty_count; ++i) {
160     ShortyFieldType shorty{shorty_types[i]};  // NOLINT [readability/braces] [4]
161 
162     size_t var_size;
163     if (LIKELY(shorty.IsStaticSize())) {
164       // TODO: needs more work to support concurrent GC, e.g. read barriers
165       if (kUseReadBarrier == false) {
166         if (UNLIKELY(shorty.IsObject())) {
167           UNIMPLEMENTED(FATAL) << "can't yet safely write objects with read barrier";
168         }
169       } else {
170         if (UNLIKELY(shorty.IsObject())) {
171           UNIMPLEMENTED(FATAL) << "writing objects not yet supported, no GC support";
172         }
173       }
174 
175       var_size = shorty.GetStaticSize();
176       DCHECK_LE(var_size, sizeof(values_[i]));
177 
178       // Safe even for objects (non-read barrier case) if we never suspend
179       // while the ClosureBuilder is live.
180       // FIXME: Need to add GC support for references in a closure.
181       memcpy(&variables[variables_offset], &values_[i], var_size);
182     } else {
183       DCHECK(shorty.IsLambda())
184           << " don't support writing dynamically sized types other than lambda";
185 
186       ShortyFieldTypeTraits::MaxType closure_raw = values_[i];
187       Closure* nested_closure = reinterpret_cast<Closure*>(closure_raw);
188 
189       DCHECK(nested_closure != nullptr);
190       nested_closure->CopyTo(&variables[variables_offset], remaining_size);
191 
192       var_size = nested_closure->GetSize();
193     }
194 
195     total_size += var_size;
196     DCHECK_GE(remaining_size, var_size);
197     remaining_size -= var_size;
198 
199     variables_offset += var_size;
200   }
201 
202   DCHECK_EQ('\0', shorty_types[shorty_count]);
203   DCHECK_EQ(variables_offset, variables_size);
204 
205   return total_size;
206 }
207 
208 
209 }  // namespace lambda
210 }  // namespace art
211