ObjectWrapper.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. using System.Collections;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Globalization;
  4. using System.Reflection;
  5. using Jint.Native;
  6. using Jint.Native.Iterator;
  7. using Jint.Native.Object;
  8. using Jint.Native.Symbol;
  9. using Jint.Runtime.Descriptors;
  10. using Jint.Runtime.Interop.Reflection;
  11. #pragma warning disable IL2067
  12. #pragma warning disable IL2072
  13. #pragma warning disable IL2075
  14. namespace Jint.Runtime.Interop;
  15. /// <summary>
  16. /// Wraps a CLR instance
  17. /// </summary>
  18. public class ObjectWrapper : ObjectInstance, IObjectWrapper, IEquatable<ObjectWrapper>
  19. {
  20. internal readonly TypeDescriptor _typeDescriptor;
  21. internal ObjectWrapper(
  22. Engine engine,
  23. object obj,
  24. Type? type = null)
  25. : base(engine)
  26. {
  27. Target = obj;
  28. ClrType = GetClrType(obj, type);
  29. _typeDescriptor = TypeDescriptor.Get(ClrType);
  30. if (_typeDescriptor.LengthProperty is not null)
  31. {
  32. // create a forwarder to produce length from Count or Length if one of them is present
  33. var functionInstance = new ClrFunction(engine, "length", GetLength);
  34. var descriptor = new GetSetPropertyDescriptor(functionInstance, Undefined, PropertyFlag.Configurable);
  35. SetProperty(KnownKeys.Length, descriptor);
  36. if (_typeDescriptor.IsArrayLike && engine.Options.Interop.AttachArrayPrototype)
  37. {
  38. // if we have array-like object, we can attach array prototype
  39. _prototype = engine.Intrinsics.Array.PrototypeObject;
  40. }
  41. }
  42. }
  43. /// <summary>
  44. /// Creates a new object wrapper for given object instance and exposed type.
  45. /// </summary>
  46. public static ObjectInstance Create(Engine engine, object target, Type? type = null)
  47. {
  48. if (target == null)
  49. {
  50. ExceptionHelper.ThrowArgumentNullException(nameof(target));
  51. }
  52. // STJ integration
  53. if (string.Equals(type?.FullName, "System.Text.Json.Nodes.JsonNode", StringComparison.Ordinal))
  54. {
  55. // we need to always expose the actual type instead of the type nodes provide
  56. type = target.GetType();
  57. }
  58. type ??= target.GetType();
  59. if (TryBuildArrayLikeWrapper(engine, target, type, out var wrapper))
  60. {
  61. return wrapper;
  62. }
  63. return new ObjectWrapper(engine, target, type);
  64. }
  65. private static bool TryBuildArrayLikeWrapper(
  66. Engine engine,
  67. object target,
  68. [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] Type type,
  69. [NotNullWhen(true)] out ArrayLikeWrapper? result)
  70. {
  71. #pragma warning disable IL2055
  72. #pragma warning disable IL3050
  73. result = null;
  74. // check for generic interfaces
  75. foreach (var i in type.GetInterfaces())
  76. {
  77. if (!i.IsGenericType)
  78. {
  79. continue;
  80. }
  81. var arrayItemType = i.GenericTypeArguments[0];
  82. if (i.GetGenericTypeDefinition() == typeof(IList<>))
  83. {
  84. var arrayWrapperType = typeof(GenericListWrapper<>).MakeGenericType(arrayItemType);
  85. result = (ArrayLikeWrapper) Activator.CreateInstance(arrayWrapperType, engine, target, type)!;
  86. break;
  87. }
  88. if (i.GetGenericTypeDefinition() == typeof(IReadOnlyList<>))
  89. {
  90. var arrayWrapperType = typeof(ReadOnlyListWrapper<>).MakeGenericType(arrayItemType);
  91. result = (ArrayLikeWrapper) Activator.CreateInstance(arrayWrapperType, engine, target, type)!;
  92. break;
  93. }
  94. }
  95. #pragma warning restore IL3050
  96. #pragma warning restore IL2055
  97. // least specific
  98. if (result is null && target is IList list)
  99. {
  100. result = new ListWrapper(engine, list, type);
  101. }
  102. return result is not null;
  103. }
  104. public object Target { get; }
  105. public Type ClrType { get; }
  106. internal override bool IsArrayLike => _typeDescriptor.IsArrayLike;
  107. internal override bool HasOriginalIterator => IsArrayLike;
  108. internal override bool IsIntegerIndexedArray => _typeDescriptor.IsIntegerIndexed;
  109. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  110. {
  111. // check if we can take shortcuts for empty object, no need to generate properties
  112. if (property is JsString stringKey)
  113. {
  114. var member = stringKey.ToString();
  115. if (_properties is null || !_properties.ContainsKey(member))
  116. {
  117. // can try utilize fast path
  118. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, ClrType, member, mustBeReadable: false, mustBeWritable: true);
  119. if (ReferenceEquals(accessor, ConstantValueAccessor.NullAccessor))
  120. {
  121. // there's no such property, but we can allow extending by calling base
  122. // which will add properties, this allows for example JS class to extend a CLR type
  123. return base.Set(property, value, receiver);
  124. }
  125. // CanPut logic
  126. if (!accessor.Writable || !_engine.Options.Interop.AllowWrite)
  127. {
  128. return false;
  129. }
  130. accessor.SetValue(_engine, Target, member, value);
  131. return true;
  132. }
  133. }
  134. else if (property is JsSymbol jsSymbol)
  135. {
  136. // symbol addition will never hit any known CLR object properties, so if write is allowed, allow writing symbols too
  137. if (_engine.Options.Interop.AllowWrite)
  138. {
  139. return base.Set(jsSymbol, value, receiver);
  140. }
  141. return false;
  142. }
  143. return SetSlow(property, value);
  144. }
  145. private bool SetSlow(JsValue property, JsValue value)
  146. {
  147. if (!CanPut(property))
  148. {
  149. return false;
  150. }
  151. var ownDesc = GetOwnProperty(property);
  152. ownDesc.Value = value;
  153. return true;
  154. }
  155. public override object ToObject() => Target;
  156. public override void RemoveOwnProperty(JsValue property)
  157. {
  158. if (_engine.Options.Interop.AllowWrite && property is JsString jsString && _typeDescriptor.RemoveMethod is not null)
  159. {
  160. _typeDescriptor.RemoveMethod.Invoke(Target, [jsString.ToString()]);
  161. }
  162. }
  163. public override JsValue Get(JsValue property, JsValue receiver)
  164. {
  165. if (!_typeDescriptor.IsDictionary
  166. && Target is ICollection c
  167. && CommonProperties.Length.Equals(property))
  168. {
  169. return JsNumber.Create(c.Count);
  170. }
  171. var desc = GetOwnProperty(property, mustBeReadable: true, mustBeWritable: false);
  172. if (desc != PropertyDescriptor.Undefined)
  173. {
  174. return UnwrapJsValue(desc, receiver);
  175. }
  176. return Prototype?.Get(property, receiver) ?? Undefined;
  177. }
  178. public override List<JsValue> GetOwnPropertyKeys(Types types = Types.Empty | Types.String | Types.Symbol)
  179. {
  180. return new List<JsValue>(EnumerateOwnPropertyKeys(types));
  181. }
  182. public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
  183. {
  184. foreach (var key in EnumerateOwnPropertyKeys(Types.String | Types.Symbol))
  185. {
  186. yield return new KeyValuePair<JsValue, PropertyDescriptor>(key, GetOwnProperty(key));
  187. }
  188. }
  189. private IEnumerable<JsValue> EnumerateOwnPropertyKeys(Types types)
  190. {
  191. // prefer object order, add possible other properties after
  192. var includeStrings = (types & Types.String) != Types.Empty;
  193. if (includeStrings && _typeDescriptor.IsStringKeyedGenericDictionary) // expando object for instance
  194. {
  195. var keys = (ICollection<string>) _typeDescriptor.KeysAccessor!.GetValue(Target)!;
  196. foreach (var key in keys)
  197. {
  198. yield return JsString.Create(key);
  199. }
  200. }
  201. else if (includeStrings && Target is IDictionary dictionary)
  202. {
  203. // we take values exposed as dictionary keys only
  204. foreach (var key in dictionary.Keys)
  205. {
  206. object? stringKey = key as string;
  207. if (stringKey is not null
  208. || _engine.TypeConverter.TryConvert(key, typeof(string), CultureInfo.InvariantCulture, out stringKey))
  209. {
  210. yield return JsString.Create((string) stringKey!);
  211. }
  212. }
  213. }
  214. else if (includeStrings)
  215. {
  216. // we take public properties, fields and methods
  217. const BindingFlags BindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public;
  218. if ((_engine.Options.Interop.ObjectWrapperReportedMemberTypes & MemberTypes.Property) == MemberTypes.Property)
  219. {
  220. foreach (var p in ClrType.GetProperties(BindingFlags))
  221. {
  222. var indexParameters = p.GetIndexParameters();
  223. if (indexParameters.Length == 0)
  224. {
  225. yield return JsString.Create(p.Name);
  226. }
  227. }
  228. }
  229. if ((_engine.Options.Interop.ObjectWrapperReportedMemberTypes & MemberTypes.Field) == MemberTypes.Field)
  230. {
  231. foreach (var f in ClrType.GetFields(BindingFlags | BindingFlags.DeclaredOnly))
  232. {
  233. yield return JsString.Create(f.Name);
  234. }
  235. }
  236. if ((_engine.Options.Interop.ObjectWrapperReportedMemberTypes & MemberTypes.Method) == MemberTypes.Method)
  237. {
  238. foreach (var m in ClrType.GetMethods(BindingFlags | BindingFlags.DeclaredOnly))
  239. {
  240. if (m.IsSpecialName)
  241. {
  242. continue;
  243. }
  244. yield return JsString.Create(m.Name);
  245. }
  246. }
  247. }
  248. }
  249. public override PropertyDescriptor GetOwnProperty(JsValue property)
  250. {
  251. // we do not know if we need to read or write
  252. return GetOwnProperty(property, mustBeReadable: false, mustBeWritable: false);
  253. }
  254. private PropertyDescriptor GetOwnProperty(JsValue property, bool mustBeReadable, bool mustBeWritable)
  255. {
  256. if (TryGetProperty(property, out var x))
  257. {
  258. return x;
  259. }
  260. // if we have array-like or dictionary or expando, we can provide iterator
  261. if (property.IsSymbol())
  262. {
  263. if (property == GlobalSymbolRegistry.Iterator && _typeDescriptor.Iterable)
  264. {
  265. var iteratorFunction = new ClrFunction(
  266. Engine,
  267. "iterator",
  268. Iterator,
  269. 1,
  270. PropertyFlag.Configurable);
  271. var iteratorProperty = new PropertyDescriptor(iteratorFunction, PropertyFlag.Configurable | PropertyFlag.Writable);
  272. SetProperty(GlobalSymbolRegistry.Iterator, iteratorProperty);
  273. return iteratorProperty;
  274. }
  275. // not that safe
  276. return PropertyDescriptor.Undefined;
  277. }
  278. var member = property.ToString();
  279. // if type is dictionary, we cannot enumerate anything other than keys
  280. // and we cannot store accessors as dictionary can change dynamically
  281. var isDictionary = _typeDescriptor.IsStringKeyedGenericDictionary;
  282. if (isDictionary)
  283. {
  284. if (_typeDescriptor.TryGetValue(Target, member, out var value))
  285. {
  286. var flags = PropertyFlag.Enumerable;
  287. if (_engine.Options.Interop.AllowWrite)
  288. {
  289. flags |= PropertyFlag.Configurable;
  290. }
  291. return new PropertyDescriptor(FromObject(_engine, value), flags);
  292. }
  293. }
  294. var result = Engine.Options.Interop.MemberAccessor(Engine, Target, member);
  295. if (result is not null)
  296. {
  297. return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable);
  298. }
  299. var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, ClrType, member, mustBeReadable, mustBeWritable);
  300. var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, member, enumerable: !isDictionary);
  301. if (!isDictionary
  302. && !ReferenceEquals(descriptor, PropertyDescriptor.Undefined)
  303. && (!mustBeReadable || accessor.Readable)
  304. && (!mustBeWritable || accessor.Writable))
  305. {
  306. // cache the accessor for faster subsequent accesses
  307. SetProperty(member, descriptor);
  308. }
  309. return descriptor;
  310. }
  311. // need to be public for advanced cases like RavenDB yielding properties from CLR objects
  312. public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object target, MemberInfo member)
  313. {
  314. // fast path which uses slow search if not found for some reason
  315. ReflectionAccessor? Factory()
  316. {
  317. return member switch
  318. {
  319. PropertyInfo pi => new PropertyAccessor(pi),
  320. MethodBase mb => new MethodAccessor(target.GetType(), MethodDescriptor.Build(new[] { mb })),
  321. FieldInfo fi => new FieldAccessor(fi),
  322. _ => null
  323. };
  324. }
  325. var accessor = engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, mustBeReadable: false, mustBeWritable: false, Factory);
  326. return accessor.CreatePropertyDescriptor(engine, target, member.Name);
  327. }
  328. internal static Type GetClrType(object obj, Type? type)
  329. {
  330. if (type is null || type == typeof(object))
  331. {
  332. return obj.GetType();
  333. }
  334. var underlyingType = Nullable.GetUnderlyingType(type);
  335. if (underlyingType is not null)
  336. {
  337. return underlyingType;
  338. }
  339. return type;
  340. }
  341. private static JsValue Iterator(JsValue thisObject, JsValue[] arguments)
  342. {
  343. var wrapper = (ObjectWrapper) thisObject;
  344. return wrapper._typeDescriptor.IsDictionary
  345. ? new DictionaryIterator(wrapper._engine, wrapper)
  346. : new EnumerableIterator(wrapper._engine, (IEnumerable) wrapper.Target);
  347. }
  348. private static JsNumber GetLength(JsValue thisObject, JsValue[] arguments)
  349. {
  350. var wrapper = (ObjectWrapper) thisObject;
  351. return JsNumber.Create((int) (wrapper._typeDescriptor.LengthProperty?.GetValue(wrapper.Target) ?? 0));
  352. }
  353. internal override ulong GetSmallestIndex(ulong length)
  354. {
  355. return Target is ICollection ? 0 : base.GetSmallestIndex(length);
  356. }
  357. public override bool Equals(object? obj) => Equals(obj as ObjectWrapper);
  358. public override bool Equals(JsValue? other) => Equals(other as ObjectWrapper);
  359. public bool Equals(ObjectWrapper? other)
  360. {
  361. if (ReferenceEquals(null, other))
  362. {
  363. return false;
  364. }
  365. if (ReferenceEquals(this, other))
  366. {
  367. return true;
  368. }
  369. return Equals(Target, other.Target);
  370. }
  371. public override int GetHashCode() => Target.GetHashCode();
  372. private sealed class DictionaryIterator : IteratorInstance
  373. {
  374. private readonly ObjectWrapper _target;
  375. private readonly IEnumerator<JsValue> _enumerator;
  376. public DictionaryIterator(Engine engine, ObjectWrapper target) : base(engine)
  377. {
  378. _target = target;
  379. _enumerator = target.EnumerateOwnPropertyKeys(Types.String).GetEnumerator();
  380. }
  381. public override bool TryIteratorStep(out ObjectInstance nextItem)
  382. {
  383. if (_enumerator.MoveNext())
  384. {
  385. var key = _enumerator.Current;
  386. var value = _target.Get(key);
  387. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine, key, value);
  388. return true;
  389. }
  390. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  391. return false;
  392. }
  393. }
  394. private sealed class EnumerableIterator : IteratorInstance
  395. {
  396. private readonly IEnumerator _enumerator;
  397. public EnumerableIterator(Engine engine, IEnumerable target) : base(engine)
  398. {
  399. _enumerator = target.GetEnumerator();
  400. }
  401. public override void Close(CompletionType completion)
  402. {
  403. (_enumerator as IDisposable)?.Dispose();
  404. base.Close(completion);
  405. }
  406. public override bool TryIteratorStep(out ObjectInstance nextItem)
  407. {
  408. if (_enumerator.MoveNext())
  409. {
  410. var value = _enumerator.Current;
  411. nextItem = IteratorResult.CreateValueIteratorPosition(_engine, FromObject(_engine, value));
  412. return true;
  413. }
  414. nextItem = IteratorResult.CreateKeyValueIteratorPosition(_engine);
  415. return false;
  416. }
  417. }
  418. }