Remote debugging via socket

Richard Suchenwirth 2007-10-23 - Here's a simple experiment on how to connect two Tcl processes so that one (call it "debugger") can inspect and control the other ("debuggee"). Both must have an event loop running. As this goes over a socket connection, the two processes could be on different hosts and operating systems (though I've so far tested only the localhost variety). Use at your own risk, of course... :^)

The "debuggee" has in my experiments the following code:

 proc remo_server {{port 3456}} {
    set sock [socket -server remo_accept $port]
 }
 proc remo_accept {socket adr port} {
    fileevent $socket readable [list remo_go $socket]
 }
 proc remo_go {sock} {
    gets $sock line
    catch {uplevel \#0 $line} res
    puts $sock $res
    if [catch {flush $sock}] {close $sock}
 }
 remo_server

The "debugger" in this version (remo.tcl) runs only on Windows in a wish, as it needs a console, but you could modify it to avoid these restrictions:

 #!/usr/bin/env wish
 console show
 wm withdraw .
 set remo [socket localhost 3456]
 fileevent $remo readable "puts \[gets $remo\]"
 proc r args {puts $::remo [join $args]; flush $::remo}
 puts "remote connection ready - use r to talk"

Now from remo you can call any Tcl command in the "debuggee", where it is executed in global scope, so in particular you can inspect (and modify) global variables. But you could also redefine procs on the fly, or whatever tickles your fancy... Examples from a remo session, showing that the two have different pids, how errors are reported, and that quoting is different from normal (needs more work):

 (suchrich) 10 % pid
 600
 (suchrich) 11 % r pid
 2556
 (suchrich) 12 % r wm title . "Under remote control"
 wrong # args: should be "wm title window ?newTitle?"
 (suchrich) 13 % r wm title . {"Under remote control"}

LV Maybe this could be crossed with tkinspect, which has a lot of neat functionality in it.

AM Ed Hume's inspect tool does very similar things. EF and then there is Tkcon Remote Access over TCP Sockets and tkcon (writing this completion, so that readers gets pointers to other solutions to the problem).

- RS I have no doubt that other tools will have more powerful features - my interest was to demonstrate a minimal working solution, for educational purposes :^)