2
0

Options.cs 16 KB

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