Quantcast
Channel: ClearScript
Viewing all 2297 articles
Browse latest View live

Closed Unassigned: Access Violation Exception in v8-x64.dll [115]

$
0
0
Hi!
We launched a new site last week that uses ClearScript to server render a React application. After launch, we get around 2-3 crashes on Access Violation Exception in w3wp.exe a day per web server. The site has around 200 concurrent users on average, with peaks up over a thousand. We use the latest version of ClearScript (5.4.7).

We see that the crash is an Access Violation Exception in v8-x64.dll and we have a few dump files from such crashes, but since we don't have any debugging symbols the stack traces doesn't give us much.

Would you be interested in looking at the crash dumps to help us figure this out? Or if you can help us with debug symbols so we can get more information out of the dumps.

Some information about how we use ClearScript:
1. We create multiple V8Runtime and V8ScriptEngine and keep them in a queue. When a request comes in, we dequeue an engine, run JS and return it back to the queue.
2. Since we don't store any JS globals we reuse the same V8 context for different visitors. But we run CollectGarbage(true) for every 30 execution. We have deployed a change this morning where we call CollectGarbage(false) instead but twice as often. Not because we think it will solve it, but see if the behavior changes.
3. We don't pass any CLR references to V8. The only thing we do is call Engine.Execute with strings of JS code. When we pass data to V8 we do that by either calling Engine.Execute or Engine.Evaluate with strings of JSON.

Any help or pointers are appreciated! We'd be happy to share code with you if you need it.

Edited Unassigned: Access Violation Exception in v8-x64.dll [115]

$
0
0
Hi!
We launched a new site last week that uses ClearScript to server render a React application. After launch, we get around 2-3 crashes on Access Violation Exception in w3wp.exe a day per web server. The site has around 200 concurrent users on average, with peaks up over a thousand. We use the latest version of ClearScript (5.4.7).

We see that the crash is an Access Violation Exception in v8-x64.dll and we have a few dump files from such crashes, but since we don't have any debugging symbols the stack traces doesn't give us much.

Would you be interested in looking at the crash dumps to help us figure this out? Or if you can help us with debug symbols so we can get more information out of the dumps.

Some information about how we use ClearScript:
1. We create multiple V8Runtime and V8ScriptEngine and keep them in a queue. When a request comes in, we dequeue an engine, run JS and return it back to the queue.
2. Since we don't store any JS globals we reuse the same V8 context for different visitors. But we run CollectGarbage(true) for every 30 execution. We have deployed a change this morning where we call CollectGarbage(false) instead but twice as often. Not because we think it will solve it, but see if the behavior changes.
3. We don't pass any CLR references to V8. The only thing we do is call Engine.Execute with strings of JS code. When we pass data to V8 we do that by either calling Engine.Execute or Engine.Evaluate with strings of JSON.

Any help or pointers are appreciated! We'd be happy to share code with you if you need it.

Closed Issue: [BUG] Crash when calling Interrupt() at bad time [112]

$
0
0
Hello,

we are having issues with a portion of code that basically provokes an exception in user code called by clearscript, and then calls Interrupt on the V8 engine.

It always crashes. Isn't this scenario supposed to function properly ? (I mean, Interrupt should not crash... ?)

Should I explicitely wait before Interrupting in this case ? (but this would be some sort of workaround?)

Cdlt,
Julien.

btw: reproduced on ClearScript 5.4.6 (Nuget version)

```
[Test]
public virtual void TestScriptTerminateCrash()
{
var ctx = new PropertyBag();
using (var engine = new V8ScriptEngine("CrashScript"))
{
engine.AddHostObject("context", ctx);

var eventW = new ManualResetEventSlim(initialState: false);
var tokenSource = new CancellationTokenSource();

// start notification only
var startEvent = new ManualResetEventSlim(false);

ThreadStart main = () =>
{
try
{

ctx["waitCode"] = new Action(() =>
{
// Waiting in the C# code : a cancel exception is generated here
eventW.Wait(tokenSource.Token);

});
ctx["startEvent"] = startEvent;
ctx["counter"] = 0;
try
{
System.DateTime dtRun = System.DateTime.UtcNow;
engine.Execute("dummyDocument.js", @"
// Start
context.counter = 1;

context.startEvent.Set();

context.counter = 2;

context.waitCode();

context.counter = 3;


");
Assert.Inconclusive();
}
catch (Microsoft.ClearScript.ScriptInterruptedException si)
{
Assert.That(si.Message.Contains("interrupted"));
}
catch (Microsoft.ClearScript.ScriptEngineException segx)
{
if (segx.InnerException is System.Reflection.TargetInvocationException &&
segx.InnerException.InnerException != null)
throw segx.InnerException.InnerException;
Assert.Fail();
}
}
catch (OperationCanceledException)
{
}
catch (Exception)
{
Assert.Fail();
}

};

var t = new Thread(main);
t.Start();
Assert.That(startEvent.Wait(5000));

// Cancel + interrupt
tokenSource.Cancel();
//Thread.Sleep(1000); // won't fail if we interrupt later
engine.Interrupt();

t.Join();

Assert.AreEqual(2, (Int32)ctx["counter"]);
}
}

```

Edited Issue: [BUG] Crash when calling Interrupt() at bad time [112]

$
0
0
Hello,

we are having issues with a portion of code that basically provokes an exception in user code called by clearscript, and then calls Interrupt on the V8 engine.

It always crashes. Isn't this scenario supposed to function properly ? (I mean, Interrupt should not crash... ?)

Should I explicitely wait before Interrupting in this case ? (but this would be some sort of workaround?)

Cdlt,
Julien.

btw: reproduced on ClearScript 5.4.6 (Nuget version)

```
[Test]
public virtual void TestScriptTerminateCrash()
{
var ctx = new PropertyBag();
using (var engine = new V8ScriptEngine("CrashScript"))
{
engine.AddHostObject("context", ctx);

var eventW = new ManualResetEventSlim(initialState: false);
var tokenSource = new CancellationTokenSource();

// start notification only
var startEvent = new ManualResetEventSlim(false);

ThreadStart main = () =>
{
try
{

ctx["waitCode"] = new Action(() =>
{
// Waiting in the C# code : a cancel exception is generated here
eventW.Wait(tokenSource.Token);

});
ctx["startEvent"] = startEvent;
ctx["counter"] = 0;
try
{
System.DateTime dtRun = System.DateTime.UtcNow;
engine.Execute("dummyDocument.js", @"
// Start
context.counter = 1;

context.startEvent.Set();

context.counter = 2;

context.waitCode();

context.counter = 3;


");
Assert.Inconclusive();
}
catch (Microsoft.ClearScript.ScriptInterruptedException si)
{
Assert.That(si.Message.Contains("interrupted"));
}
catch (Microsoft.ClearScript.ScriptEngineException segx)
{
if (segx.InnerException is System.Reflection.TargetInvocationException &&
segx.InnerException.InnerException != null)
throw segx.InnerException.InnerException;
Assert.Fail();
}
}
catch (OperationCanceledException)
{
}
catch (Exception)
{
Assert.Fail();
}

};

var t = new Thread(main);
t.Start();
Assert.That(startEvent.Wait(5000));

// Cancel + interrupt
tokenSource.Cancel();
//Thread.Sleep(1000); // won't fail if we interrupt later
engine.Interrupt();

t.Join();

Assert.AreEqual(2, (Int32)ctx["counter"]);
}
}

```

Updated Wiki: Home

$
0
0

Description

ClearScript is a library that makes it easy to add scripting to your .NET applications. It currently supports JavaScript (via V8 and JScript) and VBScript.

Features

  • Simple usage; create a script engine, add your objects and/or types, run scripts
  • Support for several script engines: Google's V8, Microsoft's JScript and VBScript
  • Exposed resources require no modification, decoration, or special coding of any kind
  • Scripts get simple access to most of the features of exposed objects and types:
    • Methods, properties, fields, events
    • (Objects) Indexers, extension methods, conversion operators, explicitly implemented interfaces
    • (Types) Constructors, nested types
  • Full support for generic types and methods, including C#-like type inference and explicit type arguments
  • Scripts can invoke methods with output parameters, optional parameters, and parameter arrays
  • Script delegates enable callbacks into script code
  • Support for exposing all the types defined in one or more assemblies in one step
  • Optional support for importing types and assemblies from script code
  • The host can invoke script functions and access script objects directly
  • Full support for script debugging

Examples

using System;
using Microsoft.ClearScript;
using Microsoft.ClearScript.JavaScript;
using Microsoft.ClearScript.V8;

// create a script engineusing (var engine = new V8ScriptEngine())
{
    // expose a host type
    engine.AddHostType("Console", typeof(Console));
    engine.Execute("Console.WriteLine('{0} is an interesting number.', Math.PI)");

    // expose a host object
    engine.AddHostObject("random", new Random());
    engine.Execute("Console.WriteLine(random.NextDouble())");

    // expose entire assemblies
    engine.AddHostObject("lib", new HostTypeCollection("mscorlib", "System.Core"));
    engine.Execute("Console.WriteLine(lib.System.DateTime.Now)");

    // create a host object from script
    engine.Execute(@"
        birthday = new lib.System.DateTime(2007, 5, 22);
        Console.WriteLine(birthday.ToLongDateString());
    ");

    // use a generic class from script
    engine.Execute(@"
        Dictionary = lib.System.Collections.Generic.Dictionary;
        dict = new Dictionary(lib.System.String, lib.System.Int32);
        dict.Add('foo', 123);
    ");

    // call a host method with an output parameter
    engine.AddHostObject("host", new HostFunctions());
    engine.Execute(@"
        intVar = host.newVar(lib.System.Int32);
        found = dict.TryGetValue('foo', intVar.out);
        Console.WriteLine('{0} {1}', found, intVar);
    ");

    // create and populate a host array
    engine.Execute(@"
        numbers = host.newArr(lib.System.Int32, 20);
        for (var i = 0; i < numbers.Length; i++) { numbers[i] = i; }
        Console.WriteLine(lib.System.String.Join(', ', numbers));
    ");

    // create a script delegate
    engine.Execute(@"
        Filter = lib.System.Func(lib.System.Int32, lib.System.Boolean);
        oddFilter = new Filter(function(value) {
            return (value & 1) ? true : false;
        });
    ");

    // use LINQ from script
    engine.Execute(@"
        oddNumbers = numbers.Where(oddFilter);
        Console.WriteLine(lib.System.String.Join(', ', oddNumbers));
    ");

    // use a dynamic host object
    engine.Execute(@"
        expando = new lib.System.Dynamic.ExpandoObject();
        expando.foo = 123;
        expando.bar = 'qux';
        delete expando.foo;
    ");

    // call a script function
    engine.Execute("function print(x) { Console.WriteLine(x); }");
    engine.Script.print(DateTime.Now.DayOfWeek);

    // examine a script object
    engine.Execute("person = { name: 'Fred', age: 5 }");
    Console.WriteLine(engine.Script.person.name);

    // read a JavaScript typed array
    engine.Execute("values = new Int32Array([1, 2, 3, 4, 5])");
    var values = (ITypedArray<int>)engine.Script.values;
    Console.WriteLine(string.Join(", ", values.ToArray()));
}

New Post: datarow problem

$
0
0
Hi I must be missing something.
What is wrong with my code

vb.net
Dim engine As New V8ScriptEngine(V8ScriptEngineFlags.EnableDebugging)
engine.AddHostType("Console", GetType(Console))
engine.AddHostType("MessageBox", GetType(MessageBox))
engine.AddHostObject("myRow", ExcelFileDataSet.Tables(0).Rows(0))
Dim jsScript As String = txttest.Text
Try
            engine.Execute(jsScript)
            engine.Script.test
Catch ex As Exception
            MessageBox.Show(ex.Message)
End Try
javascript
function test() {
  MessageBox.Show('a');
  MessageBox.Show(myRow[0].ToString);
}
It first shows me the messagebox with 'a' and afterwards gives me an error
TypeError : Cannot read property 'ToString' of undefined

New Post: datarow problem

$
0
0
Hi wernersita,

What is the actual .NET type of the object you're exposing as "myRow"? If it's System.Data.DataRow, the actual name of the indexer is "Item", and the following syntax should work:
// JavaScript
MessageBox.Show(myRow.Item(0).ToString());
Note that this is a read-only shortcut. Here's the general syntax that ClearScript supports for accessing .NET indexed properties:
// JavaScript
value = obj.Item.get(index1, index2 ...);
obj.Item.set(index1, index2 ..., value);
Note also that ClearScript does support normal JavaScript-style indexing for .NET arrays.

Good luck!

Edited Issue: Access Violation Exception in v8-x64.dll [115]

$
0
0
Hi!
We launched a new site last week that uses ClearScript to server render a React application. After launch, we get around 2-3 crashes on Access Violation Exception in w3wp.exe a day per web server. The site has around 200 concurrent users on average, with peaks up over a thousand. We use the latest version of ClearScript (5.4.7).

We see that the crash is an Access Violation Exception in v8-x64.dll and we have a few dump files from such crashes, but since we don't have any debugging symbols the stack traces doesn't give us much.

Would you be interested in looking at the crash dumps to help us figure this out? Or if you can help us with debug symbols so we can get more information out of the dumps.

Some information about how we use ClearScript:
1. We create multiple V8Runtime and V8ScriptEngine and keep them in a queue. When a request comes in, we dequeue an engine, run JS and return it back to the queue.
2. Since we don't store any JS globals we reuse the same V8 context for different visitors. But we run CollectGarbage(true) for every 30 execution. We have deployed a change this morning where we call CollectGarbage(false) instead but twice as often. Not because we think it will solve it, but see if the behavior changes.
3. We don't pass any CLR references to V8. The only thing we do is call Engine.Execute with strings of JS code. When we pass data to V8 we do that by either calling Engine.Execute or Engine.Evaluate with strings of JSON.

Any help or pointers are appreciated! We'd be happy to share code with you if you need it.

Edited Issue: Access Violation Exception in v8-x64.dll [115]

$
0
0
Hi!
We launched a new site last week that uses ClearScript to server render a React application. After launch, we get around 2-3 crashes on Access Violation Exception in w3wp.exe a day per web server. The site has around 200 concurrent users on average, with peaks up over a thousand. We use the latest version of ClearScript (5.4.7).

We see that the crash is an Access Violation Exception in v8-x64.dll and we have a few dump files from such crashes, but since we don't have any debugging symbols the stack traces doesn't give us much.

Would you be interested in looking at the crash dumps to help us figure this out? Or if you can help us with debug symbols so we can get more information out of the dumps.

Some information about how we use ClearScript:
1. We create multiple V8Runtime and V8ScriptEngine and keep them in a queue. When a request comes in, we dequeue an engine, run JS and return it back to the queue.
2. Since we don't store any JS globals we reuse the same V8 context for different visitors. But we run CollectGarbage(true) for every 30 execution. We have deployed a change this morning where we call CollectGarbage(false) instead but twice as often. Not because we think it will solve it, but see if the behavior changes.
3. We don't pass any CLR references to V8. The only thing we do is call Engine.Execute with strings of JS code. When we pass data to V8 we do that by either calling Engine.Execute or Engine.Evaluate with strings of JSON.

Any help or pointers are appreciated! We'd be happy to share code with you if you need it.

New Post: Code Caching

$
0
0
Wow, that was fast!

Is there documentation available on how to use it?

New Post: Code Caching

$
0
0
Hi yosy,

V8 caching support comes in the form of new overloads for the V8ScriptEngine.Compile and V8Runtime.Compile methods. For example, to compile a script and produce a code cache, you'd do something like this:
byte[] cacheBytes;
var script = engine.Compile(code, V8CacheKind.Code, out cacheBytes);
After that you could use the cache to accelerate recompilation:
bool cacheAccepted;
var script = engine.Compile(code, V8CacheKind.Code, cacheBytes, out cacheAccepted);
You can download an API reference here.

Good luck!

New Post: Object.defineProperty on host object

$
0
0
Hello,

I am trying to use Object.defineProperty's set function to define a setter on a host object, however I remain unsuccessful in doing so. Getters interestingly enough work fine.

I add an instance of the following class to the engine as an host object using engine.AddHostObject("foo", new Foo()):
public class Foo 
{
    private string _bar = "Baz";

    public string Bar
    {
        get
        {
            return _bar;
        }
        set
        {
            _bar = value;
            Console.WriteLine(_bar);
        }
    }
}
I then define the getters and setters in JavaScript:
Object.defineProperty(foo, "bat", {
    set: function (f) {
        console.log("set: " + f);
        foo.Bar = f;
    },
    get: function () {
        return foo.Bar;
    }
});

console.log(foo.bat);
foo.bat = "quux";
console.log(foo.bat); outputs Baz while foo.bat = "quux"; displays an error with the following message:
Error: Object has no suitable property or field named 'bat'
    at Script Document:216:9 -> foo.bat = "quux";
Is there any way of getting this to work?

Created Issue: [BUG] [V8] Crash when a JavaScript proxy targets a host object [116]

$
0
0
The native value export code doesn't recognize the proxy and crashes when it fails to retrieve the internal field.

New Post: Object.defineProperty on host object

$
0
0
Greetings!

The behavior you're seeing is by design.

Host object properties are accessed via interception, which takes precedence over normal JavaScript property access. Failure to retrieve a nonexistent host property triggers the default handling to provide access to the prototype chain; that's why getters work as expected. Property assignment on the other hand throws an exception if it fails on the host side; this is done to capture as much error information as possible at the point of failure.

This asymmetric behavior is analogous to JavaScript's default property access protocol, where reads use the prototype chain but writes do not. On the other hand, as you've noticed, it also makes most host objects non-extensible on the JavaScript side. An exception is when a host object is itself extensible, such as an instance of System.Dynamic.ExpandoObject.

That's the real issue here; host objects and script objects can have conflicting notions of extensibility. It might be possible to detect that a host object is non-extensible and fall back to JavaScript semantics, but that determination would nontrivial, and it isn't clear that the resulting behavior would be appropriate in every case. In any case, ClearScript currently doesn't do that.

One possibility might be to wrap the host object in a JavaScript proxy, but currently there's a bug that prevents proxies from targeting host objects directly. Still, you might be able to use the following JavaScript function, or something similar, to produce an object with the desired behavior:
function createProxy(obj) {
    returnnew Proxy(function () {}, {
        apply: function (target, thisArg, argumentsList) {
            return Reflect.apply(obj, thisArg, argumentsList);
        },
        construct: function(target, argumentsList, newTarget) {
            return Reflect.construct(obj, argumentsList);
        },
        get: function (target, key, receiver) {
            let value = Reflect.get(obj, key);
            return (value === undefined) ? Reflect.get(target, key, receiver) : value;
        },
        set: function (target, key, value, receiver) {
            if (Reflect.has(obj, key))
                return Reflect.set(obj, key, value);
            return Reflect.set(target, key, value, receiver);
        }
    });
}
An alternative might be to create your own JavaScript proxy object that forwards selected methods and properties to the host object.

Good luck!

New Post: Clearscript V8 engine hang while debugging

$
0
0
Hi

I've implemented a similar approach as Praveen, but encountered the same issue :(

Nevertheless, I would be more than happy if I just could pause/resume, so if there is any other option to achieve a simple pause/resume functionality, I would appreciate if you could share this.

Thanks
Marco

New Post: Clearscript V8 engine hang while debugging

$
0
0
Hi Marco,

One possibility might be to use ScriptEngine.ContinuationCallback. Your callback might look something like this:
engine.ContinuationCallback = () => {
    while (ScriptIsPaused()) {
        Thread.Sleep(500);
    }
    returntrue;
};
Note that the engine only invokes the callback approximately once every two seconds, so this technique doesn't give you very precise pause/resume control.

Good luck!

New Post: Clearscript V8 engine hang while debugging

$
0
0
Hi,

Thanks for the hint.

Best,
Marco

Created Unassigned: [BUG] [VBScriptEngine] Process memory leak when re-evaluating scripts with VBScriptEngine [117]

$
0
0
In version 5.4.7 and 5.4.8 there's still a memory leak related to script evaluations with the VBScriptEngine.
I've attached a test project, where 1000 predefined equations can be evaluated with VBScriptEngine or with the V8 engine. When re-evaluating the equations with V8 engine, the used process memory keeps stable, but not with the VBScriptEnginge. It seems to be an unmanaged memory leak.
To run the attached test project properly, ClearScript has to be added via nuget first.

Commented Unassigned: [BUG] [VBScriptEngine] Process memory leak when re-evaluating scripts with VBScriptEngine [117]

$
0
0
In version 5.4.7 and 5.4.8 there's still a memory leak related to script evaluations with the VBScriptEngine.
I've attached a test project, where 1000 predefined equations can be evaluated with VBScriptEngine or with the V8 engine. When re-evaluating the equations with V8 engine, the used process memory keeps stable, but not with the VBScriptEnginge. It seems to be an unmanaged memory leak.
To run the attached test project properly, ClearScript has to be added via nuget first.
Comments: Thanks for sharing your test project! Using the [ClearScript.V8](https://www.nuget.org/packages/ClearScript.V8/) NuGet package (based on ClearScript 5.4.7), we can't reproduce a memory leak on Windows 10. That is, the private working set reaches a maximum beyond which it doesn't go no matter how many times we use the button to invoke the VBScript test. What Windows version are you using? How are you detecting the memory leak? Thanks!

Commented Unassigned: [BUG] [VBScriptEngine] Process memory leak when re-evaluating scripts with VBScriptEngine [117]

$
0
0
In version 5.4.7 and 5.4.8 there's still a memory leak related to script evaluations with the VBScriptEngine.
I've attached a test project, where 1000 predefined equations can be evaluated with VBScriptEngine or with the V8 engine. When re-evaluating the equations with V8 engine, the used process memory keeps stable, but not with the VBScriptEnginge. It seems to be an unmanaged memory leak.
To run the attached test project properly, ClearScript has to be added via nuget first.
Comments: I made my tests with the VBScriptEngine and the V8 engine by using the ClearScript.V8 nuget package in version 5.4.7 under Windows 7 Pro x64. So, I started the test application and clicked 50 times on the button "Test VB-Script", respectively the "Test V8" button and watchted the used "process memory" in the diagnostics tools in Visual Studio. I have attached two screenshots from my tests. As you can see, the used process memory when using the V8 engine keeps stable, but not for VBScript engine. In my real world application there're also evaluated hundreds of scripts hundereds of times at runtime and it would be very nice to fix this issue. Best regards.
Viewing all 2297 articles
Browse latest View live




Latest Images