-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathdotnet.js
More file actions
290 lines (256 loc) · 14 KB
/
Copy pathdotnet.js
File metadata and controls
290 lines (256 loc) · 14 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
"use strict";
// GOAL: Using the registered COM DotNetBridge.dll, build objects to represent a root namespace and contained types.
const Win32 = require('./win32');
const Struct = require('./struct');
const GUID = require('./guid');
const COM = require('./com');
function Warn(message) { if ("CLRDebug" in global) console.warn(message); }
// InProc component that is expected to be found in the registry.
var CLSID_DotNetBridge = GUID.alloc("ddb71722-f7e5-4c45-817e-cc1b84bfab4e");
var IDotNetBridge = new COM.Interface(COM.IUnknown, {
CreateObject: [0, ['pointer', 'pointer', 'pointer']],
DescribeObject: [1, ['pointer', 'pointer', 'pointer']],
CreateDelegate: [2, ['pointer', 'pointer', 'pointer']],
InvokeMethod: [3, ['pointer', 'pointer', 'pointer', 'pointer', 'pointer', 'int', 'pointer']],
ReleaseObject: [4, ['pointer', 'pointer']],
DescribeNamespace: [5, ['pointer', 'pointer']],
}, "ea688a1d-4be4-4cae-b2a3-9a389fcd1c8b");
function DotNetBridge() {
console.log("[*] Creating DotNetBridge");
const bridge = COM.CreateInstance(CLSID_DotNetBridge, COM.ClassContext.InProc, IDotNetBridge);
function SerializedArgsToJson(params) {
if (typeof params === 'undefined') { params = []; }
if (Object.prototype.toString.call(params) === '[object Array]') {
for (var i = 0; i < params.length; ++i) {
if (params[i] && params[i].$Clr_Serialize) params[i] = params[i].$Clr_Serialize();
}
return JSON.stringify(params);
} else {
throw new Error("Bad args " + params);
}
}
function DoCall(method) {
var args = [];
for (var i = 1; i < arguments.length; ++i) { args[i - 1] = arguments[i]; }
var outPtr = new Struct({ 'value': 'pointer' });
args[args.length] = outPtr.Get();
COM.ThrowIfFailed(bridge[method].apply(bridge[method], args));
var ret = JSON.parse(Memory.readUtf16String(outPtr.value));
if (ret && ret.__ERROR) { throw Error(ret.Message + "\n" + ret.Stack + "\n") }
else if (ret && ret.__OBJECT) { ret = new ObjectWrapper(ret); }
return ret;
}
this.CreateObject = function(typeInfo, args) {
return typeInfo.IsDelegate ?
DoCall("CreateDelegate", Memory.allocUtf16String(typeInfo.TypeName), JsonDelegate(args)) :
DoCall("CreateObject", Memory.allocUtf16String(typeInfo.TypeName), Memory.allocUtf16String(SerializedArgsToJson(args)));
}
this.DescribeObject = function(typeName, objHandle) {
if (typeof typeName === "string") {
typeName = Memory.allocUtf16String(typeName);
objHandle = NULL;
} else {
objHandle = Memory.allocUtf16String(JSON.stringify(objHandle));
typeName = NULL;
}
return DoCall("DescribeObject", typeName, objHandle);
}
this.ReleaseObject = function(objHandle) {
return DoCall("ReleaseObject", Memory.allocUtf16String(JSON.stringify(objHandle)));
}
this.DescribeNamespace = function(namespaceName) {
return DoCall("DescribeNamespace", Memory.allocUtf16String(namespaceName));
}
this.InvokeMethod = function (objHandle, typeInfo, method, args, genericTypes, returnBoxed) {
return DoCall("InvokeMethod",
objHandle == null ? NULL : Memory.allocUtf16String(JSON.stringify(objHandle)),
Memory.allocUtf16String(typeInfo.TypeName),
Memory.allocUtf16String(method),
Memory.allocUtf16String(SerializedArgsToJson(args)),
genericTypes ? Memory.allocUtf16String(JSON.stringify(genericTypes.$Clr_Handle)) : NULL,
returnBoxed ? 1 : 0);
};
}
// Ensure the bridge is a singleton, even if this script is included multiple times.
function GetBridgeInstance() {
const CLR_BRIDGE_TAG = "$$CLRBRIDGE";
global[CLR_BRIDGE_TAG] = (CLR_BRIDGE_TAG in global) ? global[CLR_BRIDGE_TAG] : new DotNetBridge();
return global[CLR_BRIDGE_TAG];
}
const BridgeExports = GetBridgeInstance();
var _objects = [];
var _pinnedNativeCallbackObjects = [];
var _pinnedObjects = [];
function JsonDelegate(func) {
var callback = new NativeCallback(function (argsPtr) {
// Unpack json args and resolve object references.
var args = JSON.parse(Memory.readUtf16String(argsPtr));
for (var i = 0; i < args.length; ++i) {
if (args[i].__OBJECT) args[i] = new ObjectWrapper(args[i]);
}
var ret = func.apply(func, args);
// Pack up the result into object references
if (Object.prototype.toString.call(ret) === '[object Array]') {
for (var i = 0; i < ret.length; ++i) {
if (ret[i].$Clr_Serialize) ret[i] = ret[i].$Clr_Serialize();
}
}
if (ret) {
if (ret.$Clr_Serialize) ret = ret.$Clr_Serialize();
return Memory.allocUtf16String(JSON.stringify(ret));;
}
return NULL;
}, 'pointer', ['pointer'], Win32.Abi);
// Save a pointer somewhere in javascript, the GC is so quick it'll clean up before we have a chance to call back.
_pinnedNativeCallbackObjects.push(callback);
return callback;
}
function TypeInstance(typeName) { return new TypeWrapper("System.Type").GetType(typeName); }
function ExposeMethodsFromType(self, typeInfo) {
function CreateMethod(self, method) {
var invokeMethod = function () { return self.$Clr_Invoke(method.Name, Array.prototype.slice.call(arguments, 0)); };
invokeMethod.Box = function () { return self.$Clr_Invoke(method.Name, Array.prototype.slice.call(arguments, 0), null, true); };
invokeMethod.Of = function () {
var genericTypes = new TypeWrapper("System.Array").CreateInstance(new TypeInstance("System.Type"), arguments.length);
for (var i = 0; i < arguments.length; ++i) { genericTypes.SetValue(arguments[i].$Clr_TypeOf(), i); }
var invokeGenericMethod = function () { return self.$Clr_Invoke(method.Name, Array.prototype.slice.call(arguments, 0), genericTypes); }
invokeGenericMethod.Box = function () { return self.$Clr_Invoke(method.Name, Array.prototype.slice.call(arguments, 0), genericTypes, true); }
return invokeGenericMethod;
};
// Wire get_ and set_ to a property get/set.
if ((method.Name.startsWith("get_") && method.Parameters.length == 0) ||
(method.Name.startsWith("set_") && method.Parameters.length == 1)) {
try {
var shortMethodName = method.Name.slice("get_".length);
Object.defineProperty(self, shortMethodName, {
get: function () { return self.$Clr_Invoke("get_" + shortMethodName, []); },
set: function (newValue) { return self.$Clr_Invoke("set_" + shortMethodName, [newValue]); },
});
} catch (e) { Warn("Can't define '" + shortMethodName + "': " + e); }
// wire add_ and remove_ to an event registration object.
} else if ((method.Name.startsWith("add_") && method.Parameters && method.Parameters.length == 1) ||
(method.Name.startsWith("remove_") && method.Parameters && method.Parameters.length == 1)) {
var shortMethodName = method.Name.substring(method.Name.startsWith("add_") ? "add_".length : "remove_".length)
if (!self[shortMethodName]) Object.defineProperty(self, shortMethodName, {
get: function () {
return new function () {
this.add = function (delegate) {
self.$Clr_Invoke("add_" + shortMethodName, [delegate]);
return delegate; // delegate.toString() will act as a token for removal.
};
this.remove = function (delegate) {
// token = obj += delegate ... token is delegate.toString which is JSON by convention.
if (typeof delegate == "string") { delegate = new ObjectWrapper(JSON.parse(delegate)); }
return self.$Clr_Invoke("remove_" + shortMethodName, [delegate]);
};
// This makes it "" + other.toString() in the setter below when doing "handler += other"
this.toString = function () { return ""; }
}
},
set: function (objHandle_string) { self.$Clr_Invoke("add_" + shortMethodName, [new ObjectWrapper(JSON.parse(objHandle_string))]); },
});
} else {
self[method.Name] = invokeMethod;
}
}
function ExposeField(self, name) {
Object.defineProperty(self, name, {
get: function () { return self.$Clr_Invoke(name, []); },
set: function (value) { return self.$Clr_Invoke(name, [value]); },
});
}
for (var i = 0; typeInfo.Methods && i < typeInfo.Methods.length; ++i) { CreateMethod(self, typeInfo.Methods[i]); }
for (var i = 0; typeInfo.Fields && i < typeInfo.Fields.length; ++i) { ExposeField(self, typeInfo.Fields[i]); }
}
function TypeWrapper(typeNameOrTypeInfo) {
var typeInfo = typeNameOrTypeInfo;
if (typeof typeNameOrTypeInfo == "string") {
typeInfo = BridgeExports.DescribeObject(typeNameOrTypeInfo, null);
}
function ExposeNestedTypesFromType(self, typeInfo) {
function CreateValue(self, name) {
try {
var shortName = name.replace(typeInfo.TypeName + "+", "");
Object.defineProperty(self, shortName, { get: function () { return new TypeWrapper(name); }});
} catch (e) { Warn("Can't define " + name); }
}
for (var i = 0; typeInfo.NestedTypes && i < typeInfo.NestedTypes.length; ++i) CreateValue(self, typeInfo.NestedTypes[i]);
}
var ConstructorFunction = function () { return BridgeExports.CreateObject(typeInfo, typeInfo.IsDelegate ? arguments[0] : Array.prototype.slice.call(arguments)); };
ConstructorFunction.toString = function () { return "[ClrType " + typeInfo.TypeName + "]"; }
ConstructorFunction.$Clr_Serialize = function() { return ConstructorFunction.$Clr_TypeOf().$Clr_Handle; }
ConstructorFunction.$Clr_TypeOf = function () { return new TypeInstance(typeInfo.TypeName); }
ConstructorFunction.$Clr_Invoke = function (method, args, genericTypes, returnBoxed) {
return BridgeExports.InvokeMethod(null, typeInfo, method, args, genericTypes, returnBoxed);
}
// Dictionary<int,string> -> Dictionary.Of(System.Int, System.String)
ConstructorFunction.Of = function () {
var genericTypes = new TypeWrapper("System.Array").CreateInstance(new TypeInstance("System.Type"), arguments.length);
for (var i = 0; i < arguments.length; ++i) { genericTypes.SetValue(arguments[i].$Clr_TypeOf(), i); }
var genericType = new TypeWrapper(typeInfo.TypeName + "`" + arguments.length).$Clr_TypeOf().MakeGenericType(genericTypes);
return new TypeWrapper(genericType.FullName);
}
ExposeMethodsFromType(ConstructorFunction, typeInfo);
ExposeNestedTypesFromType(ConstructorFunction, typeInfo);
return ConstructorFunction;
}
function ObjectWrapper(objHandle) {
var typeInfo = BridgeExports.DescribeObject(NULL, objHandle);
this.$Clr_Serialize = function() { return objHandle; }
this.$Clr_Handle = objHandle;
this.$Clr_Invoke = function (method, args, genericTypes, returnBoxed) {
return BridgeExports.InvokeMethod(objHandle, typeInfo, method, args, genericTypes, returnBoxed);
}
if (typeInfo.IsEnum) {
this.value = typeInfo.EnumValue;
this.toString = function () { return this.ToString(); } // Get the symbol name for the current value.
} else if (typeInfo.IsDelegate) {
this.toString = function () { return JSON.stringify(objHandle); }; // Used in event add_/remove_ for "+=" semantics.
} else {
this.toString = function () { return "[ClrObject " + typeInfo.TypeName + ": " + this.ToString() + "]"; };
}
ExposeMethodsFromType(this, typeInfo);
_objects.push(this);
}
function NamespaceWrapper(namespaceName) {
function CreateProperty(self, leafName, isType, callback) {
try {
var isSimplifiedName = leafName.indexOf("`") > -1;
var simpleLeafName = isSimplifiedName ? leafName.substring(0, leafName.indexOf("`")) : leafName;
Object.defineProperty(self, simpleLeafName, { get: function () { return callback(simpleLeafName, isType, isSimplifiedName); }});
} catch (e) { Warn("Couldn't define " + leafName + " on " + namespaceName + ":\n" + e); }
}
var namespaceInfo = BridgeExports.DescribeNamespace(namespaceName);
for (var i = 0; i < namespaceInfo.length; ++i) {
CreateProperty(this, namespaceInfo[i].Name, namespaceInfo[i].IsType,
function (leafName, isType, isMangled) {
var fullName = namespaceName + "." + leafName;
if (isType) {
try {
return new TypeWrapper(fullName);
} catch (e) {
if (isMangled) {
// PROBLEM: Given Func`1, Func *may not* exist.
// SOLUTION: Give back an object for the sole purpose of calling .Of() on to access Func`1 and so on.
return new TypeWrapper({ TypeName: fullName });
} else throw e;
}
} else {
return new NamespaceWrapper(fullName);
}
});
}
}
module.exports = {
Namespace: NamespaceWrapper,
Prune: function () { // Enable .net GC to clean up objects (remove reference in js and in .net).
var outstanding = _objects.length;
for (var i = outstanding - 1; i > -1; --i) BridgeExports.ReleaseObject(_objects[i].$Clr_Handle);
_objects.length = 0;
return outstanding;
},
Pin: function (obj) { // Prevent an object from being garbage collected.
_objects.splice(_objects.indexOf(obj), 1);
_pinnedObjects.push(obj);
},
};