-
Notifications
You must be signed in to change notification settings - Fork 60
/
NLContext.m
243 lines (184 loc) · 8.04 KB
/
NLContext.m
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
//
// NLContext.m
// Nodelike
//
// Created by Sam Rijs on 10/13/13.
// Copyright (c) 2013 Sam Rijs.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#import "NLContext.h"
#import "NSObject+Nodelike.h"
#import "NLBinding.h"
#import "NLNatives.h"
#import "NLAsync.h"
@implementation NLContext
#pragma mark - JSContext
- (id)initWithVirtualMachine:(JSVirtualMachine *)virtualMachine {
self = [super initWithVirtualMachine:virtualMachine];
[NLContext attachToContext:self];
return self;
}
#pragma mark - Scope Setup
+ (void)attachToContext:(JSContext *)context {
uv_loop_t *eventLoop = uv_loop_new();
[context.virtualMachine nodelikeSet:&env_event_loop toValue:[NSValue valueWithPointer:eventLoop]];
uv_check_t *immediate_check_handle = malloc(sizeof(uv_check_t));
uv_idle_t *immediate_idle_handle = malloc(sizeof(uv_idle_t));
immediate_check_handle->data = (__bridge void *)(context);
uv_check_init(eventLoop, immediate_check_handle);
uv_unref((uv_handle_t *)immediate_check_handle);
uv_idle_init(eventLoop, immediate_idle_handle);
#ifdef DEBUG
context.exceptionHandler = ^(JSContext *ctx, JSValue *e) {
ctx.exception = e;
NSLog(@"EXC: %@; line: %@, stack: %@", e, [e valueForProperty:@"line"], [e valueForProperty:@"stack"]);
};
#endif
JSValue *process = [JSValue valueWithObject:@{
@"platform": @"darwin",
@"argv": @[],
@"env": NSProcessInfo.processInfo.environment,
@"execPath": NSBundle.mainBundle.executablePath,
@"_asyncFlags": @{},
@"moduleLoadList": @[]
} inContext:context];
JSValue __weak *weakProcess = process;
process[@"resourcePath"] = NLContext.resourcePath;
process[@"env"][@"NODE_PATH"] = [NLContext.resourcePath stringByAppendingString:@"/node_modules"];
// used in Hrtime() below
#define NANOS_PER_SEC 1000000000
// hrtime exposes libuv's uv_hrtime() high-resolution timer.
// The value returned by uv_hrtime() is a 64-bit int representing nanoseconds,
// so this function instead returns an Array with 2 entries representing seconds
// and nanoseconds, to avoid any integer overflow possibility.
// Pass in an Array from a previous hrtime() call to instead get a time diff.
process[@"hrtime"] = ^(JSValue *offset) {
uint64_t t = uv_hrtime();
if (!offset.isUndefined && offset.isObject) {
// return a time diff tuple
uint64_t seconds = [offset valueAtIndex:0].toInt32;
uint64_t nanos = [offset valueAtIndex:1].toInt32;
t -= (seconds * NANOS_PER_SEC) + nanos;
}
return @[[NSNumber numberWithUnsignedInt:(unsigned)(t / NANOS_PER_SEC)],
[NSNumber numberWithUnsignedInt:(unsigned)(t % NANOS_PER_SEC)]];
};
process[@"reallyExit"] = ^(NSNumber *code) {
exit(code.intValue);
};
process[@"_kill"] = ^(NSNumber *pid, NSNumber *sig) {
kill(pid.intValue, sig.intValue);
};
process[@"binding"] = ^(NSString *binding) {
return [NLBinding bindingForIdentifier:binding];
};
process[@"cwd"] = ^{
return @(getcwd(NULL, 0));
};
process[@"_setupAsyncListener"] = ^(JSValue *o, JSValue *r, JSValue *l, JSValue *u) {
[NLAsync setupAsyncListener:o run:r load:l unload:u];
[weakProcess deleteProperty:@"_setupAsyncListener"];
};
process[@"_setupNextTick"] = ^(JSValue *obj, JSValue *func) {
assert(obj.isObject);
assert(func.isObject);
[NLAsync setupNextTick:obj func:func];
[weakProcess deleteProperty:@"_setupNextTick"];
};
id getNeedImmediateCallback = ^{
return [NSNumber numberWithBool:uv_is_active((uv_handle_t *)immediate_check_handle)];
};
id setNeedImmediateCallback = ^(JSValue *value) {
bool active = uv_is_active((uv_handle_t *)immediate_check_handle);
if (active == value.toBool)
return;
if (active) {
uv_check_stop(immediate_check_handle);
uv_idle_stop(immediate_idle_handle);
} else {
uv_check_start(immediate_check_handle, CheckImmediate);
uv_idle_start(immediate_idle_handle, IdleImmediateDummy);
}
};
[process defineProperty:@"_needImmediateCallback"
descriptor:@{@"get": getNeedImmediateCallback, @"set": setNeedImmediateCallback}];
[context.virtualMachine nodelikeSet:&env_process_object toValue:process];
JSValue *noop = [context evaluateScript:@"(function(){})"];
context[@"DTRACE_NET_SERVER_CONNECTION"] = noop;
context[@"DTRACE_NET_STREAM_END"] = noop;
context[@"DTRACE_HTTP_CLIENT_REQUEST"] = noop;
context[@"DTRACE_HTTP_CLIENT_RESPONSE"] = noop;
context[@"DTRACE_HTTP_SERVER_REQUEST"] = noop;
context[@"DTRACE_HTTP_SERVER_RESPONSE"] = noop;
context[@"DTRACE_NET_SOCKET_READ"] = noop;
context[@"DTRACE_NET_SOCKET_WRITE"] = noop;
context[@"COUNTER_NET_SERVER_CONNECTION"] = noop;
context[@"COUNTER_NET_SERVER_CONNECTION_CLOSE"] = noop;
context[@"COUNTER_HTTP_SERVER_REQUEST"] = noop;
context[@"COUNTER_HTTP_SERVER_RESPONSE"] = noop;
context[@"COUNTER_HTTP_CLIENT_REQUEST"] = noop;
context[@"COUNTER_HTTP_CLIENT_RESPONSE"] = noop;
[context evaluateScript:@"Error.captureStackTrace = function (e) { e.stack = 'Trace: ' + e.message };"];
[context evaluateScript:@"Number.isFinite = function (value) { return typeof value === 'number' && isFinite(value); };"];
JSValue *constructor = [context evaluateScript:[NLNatives source:@"node"]];
[constructor callWithArguments:@[process]];
}
#if TARGET_OS_IPHONE
+ (void)attachToWebView:(UIWebView *)webView {
[self attachToContext:[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]];
}
#endif
#pragma mark - Event Handling
+ (uv_loop_t *)eventLoopInContext:(JSContext *)context {
return ((NSValue *)[context.virtualMachine nodelikeGet:&env_event_loop]).pointerValue;
}
static dispatch_queue_t dispatchQueue () {
static dispatch_queue_t queue;
static dispatch_once_t token = 0;
dispatch_once(&token, ^{
queue = dispatch_queue_create("eventLoop", DISPATCH_QUEUE_SERIAL);
});
return queue;
}
+ (void)runEventLoopSyncInContext:(JSContext *)context {
//dispatch_sync(dispatchQueue(), ^{
uv_run([NLContext eventLoopInContext:context], UV_RUN_DEFAULT);
//});
}
+ (void)runEventLoopAsyncInContext:(JSContext *)context {
dispatch_async(dispatchQueue(), ^{
uv_run([NLContext eventLoopInContext:context], UV_RUN_DEFAULT);
});
}
- (void)runProcessAsyncQueue {
[NLContext runProcessAsyncQueue:self];
}
+ (void)runProcessAsyncQueue:(JSContext *)context {
[NLAsync makeGlobalCallback:nil fromObject:[context.virtualMachine nodelikeGet:&env_process_object] withArguments:nil];
}
- (int)emitExit {
return [NLContext emitExit:self];
}
+ (int)emitExit:(JSContext *)context {
JSValue *process = [context.virtualMachine nodelikeGet:&env_process_object];
process[@"_exiting"] = [NSNumber numberWithBool:YES];
int code = process[@"exitCode"].toInt32;
[NLAsync makeGlobalCallback:process[@"emit"]
fromObject:process
withArguments:@[@"exit", @(code)]];
return code;
}
#pragma mark - Helpers
+ (NSString *)resourcePath {
return [NSBundle bundleForClass:NLContext.class].resourcePath;
}
static void CheckImmediate(uv_check_t *handle, int status) {
JSContext *context = (__bridge JSContext *)(handle->data);
JSValue *process = [context.virtualMachine nodelikeGet:&env_process_object];
JSValue *callback = [process valueForProperty:@"_immediateCallback"];
[NLAsync makeGlobalCallback:callback fromObject:process withArguments:@[]];
}
static void IdleImmediateDummy(uv_idle_t *handle, int status) {}
@end