Esempio n. 1
0
 public static string FormatInvariant(string format, params object[] args)
 {
     return(MiscHelpers.FormatInvariant(format, args));
 }
Esempio n. 2
0
        private string GetStackTraceInternal()
        {
            Debug.Assert(engineFlags.HasFlag(WindowsScriptEngineFlags.EnableDebugging));
            var stackTrace = string.Empty;

            IEnumDebugStackFrames enumFrames;

            activeScript.EnumStackFrames(out enumFrames);

            while (true)
            {
                DebugStackFrameDescriptor descriptor;
                uint countFetched;
                enumFrames.Next(1, out descriptor, out countFetched);
                if (countFetched < 1)
                {
                    break;
                }

                try
                {
                    string description;
                    descriptor.Frame.GetDescriptionString(true, out description);

                    IDebugCodeContext codeContext;
                    descriptor.Frame.GetCodeContext(out codeContext);

                    IDebugDocumentContext documentContext;
                    codeContext.GetDocumentContext(out documentContext);
                    if (documentContext == null)
                    {
                        stackTrace += MiscHelpers.FormatInvariant("    at {0}\n", description);
                    }
                    else
                    {
                        IDebugDocument document;
                        documentContext.GetDocument(out document);
                        var documentText = (IDebugDocumentText)document;

                        string documentName;
                        document.GetName(DocumentNameType.Title, out documentName);

                        uint position;
                        uint length;
                        documentText.GetPositionOfContext(documentContext, out position, out length);

                        var pBuffer = Marshal.AllocCoTaskMem((int)(sizeof(char) * length));
                        try
                        {
                            uint lengthReturned = 0;
                            documentText.GetText(position, pBuffer, IntPtr.Zero, ref lengthReturned, length);
                            var codeLine = Marshal.PtrToStringUni(pBuffer, (int)lengthReturned);

                            uint lineNumber;
                            uint offsetInLine;
                            documentText.GetLineOfPosition(position, out lineNumber, out offsetInLine);

                            stackTrace += MiscHelpers.FormatInvariant("    at {0} ({1}:{2}:{3}) -> {4}\n", description, documentName, lineNumber, offsetInLine, codeLine);
                        }
                        finally
                        {
                            Marshal.FreeCoTaskMem(pBuffer);
                        }
                    }
                }
                finally
                {
                    if (descriptor.FinalObject != null)
                    {
                        Marshal.ReleaseComObject(descriptor.FinalObject);
                    }
                }
            }

            return(stackTrace.TrimEnd('\n'));
        }
Esempio n. 3
0
 /// <summary>
 /// Initializes a new VBScript engine instance with the specified programmatic
 /// identifier, name, and options.
 /// </summary>
 /// <param name="progID">The programmatic identifier (ProgID) of the VBScript engine class.</param>
 /// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
 /// <param name="flags">A value that selects options for the operation.</param>
 /// <remarks>
 /// The <paramref name="progID"/> argument can be a class identifier (CLSID) in standard
 /// GUID format with braces (e.g., "{F414C260-6AC0-11CF-B6D1-00AA00BBBB58}").
 /// </remarks>
 protected VBScriptEngine(string progID, string name, WindowsScriptEngineFlags flags)
     : base(progID, name, flags)
 {
     Execute(
         MiscHelpers.FormatInvariant("{0} [internal]", GetType().Name),
         @"
             class EngineInternalImpl
                 public function getCommandResult(value)
                     if IsObject(value) then
                         if value is nothing then
                             getCommandResult = ""[nothing]""
                         else
                             dim valueTypeName
                             valueTypeName = TypeName(value)
                             if (valueTypeName = ""Object"" or valueTypeName = ""Unknown"") then
                                 set getCommandResult = value
                             else
                                 getCommandResult = ""[ScriptObject:"" & valueTypeName & ""]""
                             end if
                         end if
                     elseif IsArray(value) then
                         getCommandResult = ""[array]""
                     elseif IsNull(value) then
                         getCommandResult = ""[null]""
                     elseif IsEmpty(value) then
                         getCommandResult = ""[empty]""
                     else
                         getCommandResult = CStr(value)
                     end if
                 end function
                 public function invokeConstructor(constructor, args)
                     Err.Raise 445
                 end function
                 public function invokeMethod(target, method, args)
                     if IsObject(target) then
                         if target is nothing then
                         else
                             Err.Raise 445
                         end if
                     elseif IsNull(target) then
                     elseif IsEmpty(target) then
                     else
                         Err.Raise 445
                     end if
                     dim count
                     if IsArray(args) then
                         count = UBound(args) + 1
                         if count < 1 then
                             invokeMethod = method()
                         elseif count = 1 then
                             invokeMethod = method(args(0))
                         elseif count = 2 then
                             invokeMethod = method(args(0), args(1))
                         elseif count = 3 then
                             invokeMethod = method(args(0), args(1), args(2))
                         elseif count = 4 then
                             invokeMethod = method(args(0), args(1), args(2), args(3))
                         elseif count = 5 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4))
                         elseif count = 6 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5))
                         elseif count = 7 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6))
                         elseif count = 8 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7))
                         elseif count = 9 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8))
                         elseif count = 10 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9))
                         elseif count = 11 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10))
                         elseif count = 12 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11))
                         elseif count = 13 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12))
                         elseif count = 14 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12), args(13))
                         elseif count = 15 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12), args(13), args(14))
                         elseif count = 16 then
                             invokeMethod = method(args(0), args(1), args(2), args(3), args(4), args(5), args(6), args(7), args(8), args(9), args(10), args(11), args(12), args(13), args(14), args(15))
                         else
                             Err.Raise 450
                         end if
                     else
                         count = args.Length
                         if count < 1 then
                             invokeMethod = method()
                         elseif count = 1 then
                             invokeMethod = method(args.GetValue(0))
                         elseif count = 2 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1))
                         elseif count = 3 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2))
                         elseif count = 4 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3))
                         elseif count = 5 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4))
                         elseif count = 6 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5))
                         elseif count = 7 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6))
                         elseif count = 8 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7))
                         elseif count = 9 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8))
                         elseif count = 10 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9))
                         elseif count = 11 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10))
                         elseif count = 12 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11))
                         elseif count = 13 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11), args.GetValue(12))
                         elseif count = 14 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11), args.GetValue(12), args.GetValue(13))
                         elseif count = 15 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11), args.GetValue(12), args.GetValue(13), args.GetValue(14))
                         elseif count = 16 then
                             invokeMethod = method(args.GetValue(0), args.GetValue(1), args.GetValue(2), args.GetValue(3), args.GetValue(4), args.GetValue(5), args.GetValue(6), args.GetValue(7), args.GetValue(8), args.GetValue(9), args.GetValue(10), args.GetValue(11), args.GetValue(12), args.GetValue(13), args.GetValue(14), args.GetValue(15))
                         else
                             Err.Raise 450
                         end if
                     end if
                 end function
             end class
             set EngineInternal = new EngineInternalImpl
         "
         );
 }
Esempio n. 4
0
        public static object InvokeVBTestFunction(string code)
        {
            var options = new CompilerParameters {
                GenerateInMemory = true
            };

            options.ReferencedAssemblies.Add("ClearScript.dll");
            options.ReferencedAssemblies.Add("ClearScriptTest.dll");
            options.ReferencedAssemblies.Add(typeof(Enumerable).Assembly.Location);
            options.ReferencedAssemblies.Add(typeof(Assert).Assembly.Location);
            var results = new VBCodeProvider().CompileAssemblyFromSource(options, new[] { MiscHelpers.FormatInvariant(@"
                Imports System
                Imports System.Linq
                Imports Microsoft.ClearScript
                Imports Microsoft.ClearScript.Test
                Imports Microsoft.ClearScript.V8
                Imports Microsoft.ClearScript.Windows
                Imports Microsoft.VisualStudio.TestTools.UnitTesting
                Module TestModule
                    Function TestFunction
                        {0}
                    End Function
                End Module
            ", code) });

            if (results.Errors.HasErrors)
            {
                var messageBuilder = new StringBuilder("Errors encountered during Visual Basic compilation:\n");
                foreach (var error in results.Errors)
                {
                    messageBuilder.Append(error);
                    messageBuilder.Append('\n');
                }

                throw new OperationCanceledException(messageBuilder.ToString());
            }

            return(results.CompiledAssembly.GetType("TestModule").InvokeMember("TestFunction", BindingFlags.InvokeMethod, null, null, MiscHelpers.GetEmptyArray <object>()));
        }
        public void VBScriptEngine_Evaluate_Array()
        {
            // ReSharper disable ImplicitlyCapturedClosure

            var lengths      = new[] { 3, 5, 7 };
            var formatParams = string.Join(", ", Enumerable.Range(0, lengths.Length).Select(position => "{" + position + "}"));

            var hosts = Array.CreateInstance(typeof(object), lengths);

            hosts.Iterate(indices => hosts.SetValue(new HostFunctions(), indices));
            engine.AddHostObject("hostArray", hosts);

            engine.Execute(MiscHelpers.FormatInvariant("dim hosts(" + formatParams + ")", lengths.Select(length => (object)(length - 1)).ToArray()));
            hosts.Iterate(indices => engine.Execute(MiscHelpers.FormatInvariant("set hosts(" + formatParams + ") = hostArray.GetValue(" + formatParams + ")", indices.Select(index => (object)index).ToArray())));
            hosts.Iterate(indices => Assert.AreSame(hosts.GetValue(indices), engine.Evaluate(MiscHelpers.FormatInvariant("hosts(" + formatParams + ")", indices.Select(index => (object)index).ToArray()))));

            var result = engine.Evaluate("hosts");

            Assert.IsInstanceOfType(result, typeof(object[, , ]));
            var hostArray = (object[, , ])result;

            hosts.Iterate(indices => Assert.AreSame(hosts.GetValue(indices), hostArray.GetValue(indices)));

            // ReSharper restore ImplicitlyCapturedClosure
        }
        private string GetStackTraceInternal()
        {
            Debug.Assert(processDebugManager != null);
            var stackTrace = string.Empty;

            IEnumDebugStackFrames enumFrames;

            activeScript.EnumStackFrames(out enumFrames);

            while (true)
            {
                DebugStackFrameDescriptor descriptor;
                uint countFetched;
                enumFrames.Next(1, out descriptor, out countFetched);
                if (countFetched < 1)
                {
                    break;
                }

                try
                {
                    string description;
                    descriptor.Frame.GetDescriptionString(true, out description);

                    IDebugCodeContext codeContext;
                    descriptor.Frame.GetCodeContext(out codeContext);

                    IDebugDocumentContext documentContext;
                    codeContext.GetDocumentContext(out documentContext);
                    if (documentContext == null)
                    {
                        stackTrace += MiscHelpers.FormatInvariant("    at {0}\n", description);
                    }
                    else
                    {
                        IDebugDocument document;
                        documentContext.GetDocument(out document);
                        var documentText = (IDebugDocumentText)document;

                        string documentName;
                        document.GetName(DocumentNameType.UniqueTitle, out documentName);

                        uint position;
                        uint length;
                        documentText.GetPositionOfContext(documentContext, out position, out length);

                        using (var bufferBlock = new CoTaskMemArrayBlock(sizeof(char), (int)length))
                        {
                            uint lengthReturned = 0;
                            documentText.GetText(position, bufferBlock.Addr, IntPtr.Zero, ref lengthReturned, length);
                            var codeLine = Marshal.PtrToStringUni(bufferBlock.Addr, (int)lengthReturned);

                            uint lineNumber;
                            uint offsetInLine;
                            documentText.GetLineOfPosition(position, out lineNumber, out offsetInLine);

                            stackTrace += MiscHelpers.FormatInvariant("    at {0} ({1}:{2}:{3}) -> {4}\n", description, documentName, lineNumber, offsetInLine, codeLine);
                        }
                    }
                }
                finally
                {
                    if (descriptor.pFinalObject != IntPtr.Zero)
                    {
                        Marshal.Release(descriptor.pFinalObject);
                    }
                }
            }

            return(stackTrace.TrimEnd('\n'));
        }
Esempio n. 7
0
            public static MethodBindResult Create(string name, object rawResult, HostTarget hostTarget, object[] args)
            {
                var method = rawResult as MethodInfo;

                if (method != null)
                {
                    if ((method.IsStatic) && !hostTarget.Flags.HasFlag(HostTargetFlags.AllowStaticMembers))
                    {
                        return(new MethodBindFailure(() => new InvalidOperationException(MiscHelpers.FormatInvariant("Cannot access static method '{0}' in non-static context", method.Name))));
                    }

                    return(new MethodBindSuccess(hostTarget, method, args));
                }

                return(new MethodBindFailure((rawResult as Func <Exception>) ?? (() => new NotSupportedException(MiscHelpers.FormatInvariant("Invocation of method '{0}' failed (unrecognized binding)", name)))));
            }
Esempio n. 8
0
        public override string ToString()
        {
            var objectName = value.GetFriendlyName(typeof(T));

            return(MiscHelpers.FormatInvariant("HostVariable:{0}", objectName));
        }
Esempio n. 9
0
        private MethodBindResult BindMethod(string name, Type[] typeArgs, object[] args, object[] bindArgs)
        {
            var bindFlags = GetMethodBindFlags();

            // WARNING: BindSignature holds on to the specified typeArgs; subsequent modification
            // will result in bugs that are difficult to diagnose. Create a copy if necessary.

            var signature = new BindSignature(accessContext, bindFlags, target, name, typeArgs, bindArgs);
            MethodBindResult result;

            object rawResult;

            if (engine.TryGetCachedBindResult(signature, out rawResult))
            {
                result = MethodBindResult.Create(name, rawResult, target, args);
            }
            else
            {
                result = BindMethodInternal(accessContext, bindFlags, target, name, typeArgs, args, bindArgs);
                if (!result.IsPreferredMethod(this, name))
                {
                    if (result is MethodBindSuccess)
                    {
                        result = new MethodBindFailure(() => new MissingMemberException(MiscHelpers.FormatInvariant("Object has no method named '{0}' that matches the specified arguments", name)));
                    }

                    foreach (var altName in GetAltMethodNames(name, bindFlags))
                    {
                        var altResult = BindMethodInternal(accessContext, bindFlags, target, altName, typeArgs, args, bindArgs);
                        if (altResult.IsUnblockedMethod(this))
                        {
                            result = altResult;
                            break;
                        }
                    }
                }

                if ((result is MethodBindFailure) && engine.UseReflectionBindFallback)
                {
                    var reflectionResult = BindMethodUsingReflection(bindFlags, target, name, typeArgs, args);
                    if (reflectionResult is MethodBindSuccess)
                    {
                        result = reflectionResult;
                    }
                }

                engine.CacheBindResult(signature, result.RawResult);
            }

            return(result);
        }
Esempio n. 10
0
        private static object BindMethodRaw(BindingFlags bindFlags, InvokeMemberBinder binder, HostTarget target, object[] bindArgs)
        {
            var expr = DynamicHelpers.Bind(binder, target, bindArgs).Expression;

            if (expr == null)
            {
                return(new Func <Exception>(() => new MissingMemberException(MiscHelpers.FormatInvariant("Object has no method named '{0}'", binder.Name))));
            }

            if (expr.NodeType == ExpressionType.Dynamic)
            {
                // The binding result is a dynamic call, which is indicative of COM interop. This
                // sort of binding is not very useful here; it can't be resolved to a MethodInfo
                // instance, and caching it is problematic because it includes argument bindings.
                // Falling back to reflection should work in most cases because COM interfaces
                // support neither generic nor overloaded methods.

                try
                {
                    var method = target.Type.GetMethod(binder.Name, bindFlags);
                    return((object)method ?? new Func <Exception>(() => new MissingMemberException(MiscHelpers.FormatInvariant("Object has no method named '{0}'", binder.Name))));
                }
                catch (AmbiguousMatchException exception)
                {
                    return(new Func <Exception>(() => new AmbiguousMatchException(exception.Message)));
                }
            }

            return((new MethodBindingVisitor(target.InvokeTarget, binder.Name, expr)).Result);
        }
Esempio n. 11
0
 public override string ToString()
 {
     return(MiscHelpers.FormatInvariant("HostIndexedProperty:{0}", name));
 }
Esempio n. 12
0
        private void HandleWebRequest(WebContext webContext)
        {
            // https://github.com/buggerjs/bugger-daemon/blob/master/README.md#api,
            // https://github.com/nodejs/node/blob/master/src/inspector_socket_server.cc

            if (webContext.Request.RawUrl.Equals("/json", StringComparison.OrdinalIgnoreCase) ||
                webContext.Request.RawUrl.Equals("/json/list", StringComparison.OrdinalIgnoreCase))
            {
                // ReSharper disable PossibleNullReferenceException

                if (activeClient != null)
                {
                    SendWebResponse(webContext, MiscHelpers.FormatInvariant(
                                        "[ {{\r\n" +
                                        "  \"id\": \"{0}\",\r\n" +
                                        "  \"type\": \"node\",\r\n" +
                                        "  \"description\": \"ClearScript V8 runtime: {1}\",\r\n" +
                                        "  \"title\": \"{2}\",\r\n" +
                                        "  \"url\": \"{3}\",\r\n" +
                                        "  \"faviconUrl\": \"{4}\"\r\n" +
                                        "}} ]\r\n",
                                        targetId,
                                        JsonEscape(name),
                                        JsonEscape(AppDomain.CurrentDomain.FriendlyName),
                                        JsonEscape(new Uri(Process.GetCurrentProcess().MainModule.FileName)),
                                        faviconUrl
                                        ));
                }
                else
                {
                    SendWebResponse(webContext, MiscHelpers.FormatInvariant(
                                        "[ {{\r\n" +
                                        "  \"id\": \"{0}\",\r\n" +
                                        "  \"type\": \"node\",\r\n" +
                                        "  \"description\": \"ClearScript V8 runtime: {1}\",\r\n" +
                                        "  \"title\": \"{2}\",\r\n" +
                                        "  \"url\": \"{3}\",\r\n" +
                                        "  \"faviconUrl\": \"{6}\",\r\n" +
                                        "  \"devtoolsFrontendUrl\": \"chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws={4}:{5}/{0}\",\r\n" +
                                        "  \"webSocketDebuggerUrl\": \"ws://{4}:{5}/{0}\"\r\n" +
                                        "}} ]\r\n",
                                        targetId,
                                        JsonEscape(name),
                                        JsonEscape(AppDomain.CurrentDomain.FriendlyName),
                                        JsonEscape(new Uri(Process.GetCurrentProcess().MainModule.FileName)),
                                        webContext.Request.Uri.Host,
                                        webContext.Request.Uri.Port,
                                        faviconUrl
                                        ));
                }

                // ReSharper restore PossibleNullReferenceException
            }
            else if (webContext.Request.RawUrl.Equals("/json/version", StringComparison.OrdinalIgnoreCase))
            {
                SendWebResponse(webContext, MiscHelpers.FormatInvariant(
                                    "{{\r\n" +
                                    "  \"Browser\": \"ClearScript {0} [V8 {1}]\",\r\n" +
                                    "  \"Protocol-Version\": \"1.1\"\r\n" +
                                    "}}\r\n",
                                    ClearScriptVersion.Value,
                                    version
                                    ));
            }
            else if (webContext.Request.RawUrl.StartsWith("/json/activate/", StringComparison.OrdinalIgnoreCase))
            {
                var requestTargetId = webContext.Request.RawUrl.Substring(15);
                if (requestTargetId.Equals(targetId.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    SendWebResponse(webContext, "Target activated", "text/plain");
                }
                else
                {
                    SendWebResponse(webContext, "No such target id: " + requestTargetId, "text/plain", 404);
                }
            }
            else if (webContext.Request.RawUrl.StartsWith("/json/close/", StringComparison.OrdinalIgnoreCase))
            {
                var requestTargetId = webContext.Request.RawUrl.Substring(12);
                if (requestTargetId.Equals(targetId.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    SendWebResponse(webContext, "Target is closing", "text/plain");
                }
                else
                {
                    SendWebResponse(webContext, "No such target id: " + requestTargetId, "text/plain", 404);
                }
            }
            else if (webContext.Request.RawUrl.StartsWith("/json/new?", StringComparison.OrdinalIgnoreCase) ||
                     webContext.Request.RawUrl.Equals("/json/protocol", StringComparison.OrdinalIgnoreCase))
            {
                webContext.Response.Close(501);
            }
            else
            {
                webContext.Response.Close(404);
            }
        }
Esempio n. 13
0
        private static Assembly LoadAssembly()
        {
            try
            {
                return(Assembly.Load("ClearScriptV8"));
            }
            catch (FileNotFoundException)
            {
            }

            var hCppLibrary = LoadNativeLibrary("v8-libcpp");

            try
            {
                var hBaseLibrary = LoadNativeLibrary("v8-base");
                try
                {
                    var hLibrary = LoadNativeLibrary("v8");
                    try
                    {
                        var suffix         = Environment.Is64BitProcess ? "64" : "32";
                        var assemblyName   = "ClearScriptV8-" + suffix;
                        var fileName       = assemblyName + ".dll";
                        var messageBuilder = new StringBuilder();

                        var paths = GetDirPaths().Select(dirPath => Path.Combine(dirPath, deploymentDirName, fileName)).Distinct();
                        foreach (var path in paths)
                        {
                            try
                            {
                                return(Assembly.LoadFrom(path));
                            }
                            catch (Exception exception)
                            {
                                messageBuilder.AppendInvariant("\n{0}: {1}", path, MiscHelpers.EnsureNonBlank(exception.Message, "Unknown error"));
                            }
                        }

                        if (string.IsNullOrEmpty(deploymentDirName))
                        {
                            var publicKeyToken = typeof(V8Proxy).Assembly.GetName().GetPublicKeyToken();
                            if ((publicKeyToken != null) && (publicKeyToken.Length > 0))
                            {
                                var assemblyFullName = MiscHelpers.FormatInvariant("{0}, Version={1}, Culture=neutral, PublicKeyToken={2}", assemblyName, ClearScriptVersion.Value, BitConverter.ToString(publicKeyToken).Replace("-", string.Empty));
                                try
                                {
                                    return(Assembly.Load(assemblyFullName));
                                }
                                catch (Exception exception)
                                {
                                    messageBuilder.AppendInvariant("\n{0}: {1}", assemblyFullName, MiscHelpers.EnsureNonBlank(exception.Message, "Unknown error"));
                                }
                            }
                        }

                        var message = MiscHelpers.FormatInvariant("Cannot load V8 interface assembly. Load failure information for {0}:{1}", fileName, messageBuilder);
                        throw new TypeLoadException(message);
                    }
                    finally
                    {
                        NativeMethods.FreeLibrary(hLibrary);
                    }
                }
                finally
                {
                    NativeMethods.FreeLibrary(hBaseLibrary);
                }
            }
            finally
            {
                NativeMethods.FreeLibrary(hCppLibrary);
            }
        }
Esempio n. 14
0
 public override string ToString()
 {
     return(MiscHelpers.FormatInvariant("HostMethod:{0}", name));
 }
Esempio n. 15
0
        internal V8ScriptEngine(V8Runtime runtime, string name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, int debugPort)
            : base((runtime != null) ? runtime.Name + ":" + name : name)
        {
            using (var localRuntime = (runtime != null) ? null : new V8Runtime(name, constraints))
            {
                var activeRuntime = runtime ?? localRuntime;

                engineFlags = flags;
                proxy       = V8ContextProxy.Create(activeRuntime.IsolateProxy, Name, flags.HasFlag(V8ScriptEngineFlags.EnableDebugging), flags.HasFlag(V8ScriptEngineFlags.DisableGlobalMembers), debugPort);
                script      = GetRootItem();

                var engineInternal = Evaluate(
                    MiscHelpers.FormatInvariant("{0} [internal]", GetType().Name),
                    false,
                    @"
                        EngineInternal = (function () {

                            function convertArgs(args) {
                                var result = [];
                                var count = args.Length;
                                for (var i = 0; i < count; i++) {
                                    result.push(args[i]);
                                }
                                return result;
                            }

                            function construct(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) {
                                return new this(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15);
                            }

                            return {

                                getCommandResult: function (value) {
                                    if (value != null) {
                                        if (((typeof(value) == 'object') && !value.hasOwnProperty('{c2cf47d3-916b-4a3f-be2a-6ff567425808}')) || (typeof(value) == 'function')) {
                                            if (typeof(value.toString) == 'function') {
                                                return value.toString();
                                            }
                                        }
                                    }
                                    return value;
                                },

                                invokeConstructor: function (constructor, args) {
                                    if (typeof(constructor) != 'function') {
                                        throw new Error('Function expected');
                                    }
                                    return construct.apply(constructor, convertArgs(args));
                                },

                                invokeMethod: function (target, method, args) {
                                    if (typeof(method) != 'function') {
                                        throw new Error('Function expected');
                                    }
                                    return method.apply(target, convertArgs(args));
                                },

                                getStackTrace: function () {
                                    try {
                                        throw new Error('[stack trace]');
                                    }
                                    catch (exception) {
                                        return exception.stack;
                                    }
                                    return '';
                                }
                            };
                        })();
                    "
                    );

                ((IDisposable)engineInternal).Dispose();
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Initializes a new JScript engine instance with the specified programmatic
        /// identifier, name, and options.
        /// </summary>
        /// <param name="progID">The programmatic identifier (ProgID) of the JScript engine class.</param>
        /// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
        /// <param name="flags">A value that selects options for the operation.</param>
        /// <remarks>
        /// The <paramref name="progID"/> argument can be a class identifier (CLSID) in standard
        /// GUID format with braces (e.g., "{F414C260-6AC0-11CF-B6D1-00AA00BBBB58}").
        /// </remarks>
        protected JScriptEngine(string progID, string name, WindowsScriptEngineFlags flags)
            : base(progID, name, flags)
        {
            Execute(
                MiscHelpers.FormatInvariant("{0} [internal]", GetType().Name),
                @"
                    EngineInternal = (function () {

                        function convertArgs(args) {
                            var result = [];
                            if (args.GetValue) {
                                var count = args.Length;
                                for (var i = 0; i < count; i++) {
                                    result.push(args[i]);
                                }
                            }
                            else {
                                args = new VBArray(args);
                                var count = args.ubound(1) + 1;
                                for (var i = 0; i < count; i++) {
                                    result.push(args.getItem(i));
                                }
                            }
                            return result;
                        }

                        function construct(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) {
                            return new this(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15);
                        }

                        return {

                            getCommandResult: function (value) {
                                if (value != null) {
                                    if ((typeof(value) == 'object') || (typeof(value) == 'function')) {
                                        if (typeof(value.toString) == 'function') {
                                            return value.toString();
                                        }
                                    }
                                }
                                return value;
                            },

                            invokeConstructor: function (constructor, args) {
                                if (typeof(constructor) != 'function') {
                                    throw new Error('Function expected');
                                }
                                return construct.apply(constructor, convertArgs(args));
                            },

                            invokeMethod: function (target, method, args) {
                                if (typeof(method) != 'function') {
                                    throw new Error('Function expected');
                                }
                                return method.apply(target, convertArgs(args));
                            }
                        };
                    })();
                "
                );
        }
Esempio n. 17
0
        internal V8ScriptEngine(V8Runtime runtime, string name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, int debugPort)
            : base((runtime != null) ? runtime.Name + ":" + name : name)
        {
            using (var localRuntime = (runtime != null) ? null : new V8Runtime(name, constraints))
            {
                var activeRuntime = runtime ?? localRuntime;
                hostItemCollateral = activeRuntime.HostItemCollateral;

                engineFlags = flags;
                proxy       = V8ContextProxy.Create(activeRuntime.IsolateProxy, Name, flags, debugPort);
                script      = GetRootItem();

                var engineInternal = Evaluate(
                    MiscHelpers.FormatInvariant("{0} [internal]", GetType().Name),
                    false,
                    @"
                        EngineInternal = (function () {

                            function convertArgs(args) {
                                var result = [];
                                var count = args.Length;
                                for (var i = 0; i < count; i++) {
                                    result.push(args[i]);
                                }
                                return result;
                            }

                            function construct(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) {
                                return new this(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15);
                            }

                            var isHostObjectKey = this.isHostObjectKey;
                            delete this.isHostObjectKey;

                            return {

                                getCommandResult: function (value) {
                                    if (value == null) {
                                        return value;
                                    }
                                    if (typeof(value.hasOwnProperty) != 'function') {
                                        return '[external]';
                                    }
                                    if (value[isHostObjectKey] === true) {
                                        return value;
                                    }
                                    if (typeof(value.toString) != 'function') {
                                        return '[' + typeof(value) + ']';
                                    }
                                    return value.toString();
                                },

                                invokeConstructor: function (constructor, args) {
                                    if (typeof(constructor) != 'function') {
                                        throw new Error('Function expected');
                                    }
                                    return construct.apply(constructor, convertArgs(args));
                                },

                                invokeMethod: function (target, method, args) {
                                    if (typeof(method) != 'function') {
                                        throw new Error('Function expected');
                                    }
                                    return method.apply(target, convertArgs(args));
                                },

                                getStackTrace: function () {
                                    try {
                                        throw new Error('[stack trace]');
                                    }
                                    catch (exception) {
                                        return exception.stack;
                                    }
                                    return '';
                                }
                            };
                        })();
                    "
                    );

                ((IDisposable)engineInternal).Dispose();

                if (flags.HasFlag(V8ScriptEngineFlags.EnableDebugging | V8ScriptEngineFlags.AwaitDebuggerAndPauseOnStart))
                {
                    awaitDebuggerAndPause = true;
                }
            }
        }
Esempio n. 18
0
 public override string ToString()
 {
     return(MiscHelpers.FormatInvariant("ref {0}", Type.GetFriendlyName()));
 }
Esempio n. 19
0
 /// <summary>
 /// Initializes a new VBScript engine instance with the specified programmatic
 /// identifier, name, list of supported file name extensions, options, and synchronous
 /// invoker.
 /// </summary>
 /// <param name="progID">The programmatic identifier (ProgID) of the VBScript engine class.</param>
 /// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
 /// <param name="fileNameExtensions">A semicolon-delimited list of supported file name extensions.</param>
 /// <param name="flags">A value that selects options for the operation.</param>
 /// <param name="syncInvoker">An object that enforces thread affinity for the instance.</param>
 /// <remarks>
 /// The <paramref name="progID"/> argument can be a class identifier (CLSID) in standard
 /// GUID format with braces (e.g., "{F414C260-6AC0-11CF-B6D1-00AA00BBBB58}").
 /// </remarks>
 protected VBScriptEngine(string progID, string name, string fileNameExtensions, WindowsScriptEngineFlags flags, ISyncInvoker syncInvoker)
     : base(progID, name, fileNameExtensions, flags, syncInvoker)
 {
     Execute(MiscHelpers.FormatInvariant("{0} [internal]", GetType().Name), InitScript);
 }