2
0

Options.cs 19 KB

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