Options.cs 16 KB

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