Options.cs 22 KB

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