-
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathObjectManager.mm
More file actions
370 lines (323 loc) · 12.1 KB
/
Copy pathObjectManager.mm
File metadata and controls
370 lines (323 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
#include "ObjectManager.h"
#include <Block.h>
#include <CoreFoundation/CoreFoundation.h>
#include <sstream>
#include "Caches.h"
#include "Constants.h"
#include "DataWrapper.h"
#include "FFICall.h"
#include "Helpers.h"
using namespace v8;
using namespace std;
namespace tns {
static Class NSTimerClass = objc_getClass("NSTimer");
void ObjectManager::Init(Isolate* isolate, Local<ObjectTemplate> globalTemplate) {
globalTemplate->Set(tns::ToV8String(isolate, "__releaseNativeCounterpart"),
FunctionTemplate::New(isolate, ReleaseNativeCounterpartCallback));
}
namespace {
void LinkRegistered(v8::Isolate* isolate, ObjectWeakCallbackState* state) {
std::shared_ptr<Caches> cache = Caches::Get(isolate);
if (cache == nullptr) {
return;
}
state->head_ = &cache->ObjectManagedValues;
state->next_ = *state->head_;
if (state->next_ != nullptr) {
state->next_->prev_ = state;
}
*state->head_ = state;
}
void UnlinkRegistered(ObjectWeakCallbackState* state) {
if (state->head_ == nullptr) {
return;
}
if (state->prev_ != nullptr) {
state->prev_->next_ = state->next_;
} else if (*state->head_ == state) {
*state->head_ = state->next_;
}
if (state->next_ != nullptr) {
state->next_->prev_ = state->prev_;
}
state->head_ = nullptr;
state->prev_ = nullptr;
state->next_ = nullptr;
}
} // namespace
std::shared_ptr<Persistent<Value>> ObjectManager::Register(Local<Context> context,
const Local<Value> obj) {
Isolate* isolate = v8::Isolate::GetCurrent();
std::shared_ptr<Persistent<Value>> objectHandle =
std::make_shared<Persistent<Value>>(isolate, obj);
objectHandle->SetWrapperClassId(Constants::ClassTypes::ObjectManagedValue);
ObjectWeakCallbackState* state = new ObjectWeakCallbackState(objectHandle);
objectHandle->SetWeak(state, FinalizerCallback, WeakCallbackType::kFinalizer);
LinkRegistered(isolate, state);
return objectHandle;
}
namespace {
// The DataWrapper-tagged handles used to be reached through
// Isolate::VisitHandlesWithClassIds; they all live in Caches, so walk those
// directly instead.
template <typename Map>
void DisposeHandleMap(v8::Isolate* isolate, Map& map) {
for (auto& entry : map) {
if (entry.second == nullptr || entry.second->IsEmpty()) {
continue;
}
ObjectManager::DisposeValue(isolate, entry.second->Get(isolate), true);
}
}
void DisposeHandle(v8::Isolate* isolate,
const std::unique_ptr<v8::Persistent<v8::Function>>& handle) {
if (handle == nullptr || handle->IsEmpty()) {
return;
}
ObjectManager::DisposeValue(isolate, handle->Get(isolate), true);
}
} // namespace
void ObjectManager::DisposeAllRegistered(Isolate* isolate) {
std::shared_ptr<Caches> cache = Caches::Get(isolate);
if (cache == nullptr) {
return;
}
// Runs from ~Runtime, which holds a Locker but has not entered the isolate;
// creating handles below requires it to be entered.
Isolate::Scope isolateScope(isolate);
HandleScope scope(isolate);
// Detach the whole list first so disposal can't walk into freed entries.
ObjectWeakCallbackState* state = cache->ObjectManagedValues;
cache->ObjectManagedValues = nullptr;
while (state != nullptr) {
ObjectWeakCallbackState* next = state->next_;
std::shared_ptr<Persistent<Value>> handle = state->target_;
if (handle != nullptr && !handle->IsEmpty()) {
ObjectManager::DisposeValue(isolate, handle->Get(isolate), true);
if (handle->IsWeak()) {
handle->ClearWeak<ObjectWeakCallbackState>();
}
handle->Reset();
}
delete state;
state = next;
}
DisposeHandleMap(isolate, cache->CtorFuncs);
DisposeHandleMap(isolate, cache->ProtocolCtorFuncs);
DisposeHandleMap(isolate, cache->CFunctions);
DisposeHandleMap(isolate, cache->PrimitiveInteropTypes);
DisposeHandle(isolate, cache->InteropReferenceCtorFunc);
DisposeHandle(isolate, cache->PointerCtorFunc);
DisposeHandle(isolate, cache->FunctionReferenceCtorFunc);
}
void ObjectManager::FinalizerCallback(const WeakCallbackInfo<ObjectWeakCallbackState>& data) {
ObjectWeakCallbackState* state = data.GetParameter();
Isolate* isolate = data.GetIsolate();
Local<Value> value = state->target_->Get(isolate);
bool disposed = ObjectManager::DisposeValue(isolate, value);
if (disposed) {
UnlinkRegistered(state);
state->target_->Reset();
delete state;
} else {
state->target_->ClearWeak<void>();
state->target_->SetWeak(state, FinalizerCallback, WeakCallbackType::kFinalizer);
}
}
bool ObjectManager::DisposeValue(Isolate* isolate, Local<Value> value, bool isFinalDisposal) {
if (value.IsEmpty() || value->IsNullOrUndefined() || !value->IsObject()) {
return true;
}
Local<Object> obj = value.As<Object>();
if (obj->InternalFieldCount() > 1 && !isFinalDisposal) {
Local<Value> superValue = obj->GetInternalField(1).As<v8::Value>();
if (!superValue.IsEmpty() && superValue->IsString()) {
// Do not dispose the ObjCWrapper contained in a "super" instance
return true;
}
}
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
// NSLog(@"dispose %p", wrapper);
if (wrapper == nullptr) {
tns::SetValue(isolate, obj, nullptr);
return true;
}
if (wrapper->IsGcProtected() && !isFinalDisposal) {
return false;
}
std::shared_ptr<Caches> cache = Caches::Get(isolate);
switch (wrapper->Type()) {
case WrapperType::Struct: {
StructWrapper* structWrapper = static_cast<StructWrapper*>(wrapper);
void* data = structWrapper->Data();
std::shared_ptr<Persistent<Value>> poParentStruct = structWrapper->Parent();
if (poParentStruct != nullptr) {
Local<Value> parentStruct = poParentStruct->Get(isolate);
BaseDataWrapper* parentWrapper = tns::GetValue(isolate, parentStruct);
if (parentWrapper != nullptr && parentWrapper->Type() == WrapperType::Struct) {
StructWrapper* parentStructWrapper = static_cast<StructWrapper*>(parentWrapper);
parentStructWrapper->DecrementChildren();
}
} else {
if (structWrapper->ChildCount() == 0) {
std::pair<void*, std::string> key =
std::make_pair(data, structWrapper->StructInfo().Name());
cache->StructInstances.erase(key);
std::free(data);
} else {
return false;
}
}
break;
}
case WrapperType::ObjCObject: {
ObjCDataWrapper* objCObjectWrapper = static_cast<ObjCDataWrapper*>(wrapper);
id target = objCObjectWrapper->Data();
if (target != nil) {
// Instances is keyed on the raw address, so an entry rebuilt for a
// later object living there must survive this wrapper going away —
// only the entry that still points back at this object is ours.
auto it = cache->Instances.find(target);
if (it != cache->Instances.end()) {
Local<Value> cached = it->second->Get(isolate);
if (cached.IsEmpty() || cached == value) {
cache->Instances.erase(it);
}
}
[target release];
}
break;
}
case WrapperType::Block: {
BlockWrapper* blockWrapper = static_cast<BlockWrapper*>(wrapper);
if (blockWrapper->OwnsBlock()) {
// Balance the Block_copy taken when a native block was wrapped for JS
// (see Interop::GetResult). Block_release is the correct counterpart to
// Block_copy and runs the block's dispose helper once we drop the last
// reference. (Using CFRelease here over-released stack blocks that were
// never promoted to the heap, crashing in objc_release during GC.)
Block_release(blockWrapper->Block());
}
// Blocks created from JS callbacks (OwnsBlock() == false) are owned by
// the native code they were handed to (e.g. NSNotificationCenter);
// freeing them here would leave that code with a dangling pointer. The
// JSBlock dispose helper cleans up once the last native reference goes.
break;
}
case WrapperType::Reference: {
ReferenceWrapper* referenceWrapper = static_cast<ReferenceWrapper*>(wrapper);
if (referenceWrapper->Data() != nullptr) {
referenceWrapper->SetData(nullptr);
referenceWrapper->SetEncoding(nullptr);
}
break;
}
case WrapperType::Pointer: {
PointerWrapper* pointerWrapper = static_cast<PointerWrapper*>(wrapper);
if (pointerWrapper->Data() != nullptr) {
cache->PointerInstances.erase(pointerWrapper->Data());
if (pointerWrapper->IsAdopted()) {
std::free(pointerWrapper->Data());
pointerWrapper->SetData(nullptr);
}
}
break;
}
case WrapperType::FunctionReference: {
FunctionReferenceWrapper* funcWrapper = static_cast<FunctionReferenceWrapper*>(wrapper);
std::shared_ptr<Persistent<Value>> func = funcWrapper->Function();
if (func != nullptr) {
func->Reset();
}
break;
}
case WrapperType::AnonymousFunction: {
break;
}
case WrapperType::ExtVector: {
ExtVectorWrapper* extVectorWrapper = static_cast<ExtVectorWrapper*>(wrapper);
FFICall::DisposeFFIType(extVectorWrapper->FFIType(), extVectorWrapper->TypeEncoding());
void* data = extVectorWrapper->Data();
if (data) {
std::free(data);
}
break;
}
case WrapperType::Worker: {
WorkerWrapper* worker = static_cast<WorkerWrapper*>(wrapper);
if (!worker->isDisposed()) {
// during final disposal, inform the worker it should delete itself
if (isFinalDisposal) {
worker->MakeWeak();
}
return false;
}
break;
}
default:
break;
}
delete wrapper;
wrapper = nullptr;
tns::DeleteValue(isolate, obj);
return true;
}
void ObjectManager::ReleaseNativeCounterpartCallback(const FunctionCallbackInfo<Value>& info) {
Isolate* isolate = info.GetIsolate();
if (info.Length() != 1) {
std::ostringstream errorStream;
errorStream << "Actual arguments count: \"" << info.Length() << "\". Expected: \"1\".";
std::string errorMessage = errorStream.str();
Local<Value> error = Exception::Error(tns::ToV8String(isolate, errorMessage));
isolate->ThrowException(error);
return;
}
Local<Value> value = info[0];
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
if (wrapper == nullptr) {
std::string arg0 = tns::ToString(isolate, info[0]);
std::ostringstream errorStream;
errorStream << arg0 << " is an object which is not a native wrapper.";
std::string errorMessage = errorStream.str();
Local<Value> error = Exception::Error(tns::ToV8String(isolate, errorMessage));
isolate->ThrowException(error);
return;
}
if (wrapper->Type() != WrapperType::ObjCObject) {
return;
}
ObjCDataWrapper* objcWrapper = static_cast<ObjCDataWrapper*>(wrapper);
id data = objcWrapper->Data();
if (data != nil) {
std::shared_ptr<Caches> cache = Caches::Get(isolate);
auto it = cache->Instances.find(data);
if (it != cache->Instances.end()) {
ObjectWeakCallbackState* state = it->second->ClearWeak<ObjectWeakCallbackState>();
if (state != nullptr) {
UnlinkRegistered(state);
delete state;
}
cache->Instances.erase(it);
}
// Release the runtime's strong reference (taken when the object was first
// wrapped or adopted from an alloc/new/copy return). For instances solely
// owned by JS this deallocates immediately; for shared natives (e.g. an
// NSNotificationCenter observer token) the remaining owners keep it alive.
// Calling [data dealloc] here, as this used to do, destroyed objects that
// were still referenced elsewhere and caused use-after-free crashes.
[data release];
delete wrapper;
tns::SetValue(isolate, value.As<Object>(), nullptr);
}
}
bool ObjectManager::IsInstanceOf(id obj, Class clazz) { return [obj isKindOfClass:clazz]; }
long ObjectManager::GetRetainCount(id obj) {
if (!obj) {
return 0;
}
if (ObjectManager::IsInstanceOf(obj, NSTimerClass)) {
return 0;
}
return CFGetRetainCount(obj);
}
} // namespace tns