forked from ClearFoundry/ClearScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsScriptItem.cs
More file actions
478 lines (379 loc) · 16.5 KB
/
Copy pathWindowsScriptItem.cs
File metadata and controls
478 lines (379 loc) · 16.5 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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.ClearScript.JavaScript;
using Microsoft.ClearScript.Util;
using Microsoft.ClearScript.Util.COM;
namespace Microsoft.ClearScript.Windows.Core
{
internal class WindowsScriptItem : ScriptItem, IWindowsScriptObject, IDictionary<string, object>, IWindowsScriptItemTag
{
private readonly WindowsScriptEngine engine;
private readonly IDispatchEx target;
private WindowsScriptItem holder;
private readonly InterlockedOneWayFlag disposedFlag = new InterlockedOneWayFlag();
private WindowsScriptItem(WindowsScriptEngine engine, IDispatchEx target)
{
this.engine = engine;
this.target = target;
}
public static object Wrap(WindowsScriptEngine engine, object obj)
{
Debug.Assert(!(obj is IScriptMarshalWrapper));
if (obj == null)
{
return null;
}
if ((obj is IDispatchEx target) && (obj.GetType().IsCOMObject))
{
return (engine is IJavaScriptEngine) ? new WindowsJavaScriptObject(engine, target) : new WindowsScriptItem(engine, target);
}
return obj;
}
private IScriptEngineException GetScriptError(Exception exception)
{
if (TryGetScriptError(exception, out var scriptError))
{
return scriptError;
}
return new ScriptEngineException(engine.Name, exception.Message, null, HResult.CLEARSCRIPT_E_SCRIPTITEMEXCEPTION, false, false, null, exception);
}
private bool TryGetScriptError(Exception exception, out IScriptEngineException scriptError)
{
// WORKAROUND: Windows Script items often throw ugly exceptions. The code here
// attempts to clean up specific cases.
while (exception is TargetInvocationException)
{
exception = exception.InnerException;
}
scriptError = exception as IScriptEngineException;
if (scriptError != null)
{
return true;
}
if (exception is COMException comException)
{
var result = comException.ErrorCode;
if (((result == HResult.SCRIPT_E_REPORTED) || (result == HResult.CLEARSCRIPT_E_HOSTEXCEPTION)) && (engine.CurrentScriptFrame != null))
{
scriptError = engine.CurrentScriptFrame.ScriptError ?? engine.CurrentScriptFrame.PendingScriptError;
if (scriptError != null)
{
return true;
}
var hostException = engine.CurrentScriptFrame.HostException;
if (hostException != null)
{
scriptError = new ScriptEngineException(engine.Name, hostException.Message, null, HResult.CLEARSCRIPT_E_HOSTEXCEPTION, false, true, null, hostException);
return true;
}
}
else if (HResult.GetFacility(result) == HResult.FACILITY_CONTROL)
{
// These exceptions often have awful messages that include COM error codes.
// The script engine itself may be able to provide a better message.
if (engine.RuntimeErrorMap.TryGetValue(HResult.GetCode(result), out var runtimeErrorMessage) && (runtimeErrorMessage != exception.Message))
{
scriptError = new ScriptEngineException(engine.Name, runtimeErrorMessage, null, HResult.CLEARSCRIPT_E_SCRIPTITEMEXCEPTION, false, false, null, exception.InnerException);
return true;
}
if (engine.SyntaxErrorMap.TryGetValue(HResult.GetCode(result), out var syntaxErrorMessage) && (syntaxErrorMessage != exception.Message))
{
scriptError = new ScriptEngineException(engine.Name, syntaxErrorMessage, null, HResult.CLEARSCRIPT_E_SCRIPTITEMEXCEPTION, false, false, null, exception.InnerException);
return true;
}
}
else if ((result == HResult.DISP_E_MEMBERNOTFOUND) || (result == HResult.DISP_E_UNKNOWNNAME))
{
// this usually indicates invalid object or property access in JScript
scriptError = new ScriptEngineException(engine.Name, "Invalid object or property access", null, HResult.CLEARSCRIPT_E_SCRIPTITEMEXCEPTION, false, false, null, exception.InnerException);
return true;
}
}
else
{
if ((exception is ArgumentException argumentException) && (argumentException.ParamName == null))
{
// this usually indicates invalid object or property access in VBScript
scriptError = new ScriptEngineException(engine.Name, "Invalid object or property access", null, HResult.CLEARSCRIPT_E_SCRIPTITEMEXCEPTION, false, false, null, exception.InnerException);
return true;
}
}
return false;
}
private void VerifyNotDisposed()
{
if (disposedFlag.IsSet)
{
throw new ObjectDisposedException(ToString());
}
}
private bool TryGetProperty(string name, out object value)
{
VerifyNotDisposed();
object tempResult = null;
var found = engine.ScriptInvoke(() =>
{
try
{
tempResult = target.GetProperty(name, false);
return !(tempResult is Nonexistent);
}
catch (Exception exception)
{
if (!name.IsDispIDName(out _) && (exception.HResult != HResult.DISP_E_UNKNOWNNAME))
{
// Property retrieval failed, but a method with the given name exists;
// create a tear-off method. This currently applies only to VBScript.
tempResult = new ScriptMethod(this, name);
return true;
}
return false;
}
});
if (found)
{
var result = engine.MarshalToHost(tempResult, false);
if ((result is WindowsScriptItem resultScriptItem) && (resultScriptItem.engine == engine))
{
resultScriptItem.holder = this;
}
value = result;
return true;
}
value = null;
return false;
}
#region ScriptItem overrides
protected override bool TryBindAndInvoke(DynamicMetaObjectBinder binder, object[] args, out object result)
{
VerifyNotDisposed();
var succeeded = DynamicHelpers.TryBindAndInvoke(binder, target, args, out result);
if (!succeeded)
{
if ((result is Exception exception) && (engine.CurrentScriptFrame != null))
{
var scriptError = exception as IScriptEngineException ?? GetScriptError(exception);
if (scriptError.ExecutionStarted && (binder.GetType().FullName != "Microsoft.VisualBasic.CompilerServices.VBGetBinder"))
{
throw (Exception)scriptError;
}
engine.CurrentScriptFrame.ScriptError = scriptError;
}
result = null;
return false;
}
return true;
}
protected override object[] AdjustInvokeArgs(object[] args)
{
// WORKAROUND: JScript seems to require at least one argument to invoke a function
return ((engine is IJScriptEngine) && (args.Length < 1)) ? new object[] { Undefined.Value } : args;
}
public override string[] GetPropertyNames()
{
VerifyNotDisposed();
return engine.ScriptInvoke(() => target.GetPropertyNames().ExcludeIndices().ToArray());
}
public override int[] GetPropertyIndices()
{
VerifyNotDisposed();
return engine.ScriptInvoke(() => target.GetPropertyNames().GetIndices().ToArray());
}
#endregion
#region ScriptObject overrides
public override object GetProperty(string name, params object[] args)
{
VerifyNotDisposed();
var result = engine.MarshalToHost(engine.ScriptInvoke(() =>
{
try
{
var value = target.GetProperty(name, false, engine.MarshalToScript(args));
return (value is Nonexistent) ? Undefined.Value : value;
}
catch (Exception exception)
{
if (!name.IsDispIDName(out _) && (exception.HResult != HResult.DISP_E_UNKNOWNNAME))
{
// Property retrieval failed, but a method with the given name exists;
// create a tear-off method. This currently applies only to VBScript.
return new ScriptMethod(this, name);
}
return Undefined.Value;
}
}), false);
if ((result is WindowsScriptItem resultScriptItem) && (resultScriptItem.engine == engine))
{
resultScriptItem.holder = this;
}
return result;
}
public override void SetProperty(string name, params object[] args)
{
VerifyNotDisposed();
engine.ScriptInvoke(() => target.SetProperty(name, false, engine.MarshalToScript(args)));
}
public override bool DeleteProperty(string name)
{
VerifyNotDisposed();
return engine.ScriptInvoke(() => target.DeleteProperty(name, false));
}
public override object GetProperty(int index)
{
VerifyNotDisposed();
return GetProperty(index.ToString(CultureInfo.InvariantCulture));
}
public override void SetProperty(int index, object value)
{
VerifyNotDisposed();
SetProperty(index.ToString(CultureInfo.InvariantCulture), value);
}
public override bool DeleteProperty(int index)
{
VerifyNotDisposed();
return DeleteProperty(index.ToString(CultureInfo.InvariantCulture));
}
public override object Invoke(bool asConstructor, params object[] args)
{
VerifyNotDisposed();
var engineInternal = (ScriptObject)engine.Global.GetProperty("EngineInternal");
if (asConstructor)
{
return engineInternal.InvokeMethod("invokeConstructor", this, args);
}
return engineInternal.InvokeMethod("invokeMethod", holder, this, args);
}
public override object InvokeMethod(string name, params object[] args)
{
VerifyNotDisposed();
try
{
return engine.MarshalToHost(engine.ScriptInvoke(() => target.InvokeMethod(name, false, engine.MarshalToScript(args))), false);
}
catch (Exception exception)
{
if (TryGetScriptError(exception, out var scriptError))
{
throw (Exception)scriptError;
}
throw;
}
}
#endregion
#region Object overrides
public override bool Equals(object obj) => (obj is WindowsScriptItem that) && (engine == that.engine) && target.Equals(that.target);
public override int GetHashCode() => target.GetHashCode();
#endregion
#region IScriptMarshalWrapper implementation
public override ScriptEngine Engine => engine;
public override object Unwrap()
{
return target;
}
#endregion
#region IWindowsScriptObject implementation
object IWindowsScriptObject.GetUnderlyingObject()
{
var pUnkTarget = Marshal.GetIUnknownForObject(target);
var clone = Marshal.GetObjectForIUnknown(pUnkTarget);
Marshal.Release(pUnkTarget);
return clone;
}
#endregion
#region IDictionary<string, object> implementation
private IDictionary<string, object> ThisDictionary => this;
private IEnumerable<string> PropertyKeys => GetPropertyKeys();
private IEnumerable<KeyValuePair<string, object>> KeyValuePairs => PropertyKeys.Select(name => new KeyValuePair<string, object>(name, GetProperty(name)));
private string[] GetPropertyKeys()
{
VerifyNotDisposed();
return engine.ScriptInvoke(() => target.GetPropertyNames().ToArray());
}
IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
{
return KeyValuePairs.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ThisDictionary.GetEnumerator();
}
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item)
{
SetProperty(item.Key, item.Value);
}
void ICollection<KeyValuePair<string, object>>.Clear()
{
PropertyKeys.ForEach(name => DeleteProperty(name));
}
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item)
{
return TryGetProperty(item.Key, out var value) && Equals(value, item.Value);
}
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
{
var source = KeyValuePairs.ToArray();
Array.Copy(source, 0, array, arrayIndex, source.Length);
}
bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object> item)
{
return ThisDictionary.Contains(item) && DeleteProperty(item.Key);
}
int ICollection<KeyValuePair<string, object>>.Count => PropertyKeys.Count();
bool ICollection<KeyValuePair<string, object>>.IsReadOnly => false;
void IDictionary<string, object>.Add(string key, object value)
{
SetProperty(key, value);
}
bool IDictionary<string, object>.ContainsKey(string key)
{
return PropertyKeys.Contains(key);
}
bool IDictionary<string, object>.Remove(string key)
{
return DeleteProperty(key);
}
bool IDictionary<string, object>.TryGetValue(string key, out object value)
{
return TryGetProperty(key, out value);
}
object IDictionary<string, object>.this[string key]
{
get => TryGetProperty(key, out var value) ? value : throw new KeyNotFoundException();
set => SetProperty(key, value);
}
ICollection<string> IDictionary<string, object>.Keys => PropertyKeys.ToList();
ICollection<object> IDictionary<string, object>.Values => PropertyKeys.Select(name => GetProperty(name)).ToList();
#endregion
#region IDisposable implementation
public override void Dispose()
{
if (disposedFlag.Set())
{
Marshal.ReleaseComObject(target);
}
}
#endregion
#region Nested type: WindowsJavaScriptObject
private sealed class WindowsJavaScriptObject : WindowsScriptItem, IJavaScriptObject
{
public WindowsJavaScriptObject(WindowsScriptEngine engine, IDispatchEx target)
: base(engine, target)
{
}
#region IJavaScriptObject implementation
public JavaScriptObjectKind Kind => JavaScriptObjectKind.Unknown;
public JavaScriptObjectFlags Flags => JavaScriptObjectFlags.None;
#endregion
}
#endregion
}
}