Runtime evaluation: Difference between revisions

→‎{{header|Tcl}}: split up, clarify
m (stop using parentheses in a "programming" way in task description; can make for very poor line breaking)
(→‎{{header|Tcl}}: split up, clarify)
Line 154:
 
=={{header|Tcl}}==
===Simple Evaluation===
Evaluation in the current interpreter:
<lang tcl>set four 4
Line 159 ⟶ 160:
 
set result2 [eval [list expr [list $four + 5]]] ;# list input</lang>
 
===Evaluation in a restricted context===
Tcl handles sandboxing by creating new interpreters. Each interpreter is strongly isolated from all other interpreters except in that the interpreter that creates a sub-interpreter retains management control over that “slave” interpreter. The exact capabilities exposed in the slave are controlled by what commands exist in it; commands in the slave may be aliases for other commands in the master interpreter, which allows for trapping into a more highly authorized context (which can be considered analogous to a system call to an OS kernel).
<lang tcl># Create an interpreter with a default set of restrictions
interp create -safe restrictedContext
 
# Our secret variable
set v "secret"
 
# Allow some guarded access to the secret from the restricted context.
interp alias restrictedContext doubleSecret {} example
proc example {} {
global v
lappend v $v
return [llength $v]
}
 
# Evaluate a script in the restricted context
puts [restrictedContext eval {
append v " has been leaked"
catch {file delete yourCriticalFile.txt} ;# Will be denied!
return "there are [doubleSecret] words in the secret: the magic number is [expr {4 + 5}]"
doubleSecret
}]; # --> there are 2 words in the secret: the magic number is 9
expr {4 + 5}
}]; # --> 9
puts $v; # --> secret secret</lang>
As can be seen, the result of the overall evaluation is the same as the result of the evaluation in the slave.
 
Note that with providing values ''to'' the restricted context, it is normal to do this by providing an alias/trap command in the restricted context to allow the script to pick up the value when it wants it. Although the value could also have been provided by setting a variable in the restricted context, this is fairly unusual in practice. The example above shows how this might be done with the result of the <code>doubleSecret</code> command.
 
===Evaluation within limits===
{{works with|Tcl|8.5}}<br>
ThereEven arestronger protection of the master interpreter is available from Tcl 8.5 onwards through the setting of resource limits availableon whichthe slaves. These allow preventingthe master to prevent the evaluated script from going berserk:
<lang tcl>set i [interp create]
interp limit $i commands -value [expr [$i eval info cmdcount]+20] -granularity 1
Anonymous user