Repository navigation
Expand file tree
/
Copy pathObjectManager.mm
More file actions
418 lines (368 loc) · 15 KB
/
Copy pathObjectManager.mm
File metadata and controls
418 lines (368 loc) · 15 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
#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, and
// claim every state up front: disposing one entry can re-enter JS from
// -dealloc and reach __releaseNativeCounterpart for any other entry this
// walk still owns.
ObjectWeakCallbackState* state = cache->ObjectManagedValues;
cache->ObjectManagedValues = nullptr;
for (ObjectWeakCallbackState* claimed = state; claimed != nullptr; claimed = claimed->next_) {
claimed->disposing_ = true;
}
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();
if (state->disposing_) {
// Another frame owns this state's teardown — the DisposeAllRegistered
// walk, whose pre-claimed entries a nested collection can still condemn.
// Re-arm to satisfy the finalizer contract on this node and leave the
// clear/reset/delete to the owner.
state->target_->ClearWeak<void>();
state->target_->SetWeak(state, FinalizerCallback, WeakCallbackType::kFinalizer);
return;
}
state->disposing_ = true;
Local<Value> value = state->target_->Get(isolate);
bool disposed = ObjectManager::DisposeValue(isolate, value);
state->disposing_ = false;
// Disposal releases the native counterpart, and a -dealloc reached that way
// can reset this very handle (the collection adapters reset the persistent
// they were built from). An empty handle means the node is already freed, so
// there is nothing left to reset or re-arm -- ClearWeak/SetWeak would write
// through a dead slot -- and the registration must be retired even when
// disposal was refused.
if (disposed || state->target_->IsEmpty()) {
state->target_->Reset();
UnlinkRegistered(state);
delete state;
return;
}
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:
// Lives in the struct object's ArrayBuffer storage, which the GC frees.
return true;
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()) {
// A block created from a JS callback is owned by the native code it
// was handed to (e.g. NSNotificationCenter), and it owns this wrapper
// (see Interop::JSBlock): its dispose helper frees both once the last
// native reference goes, possibly after this isolate is gone.
return true;
}
// 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());
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);
// Final disposal lets go of the wrapper for good, and only deletes it
// when the worker thread is done with it; otherwise that thread deletes
// it when it ends.
//
// A weak callback deletes the wrapper only when the worker thread is
// done with it, and changes nothing otherwise. A running worker's Worker
// object is rooted (WorkerWrapper::RootWorkerObject), so a weak callback
// should not reach a live worker at all. The refusal stays as the floor
// under that: re-arming keeps the wrapper alive for another cycle, which
// is safe, whereas freeing it while the thread still posts through it is
// not. Reaching it is not free either -- a re-armed handle that is also a
// weak-collection key can corrupt the collector's ephemeron bookkeeping
// -- so it is a fallback, not a mechanism to rely on.
bool lastHolder = isFinalDisposal ? worker->ReleaseFromParent() : worker->HeldByParentOnly();
if (!lastHolder) {
return false;
}
break;
}
default:
break;
}
// A branch above can run arbitrary code -- [target release] reaching an ObjC
// -dealloc is the reachable one -- and that code may detach this wrapper or
// attach a different one. The object's internal field is the wrapper's owner,
// so only a wrapper still sitting in it is ours to free.
if (tns::GetValue(isolate, obj) == wrapper) {
delete wrapper;
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;
}
// The lookup, the Instances key and the final SetValue must all address the
// same object, so a Proxy is resolved once here.
Local<Value> value = tns::UnwrapProxy(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()) {
std::shared_ptr<Persistent<Value>> handle = it->second;
ObjectWeakCallbackState* state =
handle->IsWeak() ? handle->ClearWeak<ObjectWeakCallbackState>() : nullptr;
if (state != nullptr && state->disposing_) {
// Reached from a -dealloc running inside this handle's own finalizer:
// that frame already released the native counterpart and owns the
// state, so restore the weakness and let it finish.
handle->SetWeak(state, FinalizerCallback, WeakCallbackType::kFinalizer);
return;
}
cache->Instances.erase(it);
if (state != nullptr) {
// Reset before deleting the state: it frees the node, which clears the
// pending-finalizer bit and guarantees no callback can reach the freed
// parameter.
handle->Reset();
UnlinkRegistered(state);
delete state;
}
}
// 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.
// Read before the release below: an adapter claim's -dealloc frees the
// wrapper, so it must not be touched afterwards.
bool adapterClaim = objcWrapper->IsAdapterClaim();
[data release];
// The release above can run a -dealloc that detaches this wrapper; the
// internal field owns it, so free only what is still attached. An
// adapter's claim is exempt: the adapter owns it exclusively and deletes
// it from its own -dealloc even after isolate teardown, so retiring it
// here would leave the adapter holding a stale pointer it later frees
// again.
if (!adapterClaim && tns::GetValue(isolate, value) == wrapper) {
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