ChakraCore icon indicating copy to clipboard operation
ChakraCore copied to clipboard

app crash while executing same Serialized Scirpt multiple times. Exception : System.AccessViolationException:

Open SiamAbdullah opened this issue 8 years ago • 6 comments

Hey, I wrote a sample app where I serialized JavaScript into byte array and executed serialized script in different runtime. The app is getting crashed after a period of time. It is throwing AccessViolationException.

Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at ChakraHost.Hosting.Native.JsRunScript(String script, JavaScriptSourceContext sourceContext, String sourceUrl, JavaScriptValue& result) at ChakraHost.Hosting.JavaScriptContext.RunScript(String script, JavaScriptSourceContext sourceContext, String sourceName) in E:\ChakraCoreSampleApp\ChakraCoreHost\Hosting\JavaScriptContext.cs:line 221 at ChakraCoreHost.ChakraCoreSimulation.<>c__DisplayClass3_0.b__0() in E:\ChakraCoreSampleApp\ChakraCoreHost\ChakraCoreSimulation.cs:line 70 at ChakraCoreHost.Helper.ExecuteAction(Stopwatch stopwatch, Action action, String eventName) in E:\ChakraCoreSampleApp\ChakraCoreHost\Helper.cs:line 43 at ChakraCoreHost.ChakraCoreSimulation.ExecutedSerializedScript(Int32 max) in E:\ChakraCoreSampleApp\ChakraCoreHost\ChakraCoreSimulation.cs:line 67 at ChakraCoreHost.Program.Main(String[] arguments) in E:\ChakraCoreSampleApp\ChakraCoreHost\ChakraCoreHost.cs:line 10

public void ExecutedSerializedScript(int max=1)
         {
            Console.Error.WriteLine("** starting serializing script **");

          var serializedScripts = new List<byte[]>();
          var attributes = GetAttributes();

          using (var runtime = JavaScriptRuntime.Create(attributes, JavaScriptRuntimeVersion.VersionEdge, null))
          {
              var context = runtime.CreateContext();

              using (new JavaScriptContext.Scope(context))
              {
                  foreach (var scriptName in Helper.Library)
                  {
                      byte[] buffer = null;
                      Console.Write(scriptName);
                      this.GenerateSerializedScript(Helper.LoadFile(scriptName), ref buffer);
                      serializedScripts.Add(buffer);
                  }
              }

              Console.WriteLine("**** end of script Serialization *****");
          }

          Console.WriteLine("**** start executing serialized scripts *****");
          var result = JavaScriptValue.Invalid;
          for (var i = 0; i < max; i++)
          {
              Console.WriteLine("Iteration : " + i);
              using (var runtime = JavaScriptRuntime.Create(attributes, JavaScriptRuntimeVersion.VersionEdge, null))
              {
                  var context = runtime.CreateContext();
                  using (new JavaScriptContext.Scope(context))
                  {
                      try
                      {
                          for (var index = 0; index < serializedScripts.Count; index++)
                          {
                              Helper.ExecuteAction(this.stopwatch,
                                  () =>
                                  {
                                      Native.JsRunSerializedScript(Helper.LoadFile(Helper.Library[index]), serializedScripts[index], this.currentSourceContext++, string.Empty, out result);
                                  },
                                  Helper.Library[index]);
                          }

                          Helper.ExecuteAction(this.stopwatch,
                              () =>
                              {
                                  JavaScriptContext.RunScript(Helper.DataScript, this.currentSourceContext++, String.Empty);
                              },
                              "DataScript");

                          Helper.ExecuteAction(this.stopwatch,
                              () =>
                              {
                                  result = JavaScriptContext.RunScript(Helper.RenderScript,
                                      this.currentSourceContext++, String.Empty);
                              });
                      }
                      catch (Exception e)
                      {
                          Console.Error.WriteLine("chakrahost: failed to run script: {0}", e.Message);
                      }
                      finally
                      {
                          File.WriteAllText("SerializedOutput." + i + ".html", result.ToString());
                      }
                  }
              }

              Console.Error.WriteLine("** ending serialized chakracore example **");
          }
      }

Program.cs

public static class Program
    {
        public static void Main(string[] arguments)
        {
            var cs = new ChakraCoreSimulation();
            // no issue executing script as plain string
           // cs.ExecutePlainScript(1000);  // no issue
            cs.ExecutedSerializedScript(1000); // app crash
        }
    }

I would appreciate if someone take a look and what I am doing wrong on executing serialized script. If I execute JavaScript as plainString then there is no issue

SiamAbdullah avatar Jun 23 '18 01:06 SiamAbdullah

Hey @SiamAbdullah . While nothing jumps out as wrong, it's really hard for me to tell as this is wrapped in some C# wrapper and has a bunch methods that aren't from ChakraCore (GenerateSerializedScript, ExecuteAction, etc.). Do you have a small repro project that we could take a look?

Also, you can look at some of our docs or tests to see how we'd call them in C++.

liminzhu avatar Jun 23 '18 06:06 liminzhu

My guess is that your serialized byte code buffer got freed.

curtisman avatar Jun 25 '18 15:06 curtisman

Hey @liminzhu I made the app more simple. Here is the github link https://github.com/SiamAbdullah/sampleChakraCoreApp

public static class Program
{
    public static string[] Library = new string[]
    {
        "ServerSideRenderingDataManager.js",
        "ServerSideRendering.LayoutWriter.js",
        "ServerSideRendering.Instrumentation.js",
        "react.production16.1.1.min.js",
        "react-dom-server.browser.production16.1.1.min.js",
        "redux.min.js",
        "Region.js",
        "InstLink.js",
        "InstForm.js",
        "CommentBox.js",
        "CommentBoxServerRendering.js"
    };

    public static string DataScript = "ServerSideRenderingDataManager.set(\"CommentBoxData\",{\"Title\":\"Say What do you have in your mind ....\",\"Comments\":[{\"Author\":\"Chap\",\"Message\":\"Microsoft is Awesome\"},{\"Author\":\"Mukul\",\"Message\":\"Bing Rocks !!!!\"},{\"Author\":\"Siam\",\"Message\":\"Serverside Rendering is Awesome !!!!!!!\"},{\"Author\":\"Lawrence\",\"Message\":\"Container is comming in SnR....\"},{\"Author\":\"Sudeep\",\"Message\":\"I love serverside rendering. Documentation is awesome....\"}]});;ServerSideRenderingDataManager.set(\"link\",{\"Url\":\"http://www.bing.com\",\"UrlWithFormCode\":\"http://www.bing.com\",\"FinalFormCode\":\"\",\"LogType\":0,\"SubVertical\":null,\"Text\":null,\"Vertical\":null,\"UniqueId\":{\"K\":5000,\"KValue\":5000,\"Namespace\":\"SERP\"},\"Role\":null,\"Name\":null,\"Augmentation\":null,\"Source\":null,\"CurrentUseCount\":0});";

    public static string RenderScript = "ServerSideRenderingCommentBoxEample.render();";
    public static string InstrumentationScript = "HostInstrumentation.getInstrumentationObject();ServerSideRenderingDataManager.clear();LayoutWriter.clear();";

    private static JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);


    public static void Main(string[] arguments)
    {
        ExecutedSerializedScript(1000);
    }

    private static void ExecutedSerializedScript(int max = 1)
    {
        Console.Error.WriteLine("** start Serializing script **");

        var serializedScripts = new List<byte[]>();
        var attributes = GetAttributes();

        using (var runtime = JavaScriptRuntime.Create(attributes, JavaScriptRuntimeVersion.VersionEdge, null))
        {
            var context = runtime.CreateContext();

            using (new JavaScriptContext.Scope(context))
            {
                foreach (var scriptName in Library)
                {
                    byte[] buffer = null;
                    GenerateSerializedScript(LoadFile(scriptName), ref buffer);
                    serializedScripts.Add(buffer);
                }
            }

            Console.WriteLine("**** end of script Serialization *****");
        }

        Console.WriteLine("**** start executing serialized scripts *****");
        var result = JavaScriptValue.Invalid;
        for (var i = 0; i < max; i++)
        {
            Console.WriteLine("Iteration : " + i);
            using (var runtime = JavaScriptRuntime.Create(attributes, JavaScriptRuntimeVersion.VersionEdge, null))
            {
                var context = runtime.CreateContext();
                using (new JavaScriptContext.Scope(context))
                {
                    try
                    {
                        for (var index = 0; index < serializedScripts.Count; index++)
                        {
                            Native.JsRunSerializedScript(LoadFile(Library[index]), serializedScripts[index], currentSourceContext++, string.Empty, out result);
                        }

                        JavaScriptContext.RunScript(DataScript, currentSourceContext++, String.Empty);
                        result = JavaScriptContext.RunScript(RenderScript, currentSourceContext++, String.Empty);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine("chakrahost: failed to run script: {0}", e.Message);
                    }
                    finally
                    {
                        File.WriteAllText("SerializedOutput." + i + ".html", result.ToString());
                    }
                }
            }

            Console.Error.WriteLine("** end serialized script execution**");
        }
    }

    private static void GenerateSerializedScript(string script, ref byte[] buffer)
    {
        ulong len = 0;
        Native.JsSerializeScript(script, buffer, ref len);
        buffer = new byte[len];
        Native.JsSerializeScript(script, buffer, ref len);
    }

    private static JavaScriptRuntimeAttributes GetAttributes()
    {
        return JavaScriptRuntimeAttributes.None | JavaScriptRuntimeAttributes.DisableBackgroundWork;
    }

    private static string LoadFile(string filename)
    {
        var path = Path.Combine("Scripts", filename);
        if (File.Exists(path))
        {
            return File.ReadAllText(path);
        }

        throw new Exception("File doesn't exit " + path);
    }
}

After executing same serialized script over time cause this AccessViolation error. accessviolationerror

I use JsSerializeScript Api to serialize script.

Context: We have an aspnet application where we use chakracore to execute JavaScript on server for isomorphic application. Every request we create a runtime and execute the script. We also have engine pool to reuse runtime. Perf is our main concern. So we tried to execute serialized script but it caused our application crash. That's why I created this simple app so that It would be easy for you guys to figure out the issue. I have the github link of this simple app. I would really appreciate if one of you guys take a look it properly.

SiamAbdullah avatar Jun 25 '18 16:06 SiamAbdullah

@curtisman I got this access violation when I run plain script after executing serialized script. I am not sure this is for byte code buffer freed or not.

SiamAbdullah avatar Jun 25 '18 21:06 SiamAbdullah

@SiamAbdullah this looks like a case of the .NET GC moving the memory out from under ChakraCore. When you run the serialized script ChakraCore will hold onto the buffer that was passed until the function references are collected by the ChakraCore GC.

Unless you use JsRunSerializedScriptWithCallback and handle the unload callback, you'll have to ensure that the bytecode buffer stays valid for the full lifetime of the runtime. Before loading the bytecode buffer you'll need to ensure that the object is pinned in the .NET GC so that the pointer continues to remain valid. Once you destroy the runtime the bytecode buffers can then be unpinned and the .NET GC is free to move them again.

EDIT: Here's a rough fix that seems to have resolved the issue:

diff --git a/ChakraCoreHost/ChakraCoreHost.cs b/ChakraCoreHost/ChakraCoreHost.cs
index e3dac90..8d35682 100644
--- a/ChakraCoreHost/ChakraCoreHost.cs
+++ b/ChakraCoreHost/ChakraCoreHost.cs
@@ -4,6 +4,7 @@ namespace ChakraCoreHost
     using System;
     using System.Collections.Generic;
     using System.IO;
+    using System.Runtime.InteropServices;
     using ChakraHost.Hosting;
 
     public static class Program
@@ -62,18 +63,26 @@ namespace ChakraCoreHost
 
             Console.WriteLine("**** start executing serialized scripts *****");
             var result = JavaScriptValue.Invalid;
+            var handles = new List<GCHandle>();
             for (var i = 0; i < max; i++)
             {
                 Console.WriteLine("Iteration : " + i);
+
+                try
+                {
                     using (var runtime = JavaScriptRuntime.Create(attributes, JavaScriptRuntimeVersion.VersionEdge, null))
                     {
                         var context = runtime.CreateContext();
                         using (new JavaScriptContext.Scope(context))
                         {
+
                             try
                             {
                                 for (var index = 0; index < serializedScripts.Count; index++)
                                 {
+                                    // Make sure the object is pinned in GC memory before calling.
+                                    handles.Add(GCHandle.Alloc(serializedScripts[index], GCHandleType.Pinned));
+
                                     Native.JsRunSerializedScript(LoadFile(Library[index]), serializedScripts[index], currentSourceContext++, string.Empty, out result);
                                 }
 
@@ -90,6 +99,17 @@ namespace ChakraCoreHost
                             }
                         }
                     }
+                }
+                finally
+                {
+                    foreach (GCHandle handle in handles)
+                    {
+                        // Free the handles so the GC can manage the memory again.
+                        handle.Free();
+                    }
+
+                    handles.Clear();
+                }
 
                 Console.Error.WriteLine("** end serialized script execution**");
             }

kfarnung avatar Jun 26 '18 00:06 kfarnung

Thanks @kfarnung for clarification. It's also make sense why the crash happen randomly. I missed to hold bytecode buffer stays valid for the full lifetime of the runtime. I made the change and looks ok to me. Thanks a lot.

SiamAbdullah avatar Jun 26 '18 00:06 SiamAbdullah