Create a TCL interpreter that only supports the commands that I supply

Say I defined proc f1 proc f2 and proc f3. Now I want to create a TCL interpreter, send the code proc f1 proc f2 and proc f3 to this interpreter and restrict all commands other than f1, f2 and f3 inside this interpreter. How can i do this?

EDIT:

If another f1, f2, and f3 command is called in the interpreter, I created an error message and execute the code received in the interpreter (suppose that this other code, which is received in the same interpreter, after searching for the code with f1, f2 and f3 procs) should be stopped.

+5
source share
2 answers

, - .

, f1, f2 f3 , -, Tcl, , - .

# First define f1-f3 in whatever way you want

# Now make the context; we'll use a safe interpreter for good measure...
set slave [interp create -safe]

# Scrub namespaces, then global vars, then commands
foreach ns [$slave eval namespace children ::] {
    $slave eval namespace delete $ns
}
foreach v [$slave eval info vars] {
    $slave eval unset $v
}
foreach cmd [$slave eval info commands] {
    # Note: we're hiding, not completely removing
    $slave hide $cmd
}

# Make the aliases for the things we want
foreach cmd {f1 f2 f3} {
    $slave alias $cmd $cmd
}

# And evaluate the untrusted script in it
catch {$slave invokehidden source $theScript}

# Finally, kill the untrusted interpreter
interp delete $slave
+9

: . f1, f2 f3, , Control + C exit, :

proc f1 {args} { puts "f1:$args" }
proc f2 {args} { puts "f2:$args" }
proc f3 {args} { puts "f3:$args" }

while 1 {
    puts -nonewline ">"
    flush stdout
    gets stdin line
    set firstToken [lindex $line 0]
    if {[lsearch {f1 f2 f3 exit} $firstToken] != -1} {
        eval $line
    }
}

:

  • Eval
  • , tclreadline

, .

+2

All Articles