public void ConnectViaDebugChannel(DebugConnectionListener target)
 {
     try
     {
         var result = DebugConnection.Connect(target);
         Client = new RpcClient(result, this);
         RaisePropertyChanged(nameof(Client));
     }
     catch
     {
         Messages.Add($"Failed to connect to debug channel");
     }
 }
示例#2
0
        public void ConnectConnector(DebugConnection connector)
        {
            this.debugProtocol.Connection = connector;
            // If connect was successful, save this configuration to be opened on next launch
            if (this.debugProtocol.Connect())
            {
                XmlSerializer writer = new XmlSerializer(typeof(DebugConnection), new[] { typeof(ExampleProjectConnector) });

                string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "EmbeddedDebugger", "Config", "connection.xml");
                Directory.CreateDirectory(Path.GetDirectoryName(path) ?? throw new InvalidOperationException());
                FileStream file = File.Create(path);

                writer.Serialize(file, this.debugProtocol.Connection);
                file.Close();
            }
        }
示例#3
0
        public DebugConnection FindPreviousConnector()
        {
            DebugConnection returnable = null;
            string          path       = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "EmbeddedDebugger", "Config", "connection.xml");

            if (File.Exists(path))
            {
                try
                {
                    XmlSerializer serializer =
                        new XmlSerializer(typeof(DebugConnection));
                    using (Stream reader = new FileStream(path, FileMode.Open))
                    {
                        // Call the Deserialize method to restore the object's state.
                        returnable = (DebugConnection)serializer.Deserialize(reader);
                    }
                }
                catch (Exception e)
                {
                    Logger.Error(e);
                }
            }
            return(returnable);
        }
示例#4
0
        /// <summary>
        /// Connects to and performs the initial handshake with the remote debugging server, verifying protocol signature and version number,
        /// and returns the opened stream in a state ready to receive further ptvsd commands (e.g. attach).
        /// </summary>
        public static async Task <DebugConnection> ConnectAsync(Uri uri, bool warnAboutAuthenticationErrors, CancellationToken ct)
        {
            var transport = DebuggerTransportFactory.Get(uri);

            if (transport == null)
            {
                throw new ConnectionException(ConnErrorMessages.RemoteInvalidUri);
            }

            Stream stream = null;

            do
            {
                try {
                    stream = transport.Connect(uri, warnAboutAuthenticationErrors);
                } catch (AuthenticationException ex) {
                    if (!warnAboutAuthenticationErrors)
                    {
                        // This should never happen, but if it does, we don't want to keep trying.
                        throw new ConnectionException(ConnErrorMessages.RemoteSslError, ex);
                    }

                    string errText = Strings.RemoteProcessAuthenticationErrorWarning.FormatUI(ex.Message);
                    var    dlgRes  = MessageBox.Show(errText, Strings.ProductTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (dlgRes == DialogResult.Yes)
                    {
                        warnAboutAuthenticationErrors = false;
                    }
                    else
                    {
                        throw new ConnectionException(ConnErrorMessages.RemoteSslError, ex);
                    }
                }
            } while (stream == null);

            var  debugConn = new DebugConnection(stream);
            bool connected = false;

            try {
                string serverDebuggerName            = string.Empty;
                int    serverDebuggerProtocolVersion = 0;
                using (var connectedEvent = new AutoResetEvent(false)) {
                    EventHandler <LDP.RemoteConnectedEvent> eventReceived = (object sender, LDP.RemoteConnectedEvent ea) => {
                        serverDebuggerName            = ea.debuggerName;
                        serverDebuggerProtocolVersion = ea.debuggerProtocolVersion;
                        try {
                            connectedEvent.Set();
                        } catch (ObjectDisposedException) {
                        }
                        debugConn.Authenticated();
                    };

                    // When the server accepts a connection, it sends an event and then waits for a request
                    debugConn.LegacyRemoteConnected += eventReceived;
                    try {
                        debugConn.StartListening();
                        bool received = connectedEvent.WaitOne(ConnectTimeoutMs);
                        if (!received)
                        {
                            throw new ConnectionException(ConnErrorMessages.TimeOut);
                        }
                    } finally {
                        debugConn.LegacyRemoteConnected -= eventReceived;
                    }
                }

                if (serverDebuggerName != DebuggerSignature)
                {
                    throw new ConnectionException(ConnErrorMessages.RemoteUnsupportedServer);
                }

                // If we are talking the same protocol but different version, reply with signature + version before bailing out
                // so that ptvsd has a chance to gracefully close the socket on its side.
                var response = await debugConn.SendRequestAsync(new LDP.RemoteDebuggerAuthenticateRequest()
                {
                    clientSecret            = uri.UserInfo,
                    debuggerName            = DebuggerSignature,
                    debuggerProtocolVersion = DebuggerProtocolVersion,
                }, ct);

                if (serverDebuggerProtocolVersion != DebuggerProtocolVersion)
                {
                    throw new ConnectionException(ConnErrorMessages.RemoteUnsupportedServer);
                }

                if (!response.accepted)
                {
                    throw new ConnectionException(ConnErrorMessages.RemoteSecretMismatch);
                }

                connected = true;
                return(debugConn);
            } catch (IOException ex) {
                throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
            } catch (SocketException ex) {
                throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
            } finally {
                if (!connected)
                {
                    debugConn?.Dispose();
                }
            }
        }
示例#5
0
        public static async Task <PythonRemoteDebugProcess> ConnectAsync(PythonRemoteDebugPort port, TextWriter debugLog, CancellationToken ct)
        {
            PythonRemoteDebugProcess process = null;

            // Connect to the remote debugging server and obtain process information. If any errors occur, display an error dialog, and keep
            // trying for as long as user clicks "Retry".
            while (true)
            {
                DebugConnection     debugConn = null;
                ConnectionException connEx    = null;
                try {
                    // Process information is not sensitive, so ignore any SSL certificate errors, rather than bugging the user with warning dialogs.
                    debugConn = await PythonRemoteProcess.ConnectAsync(port.Uri, false, debugLog, ct);
                } catch (ConnectionException ex) {
                    connEx = ex;
                }

                using (debugConn) {
                    if (debugConn != null)
                    {
                        try {
                            var response = await debugConn.SendRequestAsync(new LDP.RemoteDebuggerInfoRequest(), ct);

                            process = new PythonRemoteDebugProcess(port, response.processId, response.executable, response.user, response.pythonVersion);
                            break;
                        } catch (IOException ex) {
                            connEx = new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
                        } catch (FailedRequestException ex) {
                            connEx = new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
                        }
                    }

                    if (connEx != null)
                    {
                        string errText;
                        switch (connEx.Error)
                        {
                        case ConnErrorMessages.RemoteUnsupportedServer:
                            errText = Strings.RemoteUnsupportedServer_Host.FormatUI(port.Uri);
                            break;

                        case ConnErrorMessages.RemoteSecretMismatch:
                            errText = Strings.RemoteSecretMismatch_Host.FormatUI(new UriBuilder(port.Uri)
                            {
                                UserName = null, Password = null
                            }.Uri);
                            break;

                        case ConnErrorMessages.RemoteSslError:
                            // User has already got a warning dialog and clicked "Cancel" on that, so no further prompts are needed.
                            return(null);

                        default:
                        {
                            // Azure uses HTTP 503 (Service Unavailable) to indicate that websocket connections are not supported. Show a special error message for that.
                            var wsEx = connEx.InnerException as WebSocketException;
                            if (wsEx != null)
                            {
                                var webEx = wsEx.InnerException as WebException;
                                if (webEx != null)
                                {
                                    var httpResponse = webEx.Response as HttpWebResponse;
                                    if (httpResponse != null && httpResponse.StatusCode == HttpStatusCode.ServiceUnavailable)
                                    {
                                        errText = Strings.RemoteAzureServiceUnavailable_Host.FormatUI(port.Uri);
                                        break;
                                    }
                                }
                            }

                            errText = Strings.RemoteServiceUnavailable_Host.FormatUI(port.Uri);
                            for (var ex = connEx.InnerException; ex != null; ex = ex.InnerException)
                            {
                                if (ex.InnerException == null)
                                {
                                    errText += "\r\n\r\n{0}\r\n{1}".FormatUI(Strings.AdditionalInformation, ex.Message);
                                }
                            }
                            break;
                        }
                        }

                        DialogResult dlgRes = MessageBox.Show(errText, Strings.ProductTitle, MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                        if (dlgRes != DialogResult.Retry)
                        {
                            break;
                        }
                    }
                }
            }

            return(process);
        }
 /// <summary>
 /// Method used to set the setting for a connection
 /// </summary>
 /// <param name="connection">The connection for which the settings are set</param>
 /// <param name="settings">The settings for the connection</param>
 public void SetConnectorSettings(DebugConnection connection, List <ConnectionSetting> settings)
 {
     connection.SetConnectionSettings(settings);
 }
 /// <summary>
 /// Ask all nodes if there is anyone there
 /// </summary>
 public void SearchForNodes(DebugConnection connection)
 {
     // TODO NEEDS REMOVAL
     connection.Nodes = this.core.Nodes;
     connection.SearchForNodes();
 }
示例#8
0
        async static Task Run(string[] args)
        {
            RegisterCommand("help", Help, "help", "Shows the list of available commands (this).");
            RegisterCommand("disconnect", Disconnect, "disconnect", "Disconnects from the debug server.");
            RegisterCommand("break", Break, "break", "Suspends execution before the next OSI instruction to be executed.");
            RegisterCommand("step", Step, "step [over|in|out]", "Executes the next OSI instruction. (over: until the next instruction in this subroutine, out: until the next instruction after this subroutine returns; default is over)");
            RegisterCommand("resume", Resume, "resume", "Resumes OSI execution when the debug server is suspended.");
            RegisterCommand("stack", Stack, "stack [values|trace|frames]", "Shows the contents of the stack of the OSI virtual machine (values: just the OSI values on the stack, trace: just the call stack, frames: the full detail of the frames of the stack; default is values)");

            string hostname = "localhost";
            int    port     = 10001;

            Console.Write("Hostname (Blank for '" + hostname + "') > ");
            string hostnameInput = Console.ReadLine().Trim();

            if (hostnameInput.Length > 0)
            {
                hostname = hostnameInput;
            }
            Console.Write("Remote port (Blank for " + port + ") > ");
            string portInput = Console.ReadLine().Trim();

            if (portInput.Length > 0)
            {
                if (!Int32.TryParse(portInput, out port))
                {
                    Console.WriteLine("Invalid port. Using " + port + ".");
                }
            }

            Console.Clear();
            //Console.CursorTop = 1;

            Connection = new DebugConnection(System.Threading.SynchronizationContext.Current, hostname, port);
            BetterWriteLine("Connecting to " + hostname + ":" + port + "...");
            await Connection.Connect();

            if (!Connection.IsConnected)
            {
                BetterWriteLine("Connection failed.");
            }
            else
            {
                BetterWriteLine("Connected!");
                bool exit = false;
                Connection.ServerDisconnect += (_, __) =>
                {
                    BetterWriteLine("Disconnected by server.");
                    exit = true;
                    //throw new Exception(); // Hack to interrupt the ReadLine() method
                };
                Connection.ServerDebugOutput += (_, output) =>
                {
                    BetterWrite(output, "[VM]: ");
                };
                Connection.ServerException += (_, output) =>
                {
                    BetterWrite(output, "[VM Error]: ");
                };
                Connection.VMState.ExecutionStateChanged += (_, __) =>
                {
                    int oldrow = Console.CursorTop;
                    int oldcol = Console.CursorLeft;
                    Console.CursorLeft = Console.WindowWidth - 12;
                    Console.CursorTop  = 0;
                    if (Connection.VMState.ExecutionState == VMState.VMExecutionState.Unknown)
                    {
                        Console.Write("?");
                        Console.Write("           ");
                    }
                    else if (Connection.VMState.ExecutionState == VMState.VMExecutionState.NativeCode)
                    {
                        Console.Write("N");
                        Console.Write("           ");
                    }
                    else if (Connection.VMState.ExecutionState == VMState.VMExecutionState.OSIRunning)
                    {
                        Console.Write("R");
                        Console.Write("           ");
                    }
                    else if (Connection.VMState.ExecutionState == VMState.VMExecutionState.OSISuspended)
                    {
                        Console.Write("P");
                        Console.Write(":0x" + Connection.VMState.InstructionPointer.ToString("X8"));
                    }
                    Console.CursorLeft = oldcol;
                    Console.CursorTop  = oldrow;
                };

                while (!exit)
                {
                    string prologue = hostname + ":" + port + " > ";
                    Console.CursorTop  = 0;
                    Console.CursorLeft = 0;
                    Console.Write(prologue.PadRight(Console.BufferWidth - 12));
                    //Console.CursorTop = 0;
                    Console.CursorLeft = prologue.Length;
                    string command = Console.ReadLine();

                    /*Console.Write(hostname + ":" + port + " > ");
                    *  Console.CursorTop = 0;
                    *  Console.CursorLeft = 0;
                    *
                    *  Console.CursorTop = 0;
                    *  Console.CursorLeft = 0;
                    *  Console.Write(hostname + ":" + port + " > ");*/

                    string[] parts = command.Split(' ');
                    if (parts.Length > 0)
                    {
                        BetterWriteLine(" > " + command);
                        if (Commands.ContainsKey(parts[0]))
                        {
                            exit = Commands[parts[0]].Run(parts);
                        }
                        else
                        {
                            Help(new string[] { });
                        }
                    }
                }
            }
            BetterWriteLine("Press any key to exit.");
            Console.ReadKey();
        }
示例#9
0
 public void SetConnectorSettings(DebugConnection connector, List <ConnectionSetting> settings)
 {
     this.debugProtocol.SetConnectorSettings(connector, settings);
 }
示例#10
0
 public void DisconnectConnector(DebugConnection connector)
 {
     this.debugProtocol.Disconnect();
 }