-
Notifications
You must be signed in to change notification settings - Fork 126
/
Copy pathimport.js
354 lines (319 loc) · 10.7 KB
/
import.js
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
/**
* Logic for importing a Framework into the node process.
*
* "Importing" a framework is a multi-step process:
*
* 1. `resolve()` the absolute path of the given framework name.
* 1. Load the framework's binary `dylib` file into the process.
* 1. Usually locate the `BridgeSupport` files for the framework and process.
* 1. Define any new class getters for newly loaded Objective-C classes.
*/
/*!
* Module dependencies.
*/
var fs = require('fs')
, ref = require('ref')
, read = fs.readFileSync
, path = require('path')
, core = require('./core')
, Class = require('./class')
, join = path.join
, basename = path.basename
, exists = fs.existsSync || path.existsSync
, SUFFIX = '.framework'
, PATH = [
'/System/Library/Frameworks'
, '/System/Library/PrivateFrameworks'
, '/Library/Frameworks'
, process.env['HOME'] + '/Library/Frameworks'
]
, DY_SUFFIX = '.dylib'
, BS_SUFFIX = '.bridgesupport';
/*!
* A cache for the frameworks that have already been imported.
*/
var cache = {}
/*!
* Architecture-specific functions that return the Obj-C type or value from one
* of these BridgeSupport XML nodes.
*/
var typePrefix = (process.arch=='x64') ? '64' : '';
var typeSuffix = (process.arch=='x64') ? '' : '64';
function getType(node) {
return node.attrib['type' + typePrefix] || node.attrib['type' + typeSuffix];
}
function getValue(node) {
return node.attrib['value' + typePrefix] || node.attrib['value' + typeSuffix];
}
function fastIndexOf(subject, target, fromIndex) {
var length = subject.length, i = 0;
if (typeof fromIndex === 'number') {
i = fromIndex;
if (i < 0) {
i += length;
if (i < 0) i = 0;
}
}
for (; i < length; i++) if (subject[i] === target) return i;
return -1;
}
function parseAttrib(tag,attr) {
var coll = {}, split = 0, name = '', value = '', i=0;
attr = attr.split('\' ');
for(; i < attr.length; i++) {
split = fastIndexOf(attr[i], "=");
name = attr[i].substring(0, split);
value = attr[i].substring(split+2, (i==attr.length-1) ? attr[i].length-1 : undefined);
if(fastIndexOf(value, '&') != -1) value = value.replace(quoteRegExp, '"')
coll[name]=value;
}
return coll;
}
function parseTag(names, tag, content) {
var sattr = 2 + tag.name.length
, eattr = fastIndexOf(content,'>',1)
, isBodyless = (content[eattr - 1]=='/');
var sbody = eattr + 1
, ebody = isBodyless ? eattr - 1 : content.indexOf('</'+tag.name, eattr); // cannot use fastIndexOf
tag.end = isBodyless ? ebody + 2 : ebody + tag.name.length + 3;
tag.attrib = parseAttrib(tag,content.substring(sattr, eattr + (isBodyless ? -1 : 0)));
if(sbody == ebody || names[tag.name] == null) tag.children = [];
else tag.children = findTags(names[tag.name], content.substring(sbody,ebody));
return tag;
}
function findTags(names, content) {
var ndx = 0,
i = 0,
tagKeys = Object.keys(names),
ftags=[ { end: 1 } ],
key = '';
do {
content = content.substring(ndx);
for(i=0; i < tagKeys.length; i++) {
key = tagKeys[i];
// quick break for non-matching keys, cheaper on fails (which happen a lot)
// rather than a full substring. Three is both the max benefit and after that
// we'll cause some odd behavior (e.g., matching conditions)
if( content[1] == key[0] &&
content[2] == key[1] &&
content[3] == key[2])
{
if(key.length < 4 || key == content.substring(1,key.length+1)) {
delete ftags[ftags.length-1].end;
ftags.push(parseTag(names,{name:key},content));
break;
}
}
}
ndx = fastIndexOf(content, '<', ftags[ftags.length-1].end );
} while(ndx != -1);
ftags.shift();
return ftags;
}
var quoteRegExp = new RegExp(""","g");
/**
* This module takes care of loading the BridgeSupport XML files for a given
* framework, and parsing the data into the given framework object.
*
* ### References:
*
* * [`man 5 BridgeSupport`](http://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man5/BridgeSupport.5.html)
* * [BridgeSupport MacOS Forge website](http://bridgesupport.macosforge.org)
*/
/**
* Attempts to retrieve the BridgeSupport files for the given framework.
* It synchronously reads the contents of the bridgesupport files and parses
* them in order to add the symbols that the Obj-C runtime functions cannot
* determine.
*/
function parseBridgeFile(fw, onto, recursive) {
var bridgedir = join(fw.basePath, 'Resources', 'BridgeSupport')
, bridgeSupportXML = join(bridgedir, fw.name + BS_SUFFIX)
, bridgeSupportDylib = join(bridgedir, fw.name + DY_SUFFIX);
// If there's no BridgeSupport file, then bail...
if (!exists(bridgeSupportXML)) return;
// Load the "inline" dylib if it exists
if (exists(bridgeSupportDylib)) fw.lib = core.dlopen(bridgeSupportDylib);
var tags = {'function':{'retval':{'retval':null,'arg':null},'arg':{'retval':null,'arg':null}},'depends_on':null,'string_constant':null,'enum':null,'struct':null,'constant':null};
var nodes = findTags(tags, read(bridgeSupportXML, 'utf8'));
nodes.forEach(function (node) {
var name = node.attrib.name;
if(node.name == 'depends_on')
{
if(recursive && recursive > 0)
importFramework(node.attrib.path, true, onto, --recursive);
}
else if (node.name == 'string_constant')
{
onto[name] = getValue(node);
}
else if (node.name == 'enum')
{
if (node.attrib.ignore !== "true") onto[name] = parseInt(getValue(node));
}
else if (node.name == 'struct')
{
var type = getType(node);
onto[name] = core.Types.knownStructs[core.Types.parseStructName(type)] = type;
}
else if (node.name == 'constant')
{
var type = getType(node);
Object.defineProperty(onto, name, {
enumerable: true,
configurable: true,
get: function () {
var ptr = fw.lib.get(name);
var derefPtr = ref.get(ptr, 0, core.Types.map(type))
delete onto[name];
return onto[name] = core.wrapValue(derefPtr, type);
}
});
}
else if (node.name == 'function')
{
if(node.attrib.original) { // Support for function aliases
onto[node.attrib.original] = onto[node.attrib.name];
return;
}
var isInline = node.attrib.inline === 'true' ? true : false
, isVariadic = node.attrib.variadic === 'true' ? true : false
, passedTypes = {args:[],name:name};
node.children.forEach(function (n, i) {
var type = n.name;
if(type == 'arg') passedTypes.args.push(flattenNode(n));
else if (type == 'retval') passedTypes.retval = flattenNode(n);
});
Object.defineProperty(onto, name, {
enumerable: true,
configurable: true,
get: function () {
var ptr = fw.lib.get(name);
var unwrapper = core.createUnwrapperFunction(ptr, passedTypes, isVariadic);
delete onto[name];
return onto[name] = unwrapper;
}
});
}
});
}
function flattenNode (node) {
var rnode = {};
rnode.type = getType(node);
if (node.attrib.function_pointer === 'true') {
rnode.args = [];
node.children.forEach(function (n) {
if(n.name == 'arg') rnode.args.push(flattenNode(n));
else if(n.name == 'retval') rnode.retval = flattenNode(n);
});
}
return rnode;
}
/**
* Accepts a single framework name and resolves it into an absolute path
* to the base directory of the framework.
*
* In most cases, you will not need to use this function in your code.
*
* $.resolve('Foundation')
* // '/System/Library/Frameworks/Foundation.framework'
*
* @param {String} framework The framework name or path to resolve.
* @return {String} The resolved framework path.
*/
function resolve (framework) {
// strip off a trailing slash if present
if (framework[framework.length-1] == '/')
framework = framework.slice(0, framework.length-1);
// already absolute, return as-is
if (~framework.indexOf('/')) return framework;
var i=0, l=PATH.length, rtn=null;
for (; i<l; i++) {
rtn = join(PATH[i], framework + SUFFIX);
if (exists(rtn)) return rtn;
}
throw new Error('Could not resolve framework: ' + framework);
}
/**
* Allocates a new pointer to this type. The pointer points to `nil` initially.
* This is meant for creating a pointer to hold an NSError*, and pass a ref()
* to it into a method that accepts an 'error' double pointer.
* XXX: Tentative API - name will probably change
*/
function allocReference(classWrap) {
// We do some "magic" here to support the dereferenced
// pointer to become an obj-c type.
var ptr = ref.alloc('pointer', null);
ptr._type = '@';
var _ref = ptr.ref;
ptr.ref = function() {
var v = _ref.call(ptr,arguments);
var _deref = v.deref;
v.deref = function() {
var rtnval = _deref.call(v,arguments)
return core.wrapValue(rtnval,'@');
};
return v;
};
return ptr;
}
/**
* Accepts a single framework name and imports it into the current node process.
* `framework` may be a relative (singular) framework name, or a path (relative or
* absolute) to a Framework directory.
*
* $.NSObject // undefined
*
* $.import('Foundation')
*
* $.NSObject // [Class: NSObject]
*
* @param {String} framework The framework name or path to load.
*/
function importFramework (framework, skip, onto, recursive) {
framework=resolve(framework);
var shortName=basename(framework, SUFFIX);
// Check if the framework has already been loaded
var fw=cache[shortName];
if (fw) return;
// Load the main framework binary file
var frameworkPath = join(framework, shortName);
var lib = core.dlopen(frameworkPath);
fw = {
lib: lib,
name: shortName,
basePath: framework,
binaryPath: frameworkPath
};
// cache before loading bridgesupport files
cache[shortName] = fw;
// Parse the BridgeSupport file and inline dylib, for the C functions, enums,
// and other symbols not introspectable at runtime.
parseBridgeFile(fw, onto, recursive);
// Iterate through the loaded classes list and define "setup getters" for them.
if (!skip) {
var classes = core.getClassList();
classes.forEach(function (c) {
if (c in onto) return;
Object.defineProperty(onto, c, {
enumerable: true,
configurable: true,
get: function () {
var clazz = Class.getClassByName(c, onto);
delete onto[c];
return onto[c] = clazz;
}
});
});
}
}
/*!
* Module exports.
*/
exports.import = importFramework;
exports.resolve = resolve;
exports.PATH = PATH;
exports.allocReference = allocReference;
exports.createBlock = function (func, types) {
return core.wrapValue(core.createBlock(func, types), '@');
};