2
0

Options.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Dynamic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Reflection;
  7. using Jint.Native;
  8. using Jint.Native.Object;
  9. using Jint.Runtime;
  10. using Jint.Runtime.Interop;
  11. using Jint.Runtime.Debugger;
  12. using Jint.Runtime.Descriptors;
  13. using Jint.Runtime.Interop.Reflection;
  14. using Jint.Runtime.References;
  15. namespace Jint
  16. {
  17. public delegate JsValue MemberAccessorDelegate(Engine engine, object target, string member);
  18. public sealed class Options
  19. {
  20. private readonly List<IConstraint> _constraints = new();
  21. private bool _strict;
  22. private DebuggerStatementHandling _debuggerStatementHandling;
  23. private bool _allowClr;
  24. private bool _allowClrWrite = true;
  25. private bool _allowOperatorOverloading;
  26. private readonly List<IObjectConverter> _objectConverters = new();
  27. private Func<Engine, object, ObjectInstance> _wrapObjectHandler;
  28. private MemberAccessorDelegate _memberAccessor;
  29. private int _maxRecursionDepth = -1;
  30. private TimeSpan _regexTimeoutInterval = TimeSpan.FromSeconds(10);
  31. private CultureInfo _culture = CultureInfo.CurrentCulture;
  32. private TimeZoneInfo _localTimeZone = TimeZoneInfo.Local;
  33. private List<Assembly> _lookupAssemblies = new();
  34. private Predicate<Exception> _clrExceptionsHandler;
  35. private IReferenceResolver _referenceResolver = DefaultReferenceResolver.Instance;
  36. private readonly List<Action<Engine>> _configurations = new();
  37. private readonly List<Type> _extensionMethodClassTypes = new();
  38. internal ExtensionMethodCache _extensionMethods = ExtensionMethodCache.Empty;
  39. internal Func<Engine, Host> _hostFactory = _ => new Host();
  40. /// <summary>
  41. /// Run the script in strict mode.
  42. /// </summary>
  43. public Options Strict(bool strict = true)
  44. {
  45. _strict = strict;
  46. return this;
  47. }
  48. /// <summary>
  49. /// Selects the handling for script <code>debugger</code> statements.
  50. /// </summary>
  51. /// <remarks>
  52. /// The <c>debugger</c> statement can either be ignored (default) trigger debugging at CLR level (e.g. Visual Studio),
  53. /// or trigger a break in Jint's DebugHandler.
  54. /// </remarks>
  55. public Options DebuggerStatementHandling(DebuggerStatementHandling debuggerStatementHandling)
  56. {
  57. _debuggerStatementHandling = debuggerStatementHandling;
  58. return this;
  59. }
  60. /// <summary>
  61. /// Allow to run the script in debug mode.
  62. /// </summary>
  63. public Options DebugMode(bool debugMode = true)
  64. {
  65. IsDebugMode = debugMode;
  66. return this;
  67. }
  68. /// <summary>
  69. /// Adds a <see cref="IObjectConverter"/> instance to convert CLR types to <see cref="JsValue"/>
  70. /// </summary>
  71. public Options AddObjectConverter<T>() where T : IObjectConverter, new()
  72. {
  73. return AddObjectConverter(new T());
  74. }
  75. /// <summary>
  76. /// Adds a <see cref="IObjectConverter"/> instance to convert CLR types to <see cref="JsValue"/>
  77. /// </summary>
  78. public Options AddObjectConverter(IObjectConverter objectConverter)
  79. {
  80. _objectConverters.Add(objectConverter);
  81. return this;
  82. }
  83. public Options AddExtensionMethods(params Type[] types)
  84. {
  85. _extensionMethodClassTypes.AddRange(types);
  86. _extensionMethods = ExtensionMethodCache.Build(_extensionMethodClassTypes);
  87. return this;
  88. }
  89. private void AttachExtensionMethodsToPrototypes(Engine engine)
  90. {
  91. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Array.PrototypeObject, typeof(Array));
  92. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Boolean.PrototypeObject, typeof(bool));
  93. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Date.PrototypeObject, typeof(DateTime));
  94. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Number.PrototypeObject, typeof(double));
  95. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Object.PrototypeObject, typeof(ExpandoObject));
  96. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.RegExp.PrototypeObject, typeof(System.Text.RegularExpressions.Regex));
  97. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.String.PrototypeObject, typeof(string));
  98. }
  99. private void AttachExtensionMethodsToPrototype(Engine engine, ObjectInstance prototype, Type objectType)
  100. {
  101. if (!_extensionMethods.TryGetExtensionMethods(objectType, out var methods))
  102. {
  103. return;
  104. }
  105. foreach (var overloads in methods.GroupBy(x => x.Name))
  106. {
  107. PropertyDescriptor CreateMethodInstancePropertyDescriptor(ClrFunctionInstance clrFunctionInstance)
  108. {
  109. var instance = clrFunctionInstance == null
  110. ? new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList()))
  111. : new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList()), clrFunctionInstance);
  112. return new PropertyDescriptor(instance, PropertyFlag.NonConfigurable);
  113. }
  114. JsValue key = overloads.Key;
  115. PropertyDescriptor descriptorWithFallback = null;
  116. PropertyDescriptor descriptorWithoutFallback = null;
  117. if (prototype.HasOwnProperty(key) && prototype.GetOwnProperty(key).Value is ClrFunctionInstance clrFunctionInstance)
  118. {
  119. descriptorWithFallback = CreateMethodInstancePropertyDescriptor(clrFunctionInstance);
  120. prototype.SetOwnProperty(key, descriptorWithFallback);
  121. }
  122. else
  123. {
  124. descriptorWithoutFallback = CreateMethodInstancePropertyDescriptor(null);
  125. prototype.SetOwnProperty(key, descriptorWithoutFallback);
  126. }
  127. // make sure we register both lower case and upper case
  128. if (char.IsUpper(overloads.Key[0]))
  129. {
  130. key = char.ToLower(overloads.Key[0]) + overloads.Key.Substring(1);
  131. if (prototype.HasOwnProperty(key) && prototype.GetOwnProperty(key).Value is ClrFunctionInstance lowerclrFunctionInstance)
  132. {
  133. descriptorWithFallback = descriptorWithFallback ?? CreateMethodInstancePropertyDescriptor(lowerclrFunctionInstance);
  134. prototype.SetOwnProperty(key, descriptorWithFallback);
  135. }
  136. else
  137. {
  138. descriptorWithoutFallback = descriptorWithoutFallback ?? CreateMethodInstancePropertyDescriptor(null);
  139. prototype.SetOwnProperty(key, descriptorWithoutFallback);
  140. }
  141. }
  142. }
  143. }
  144. /// <summary>
  145. /// If no known type could be guessed, objects are normally wrapped as an
  146. /// ObjectInstance using class ObjectWrapper. This function can be used to
  147. /// register a handler for a customized handling.
  148. /// </summary>
  149. public Options SetWrapObjectHandler(Func<Engine, object, ObjectInstance> wrapObjectHandler)
  150. {
  151. _wrapObjectHandler = wrapObjectHandler;
  152. return this;
  153. }
  154. /// <summary>
  155. /// Sets the type converter to use.
  156. /// </summary>
  157. public Options SetTypeConverter(Func<Engine, ITypeConverter> typeConverterFactory)
  158. {
  159. _configurations.Add(engine => engine.ClrTypeConverter = typeConverterFactory(engine));
  160. return this;
  161. }
  162. /// <summary>
  163. /// Registers a delegate that is called when CLR members are invoked. This allows
  164. /// to change what values are returned for specific CLR objects, or if any value
  165. /// is returned at all.
  166. /// </summary>
  167. /// <param name="accessor">
  168. /// The delegate to invoke for each CLR member. If the delegate
  169. /// returns <c>null</c>, the standard evaluation is performed.
  170. /// </param>
  171. public Options SetMemberAccessor(MemberAccessorDelegate accessor)
  172. {
  173. _memberAccessor = accessor;
  174. return this;
  175. }
  176. /// <summary>
  177. /// Allows scripts to call CLR types directly like <example>System.IO.File</example>
  178. /// </summary>
  179. public Options AllowClr(params Assembly[] assemblies)
  180. {
  181. _allowClr = true;
  182. _lookupAssemblies.AddRange(assemblies);
  183. _lookupAssemblies = _lookupAssemblies.Distinct().ToList();
  184. return this;
  185. }
  186. public Options AllowClrWrite(bool allow = true)
  187. {
  188. _allowClrWrite = allow;
  189. return this;
  190. }
  191. public Options AllowOperatorOverloading(bool allow = true)
  192. {
  193. _allowOperatorOverloading = allow;
  194. return this;
  195. }
  196. /// <summary>
  197. /// Exceptions thrown from CLR code are converted to JavaScript errors and
  198. /// can be used in at try/catch statement. By default these exceptions are bubbled
  199. /// to the CLR host and interrupt the script execution.
  200. /// </summary>
  201. public Options CatchClrExceptions()
  202. {
  203. CatchClrExceptions(_ => true);
  204. return this;
  205. }
  206. /// <summary>
  207. /// Exceptions that thrown from CLR code are converted to JavaScript errors and
  208. /// can be used in at try/catch statement. By default these exceptions are bubbled
  209. /// to the CLR host and interrupt the script execution.
  210. /// </summary>
  211. public Options CatchClrExceptions(Predicate<Exception> handler)
  212. {
  213. _clrExceptionsHandler = handler;
  214. return this;
  215. }
  216. public Options Constraint(IConstraint constraint)
  217. {
  218. if (constraint != null)
  219. {
  220. _constraints.Add(constraint);
  221. }
  222. return this;
  223. }
  224. public Options WithoutConstraint(Predicate<IConstraint> predicate)
  225. {
  226. _constraints.RemoveAll(predicate);
  227. return this;
  228. }
  229. public Options RegexTimeoutInterval(TimeSpan regexTimeoutInterval)
  230. {
  231. _regexTimeoutInterval = regexTimeoutInterval;
  232. return this;
  233. }
  234. /// <summary>
  235. /// Sets maximum allowed depth of recursion.
  236. /// </summary>
  237. /// <param name="maxRecursionDepth">
  238. /// The allowed depth.
  239. /// a) In case max depth is zero no recursion is allowed.
  240. /// b) In case max depth is equal to n it means that in one scope function can be called no more than n times.
  241. /// </param>
  242. /// <returns>Options instance for fluent syntax</returns>
  243. public Options LimitRecursion(int maxRecursionDepth = 0)
  244. {
  245. _maxRecursionDepth = maxRecursionDepth;
  246. return this;
  247. }
  248. public Options Culture(CultureInfo cultureInfo)
  249. {
  250. _culture = cultureInfo;
  251. return this;
  252. }
  253. public Options LocalTimeZone(TimeZoneInfo timeZoneInfo)
  254. {
  255. _localTimeZone = timeZoneInfo;
  256. return this;
  257. }
  258. public Options SetReferencesResolver(IReferenceResolver resolver)
  259. {
  260. _referenceResolver = resolver;
  261. return this;
  262. }
  263. /// <summary>
  264. /// Registers some custom logic to apply on an <see cref="Engine"/> instance when the options
  265. /// are loaded.
  266. /// </summary>
  267. /// <param name="configuration">The action to register.</param>
  268. public Options Configure(Action<Engine> configuration)
  269. {
  270. _configurations.Add(configuration);
  271. return this;
  272. }
  273. /// <summary>
  274. /// Allows to configure how the host is constructed.
  275. /// </summary>
  276. /// <remarks>
  277. /// Passed Engine instance is still in construction and should not be used during call stage.
  278. /// </remarks>
  279. public void UseHostFactory<T>(Func<Engine, T> factory) where T : Host
  280. {
  281. _hostFactory = factory;
  282. }
  283. /// <summary>
  284. /// Called by the <see cref="Engine"/> instance that loads this <see cref="Options" />
  285. /// once it is loaded.
  286. /// </summary>
  287. internal void Apply(Engine engine)
  288. {
  289. foreach (var configuration in _configurations)
  290. {
  291. configuration?.Invoke(engine);
  292. }
  293. // add missing bits if needed
  294. if (_allowClr)
  295. {
  296. engine.Realm.GlobalObject.SetProperty("System", new PropertyDescriptor(new NamespaceReference(engine, "System"), PropertyFlag.AllForbidden));
  297. engine.Realm.GlobalObject.SetProperty("importNamespace", new PropertyDescriptor(new ClrFunctionInstance(
  298. engine,
  299. "importNamespace",
  300. func: (thisObj, arguments) => new NamespaceReference(engine, TypeConverter.ToString(arguments.At(0)))), PropertyFlag.AllForbidden));
  301. }
  302. if (_extensionMethodClassTypes.Count > 0)
  303. {
  304. AttachExtensionMethodsToPrototypes(engine);
  305. }
  306. // ensure defaults
  307. engine.ClrTypeConverter ??= new DefaultTypeConverter(engine);
  308. }
  309. internal bool IsStrict => _strict;
  310. internal DebuggerStatementHandling _DebuggerStatementHandling => _debuggerStatementHandling;
  311. internal bool IsDebugMode { get; private set; }
  312. internal bool _IsClrWriteAllowed => _allowClrWrite;
  313. internal bool _IsOperatorOverloadingAllowed => _allowOperatorOverloading;
  314. internal Predicate<Exception> _ClrExceptionsHandler => _clrExceptionsHandler;
  315. internal List<Assembly> _LookupAssemblies => _lookupAssemblies;
  316. internal List<IObjectConverter> _ObjectConverters => _objectConverters;
  317. internal List<IConstraint> _Constraints => _constraints;
  318. internal Func<Engine, object, ObjectInstance> _WrapObjectHandler => _wrapObjectHandler;
  319. internal MemberAccessorDelegate _MemberAccessor => _memberAccessor;
  320. internal int MaxRecursionDepth => _maxRecursionDepth;
  321. internal TimeSpan _RegexTimeoutInterval => _regexTimeoutInterval;
  322. internal CultureInfo _Culture => _culture;
  323. internal TimeZoneInfo _LocalTimeZone => _localTimeZone;
  324. internal IReferenceResolver ReferenceResolver => _referenceResolver;
  325. private sealed class DefaultReferenceResolver : IReferenceResolver
  326. {
  327. public static readonly DefaultReferenceResolver Instance = new();
  328. private DefaultReferenceResolver()
  329. {
  330. }
  331. public bool TryUnresolvableReference(Engine engine, Reference reference, out JsValue value)
  332. {
  333. value = JsValue.Undefined;
  334. return false;
  335. }
  336. public bool TryPropertyReference(Engine engine, Reference reference, ref JsValue value)
  337. {
  338. return false;
  339. }
  340. public bool TryGetCallable(Engine engine, object callee, out JsValue value)
  341. {
  342. value = JsValue.Undefined;
  343. return false;
  344. }
  345. public bool CheckCoercible(JsValue value)
  346. {
  347. return false;
  348. }
  349. }
  350. }
  351. }