Options.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. using System.Dynamic;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Reflection;
  5. using Jint.Native;
  6. using Jint.Native.Object;
  7. using Jint.Runtime;
  8. using Jint.Runtime.Interop;
  9. using Jint.Runtime.Debugger;
  10. using Jint.Runtime.Descriptors;
  11. using Jint.Runtime.Modules;
  12. using Jint.Runtime.CallStack;
  13. namespace Jint;
  14. public class Options
  15. {
  16. private static readonly CultureInfo _defaultCulture = CultureInfo.CurrentCulture;
  17. private static readonly TimeZoneInfo _defaultTimeZone = TimeZoneInfo.Local;
  18. private ITimeSystem? _timeSystem;
  19. internal List<Action<Engine>> _configurations { get; } = new();
  20. public delegate JsValue? MemberAccessorDelegate(Engine engine, object target, string member);
  21. public delegate ObjectInstance? WrapObjectDelegate(Engine engine, object target, Type? type);
  22. public delegate bool ExceptionHandlerDelegate(Exception exception);
  23. /// <summary>
  24. /// Execution constraints for the engine.
  25. /// </summary>
  26. public ConstraintOptions Constraints { get; } = new();
  27. /// <summary>
  28. /// CLR interop related options.
  29. /// </summary>
  30. public InteropOptions Interop { get; } = new();
  31. /// <summary>
  32. /// Debugger configuration.
  33. /// </summary>
  34. public DebuggerOptions Debugger { get; } = new();
  35. /// <summary>
  36. /// Host options.
  37. /// </summary>
  38. internal HostOptions Host { get; } = new();
  39. /// <summary>
  40. /// Module options
  41. /// </summary>
  42. public ModuleOptions Modules { get; } = new();
  43. /// <summary>
  44. /// Whether the code should be always considered to be in strict mode. Can improve performance.
  45. /// </summary>
  46. public bool Strict { get; set; }
  47. /// <summary>
  48. /// The culture the engine runs on, defaults to current culture.
  49. /// </summary>
  50. public CultureInfo Culture { get; set; } = _defaultCulture;
  51. /// <summary>
  52. /// Configures a time system to use. Defaults to DefaultTimeSystem using local time.
  53. /// </summary>
  54. public ITimeSystem TimeSystem
  55. {
  56. get => _timeSystem ??= new DefaultTimeSystem(TimeZone, Culture);
  57. set => _timeSystem = value;
  58. }
  59. /// <summary>
  60. /// The time zone the engine runs on, defaults to local. Same as setting DefaultTimeSystem with the time zone.
  61. /// </summary>
  62. public TimeZoneInfo TimeZone { get; set; } = _defaultTimeZone;
  63. /// <summary>
  64. /// Reference resolver allows customizing behavior for reference resolving. This can be useful in cases where
  65. /// you want to ignore long chain of property accesses that might throw if anything is null or undefined.
  66. /// An example of such is <code>var a = obj.field.subField.value</code>. Custom resolver could accept chain to return
  67. /// null/undefined on first occurrence.
  68. /// </summary>
  69. public IReferenceResolver ReferenceResolver { get; set; } = DefaultReferenceResolver.Instance;
  70. /// <summary>
  71. /// Whether calling 'eval' with custom code and function constructors taking function code as string is allowed.
  72. /// Defaults to true.
  73. /// </summary>
  74. /// <remarks>
  75. /// https://tc39.es/ecma262/#sec-hostensurecancompilestrings
  76. /// </remarks>
  77. public bool StringCompilationAllowed { get; set; } = true;
  78. /// <summary>
  79. /// Options for the built-in JSON (de)serializer which
  80. /// gets used using <c>JSON.parse</c> or <c>JSON.stringify</c>
  81. /// </summary>
  82. public JsonOptions Json { get; set; } = new();
  83. /// <summary>
  84. /// What experimental features are allowed, functionality may lacking or even plain wrong. Defaults to having none.
  85. /// </summary>
  86. public ExperimentalFeature ExperimentalFeatures { get; set; }
  87. /// <summary>
  88. /// Called by the <see cref="Engine"/> instance that loads this <see cref="Options" />
  89. /// once it is loaded.
  90. /// </summary>
  91. internal void Apply(Engine engine)
  92. {
  93. foreach (var configuration in _configurations)
  94. {
  95. configuration(engine);
  96. }
  97. // add missing bits if needed
  98. if (Interop.Enabled)
  99. {
  100. #pragma warning disable IL2026
  101. engine.Realm.GlobalObject.SetProperty("System", new PropertyDescriptor(new NamespaceReference(engine, "System"), PropertyFlag.AllForbidden));
  102. engine.Realm.GlobalObject.SetProperty("importNamespace", new PropertyDescriptor(new ClrFunction(
  103. engine,
  104. "importNamespace",
  105. (_, arguments) => new NamespaceReference(engine, arguments.At(0).IsNullOrUndefined() ? null : TypeConverter.ToString(arguments.At(0)))),
  106. PropertyFlag.AllForbidden));
  107. engine.Realm.GlobalObject.SetProperty("clrHelper", new PropertyDescriptor(ObjectWrapper.Create(engine, new ClrHelper(Interop)), PropertyFlag.AllForbidden));
  108. #pragma warning restore IL2026
  109. }
  110. if (Interop.ExtensionMethodTypes.Count > 0)
  111. {
  112. AttachExtensionMethodsToPrototypes(engine);
  113. }
  114. if (Modules.RegisterRequire)
  115. {
  116. // Node js like loading of modules
  117. engine.Realm.GlobalObject.SetProperty("require", new PropertyDescriptor(new ClrFunction(
  118. engine,
  119. "require",
  120. (thisObj, arguments) =>
  121. {
  122. var specifier = TypeConverter.ToString(arguments.At(0));
  123. return engine.Modules.Import(specifier);
  124. }),
  125. PropertyFlag.AllForbidden));
  126. }
  127. engine.Modules = new Engine.ModuleOperations(engine, Modules.ModuleLoader);
  128. }
  129. private static void AttachExtensionMethodsToPrototypes(Engine engine)
  130. {
  131. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Array.PrototypeObject, typeof(Array));
  132. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Boolean.PrototypeObject, typeof(bool));
  133. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Date.PrototypeObject, typeof(DateTime));
  134. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Number.PrototypeObject, typeof(double));
  135. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.Object.PrototypeObject, typeof(ExpandoObject));
  136. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.RegExp.PrototypeObject, typeof(System.Text.RegularExpressions.Regex));
  137. AttachExtensionMethodsToPrototype(engine, engine.Realm.Intrinsics.String.PrototypeObject, typeof(string));
  138. }
  139. private static void AttachExtensionMethodsToPrototype(Engine engine, ObjectInstance prototype, Type objectType)
  140. {
  141. if (!engine._extensionMethods.TryGetExtensionMethods(objectType, out var methods))
  142. {
  143. return;
  144. }
  145. foreach (var overloads in methods.GroupBy(x => x.Name, StringComparer.Ordinal))
  146. {
  147. PropertyDescriptor CreateMethodInstancePropertyDescriptor(ClrFunction? function)
  148. {
  149. var instance = new MethodInfoFunction(
  150. engine,
  151. objectType,
  152. target: null,
  153. overloads.Key,
  154. methods: MethodDescriptor.Build(overloads.ToList()),
  155. function);
  156. return new PropertyDescriptor(instance, PropertyFlag.AllForbidden);
  157. }
  158. JsValue key = overloads.Key;
  159. PropertyDescriptor? descriptorWithFallback = null;
  160. PropertyDescriptor? descriptorWithoutFallback = null;
  161. if (prototype.HasOwnProperty(key) &&
  162. prototype.GetOwnProperty(key).Value is ClrFunction clrFunctionInstance)
  163. {
  164. descriptorWithFallback = CreateMethodInstancePropertyDescriptor(clrFunctionInstance);
  165. prototype.SetOwnProperty(key, descriptorWithFallback);
  166. }
  167. else
  168. {
  169. descriptorWithoutFallback = CreateMethodInstancePropertyDescriptor(null);
  170. prototype.SetOwnProperty(key, descriptorWithoutFallback);
  171. }
  172. // make sure we register both lower case and upper case
  173. if (char.IsUpper(overloads.Key[0]))
  174. {
  175. key = char.ToLower(overloads.Key[0], CultureInfo.InvariantCulture) + overloads.Key.Substring(1);
  176. if (prototype.HasOwnProperty(key) &&
  177. prototype.GetOwnProperty(key).Value is ClrFunction lowerclrFunctionInstance)
  178. {
  179. descriptorWithFallback ??= CreateMethodInstancePropertyDescriptor(lowerclrFunctionInstance);
  180. prototype.SetOwnProperty(key, descriptorWithFallback);
  181. }
  182. else
  183. {
  184. descriptorWithoutFallback ??= CreateMethodInstancePropertyDescriptor(null);
  185. prototype.SetOwnProperty(key, descriptorWithoutFallback);
  186. }
  187. }
  188. }
  189. }
  190. public class DebuggerOptions
  191. {
  192. /// <summary>
  193. /// Whether debugger functionality is enabled, defaults to false.
  194. /// </summary>
  195. public bool Enabled { get; set; }
  196. /// <summary>
  197. /// Configures the statement handling strategy, defaults to Ignore.
  198. /// </summary>
  199. public DebuggerStatementHandling StatementHandling { get; set; } = DebuggerStatementHandling.Ignore;
  200. /// <summary>
  201. /// Configures the step mode used when entering the script.
  202. /// </summary>
  203. public StepMode InitialStepMode { get; set; } = StepMode.None;
  204. }
  205. public class InteropOptions
  206. {
  207. /// <summary>
  208. /// Whether accessing CLR and it's types and methods is allowed from JS code, defaults to false.
  209. /// </summary>
  210. public bool Enabled { get; set; }
  211. /// <summary>
  212. /// Whether to expose <see cref="object.GetType"></see> which can allow bypassing allow lists and open a way to reflection.
  213. /// Defaults to false.
  214. /// </summary>
  215. public bool AllowGetType { get; set; }
  216. /// <summary>
  217. /// Whether Jint should allow wrapping objects from System.Reflection namespace.
  218. /// Defaults to false.
  219. /// </summary>
  220. public bool AllowSystemReflection { get; set; }
  221. /// <summary>
  222. /// Whether writing to CLR objects is allowed (set properties), defaults to true.
  223. /// </summary>
  224. public bool AllowWrite { get; set; } = true;
  225. /// <summary>
  226. /// Whether operator overloading resolution is allowed, defaults to false.
  227. /// </summary>
  228. public bool AllowOperatorOverloading { get; set; }
  229. /// <summary>
  230. /// Types holding extension methods that should be considered when resolving methods.
  231. /// </summary>
  232. public List<Type> ExtensionMethodTypes { get; } = new();
  233. /// <summary>
  234. /// Object converters to try when build-in conversions.
  235. /// </summary>
  236. public List<IObjectConverter> ObjectConverters { get; } = new();
  237. /// <summary>
  238. /// Whether identity map is persisted for object wrappers in order to maintain object identity. This can cause
  239. /// memory usage to grow when targeting large set and freeing of memory can be delayed due to ConditionalWeakTable semantics.
  240. /// Defaults to false.
  241. /// </summary>
  242. public bool TrackObjectWrapperIdentity { get; set; }
  243. /// <summary>
  244. /// If no known type could be guessed, objects are by default wrapped as an
  245. /// ObjectInstance using class ObjectWrapper. This function can be used to
  246. /// change the behavior.
  247. /// </summary>
  248. public WrapObjectDelegate WrapObjectHandler { get; set; } = static (engine, target, type) => ObjectWrapper.Create(engine, target, type);
  249. /// <summary>
  250. ///
  251. /// </summary>
  252. public MemberAccessorDelegate MemberAccessor { get; set; } = static (engine, target, member) => null;
  253. /// <summary>
  254. /// Exceptions that thrown from CLR code are converted to JavaScript errors and
  255. /// can be used in at try/catch statement. By default these exceptions are bubbled
  256. /// to the CLR host and interrupt the script execution. If handler returns true these exceptions are converted
  257. /// to JS errors that can be caught by the script.
  258. /// </summary>
  259. public ExceptionHandlerDelegate ExceptionHandler { get; set; } = _defaultExceptionHandler;
  260. /// <summary>
  261. /// Assemblies to allow scripts to call CLR types directly like <example>System.IO.File</example>.
  262. /// </summary>
  263. public List<Assembly> AllowedAssemblies { get; set; } = new();
  264. /// <summary>
  265. /// Type and member resolving strategy, which allows filtering allowed members and configuring member
  266. /// name matching comparison.
  267. /// </summary>
  268. /// <remarks>
  269. /// As this object holds caching state same instance should be shared between engines, if possible.
  270. /// </remarks>
  271. public TypeResolver TypeResolver { get; set; } = TypeResolver.Default;
  272. /// <summary>
  273. /// When writing values to CLR objects, how should JS values be coerced to CLR types.
  274. /// Defaults to only coercing to string values when writing to string targets.
  275. /// </summary>
  276. public ValueCoercionType ValueCoercion { get; set; } = ValueCoercionType.String;
  277. /// <summary>
  278. /// Strategy to create a CLR object to hold converted <see cref="ObjectInstance"/>.
  279. /// </summary>
  280. public Func<ObjectInstance, IDictionary<string, object?>>? CreateClrObject = _ => new ExpandoObject();
  281. /// <summary>
  282. /// Strategy to create a CLR object from TypeReference.
  283. /// Defaults to retuning null which makes TypeReference attempt to find suitable constructor.
  284. /// </summary>
  285. public Func<Engine, Type, JsValue[], object?> CreateTypeReferenceObject = (_, _, _) => null;
  286. internal static readonly ExceptionHandlerDelegate _defaultExceptionHandler = static exception => false;
  287. /// <summary>
  288. /// When not null, is used to serialize any CLR object in an
  289. /// <see cref="IObjectWrapper"/> passing through 'JSON.stringify'.
  290. /// </summary>
  291. public Func<object, string>? SerializeToJson { get; set; }
  292. /// <summary>
  293. /// What kind of date time should be produced when JavaScript date is converted to DateTime. If Local, uses <see cref="Options.TimeZone"/>.
  294. /// Defaults to <see cref="System.DateTimeKind.Utc"/>.
  295. /// </summary>
  296. public DateTimeKind DateTimeKind { get; set; } = DateTimeKind.Utc;
  297. /// <summary>
  298. /// Should the Array prototype be attached instead of Object prototype to the wrapped interop objects when type looks suitable. Defaults to true.
  299. /// </summary>
  300. public bool AttachArrayPrototype { get; set; } = true;
  301. /// <summary>
  302. /// Whether the engine should throw an error when a member is not found on a CLR object. Defaults to false.
  303. /// </summary>
  304. public bool ThrowOnUnresolvedMember { get; set; }
  305. /// <summary>
  306. /// Types of CLR members reported by <see cref="ObjectWrapper"/> when enumerating properties/serializing <see cref="ObjectWrapper.ToObject"/>.
  307. /// Supported values are: <see cref="MemberTypes.Field"/>, <see cref="MemberTypes.Property"/>, <see cref="MemberTypes.Method"/>.
  308. /// All other values are ignored.
  309. /// </summary>
  310. public MemberTypes ObjectWrapperReportedMemberTypes { get; set; } = MemberTypes.Field | MemberTypes.Property | MemberTypes.Method;
  311. }
  312. public class ConstraintOptions
  313. {
  314. /// <summary>
  315. /// Registered constraints.
  316. /// </summary>
  317. public List<Constraint> Constraints { get; } = new();
  318. /// <summary>
  319. /// Maximum recursion depth allowed, defaults to -1 (no checks).
  320. /// </summary>
  321. public int MaxRecursionDepth { get; set; } = -1;
  322. /// <summary>
  323. /// Maximum recursion stack count, defaults to -1 (as-is dotnet stacktrace).
  324. /// </summary>
  325. /// <remarks>
  326. /// Chrome and V8 based engines (ClearScript) that can handle 13955.
  327. /// When set to a different value except -1, it can reduce slight performance/stack trace readability drawback. (after hitting the engine's own limit),
  328. /// When max stack size to be exceeded, Engine throws an exception <see cref="JavaScriptException" />.
  329. /// </remarks>
  330. public int MaxExecutionStackCount { get; set; } = StackGuard.Disabled;
  331. /// <summary>
  332. /// Maximum time a Regex is allowed to run, defaults to 10 seconds.
  333. /// </summary>
  334. public TimeSpan RegexTimeout { get; set; } = TimeSpan.FromSeconds(10);
  335. /// <summary>
  336. /// The maximum size for JavaScript array, defaults to <see cref="uint.MaxValue"/>.
  337. /// </summary>
  338. public uint MaxArraySize { get; set; } = uint.MaxValue;
  339. }
  340. /// <summary>
  341. /// Host related customization, still work in progress.
  342. /// </summary>
  343. public class HostOptions
  344. {
  345. internal Func<Engine, Host> Factory { get; set; } = _ => new Host();
  346. }
  347. /// <summary>
  348. /// Module related customization
  349. /// </summary>
  350. public class ModuleOptions
  351. {
  352. /// <summary>
  353. /// Whether to register require function to engine which will delegate to module loader, defaults to false.
  354. /// </summary>
  355. public bool RegisterRequire { get; set; }
  356. /// <summary>
  357. /// Module loader implementation, by default exception will be thrown if module loading is not enabled.
  358. /// </summary>
  359. public IModuleLoader ModuleLoader { get; set; } = FailFastModuleLoader.Instance;
  360. }
  361. /// <summary>
  362. /// JSON.parse / JSON.stringify related customization
  363. /// </summary>
  364. public class JsonOptions
  365. {
  366. /// <summary>
  367. /// The maximum depth allowed when parsing JSON files using "JSON.parse",
  368. /// defaults to 64.
  369. /// </summary>
  370. public int MaxParseDepth { get; set; } = 64;
  371. }
  372. }
  373. /// <summary>
  374. /// Rules for writing values to CLR fields.
  375. /// </summary>
  376. [Flags]
  377. public enum ValueCoercionType
  378. {
  379. /// <summary>
  380. /// No coercion will be done. If there's no type converter, and error will be thrown.
  381. /// </summary>
  382. None = 0,
  383. /// <summary>
  384. /// JS coercion using boolean rules "dog" == true, "" == false, 1 == true, 3 == true, 0 == false, { "prop": 1 } == true etc.
  385. /// </summary>
  386. Boolean = 1,
  387. /// <summary>
  388. /// JS coercion to numbers, false == 0, true == 1. valueOf functions will be used when available for object instances.
  389. /// Valid against targets of type: Decimal, Double, Int32, Int64.
  390. /// </summary>
  391. Number = 2,
  392. /// <summary>
  393. /// JS coercion to strings, toString function will be used when available for objects.
  394. /// </summary>
  395. String = 4,
  396. /// <summary>
  397. /// All coercion rules enabled.
  398. /// </summary>
  399. All = Boolean | Number | String
  400. }
  401. /// <summary>
  402. /// Features that only work partially, if all.
  403. /// </summary>
  404. [Flags]
  405. public enum ExperimentalFeature
  406. {
  407. /// <summary>
  408. /// No experimental features enabled.
  409. /// </summary>
  410. None = 0,
  411. /// <summary>
  412. /// Generator support
  413. /// </summary>
  414. Generators = 1,
  415. /// <summary>
  416. /// Wrapping tasks to promises
  417. /// </summary>
  418. TaskInterop = 2,
  419. /// <summary>
  420. /// All coercion rules enabled.
  421. /// </summary>
  422. All = Generators | TaskInterop
  423. }