1interp(n) Tcl Built-In Commands interp(n)
2
3
4
5______________________________________________________________________________
6
8 interp - Create and manipulate Tcl interpreters
9
11 interp subcommand ?arg arg ...?
12______________________________________________________________________________
13
15 This command makes it possible to create one or more new Tcl inter‐
16 preters that co-exist with the creating interpreter in the same appli‐
17 cation. The creating interpreter is called the parent and the new in‐
18 terpreter is called a child. A parent can create any number of chil‐
19 dren, and each child can itself create additional children for which it
20 is parent, resulting in a hierarchy of interpreters.
21
22 Each interpreter is independent from the others: it has its own name
23 space for commands, procedures, and global variables. A parent inter‐
24 preter may create connections between its children and itself using a
25 mechanism called an alias. An alias is a command in a child inter‐
26 preter which, when invoked, causes a command to be invoked in its par‐
27 ent interpreter or in another child interpreter. The only other con‐
28 nections between interpreters are through environment variables (the
29 env variable), which are normally shared among all interpreters in the
30 application, and by resource limit exceeded callbacks. Note that the
31 name space for files (such as the names returned by the open command)
32 is no longer shared between interpreters. Explicit commands are pro‐
33 vided to share files and to transfer references to open files from one
34 interpreter to another.
35
36 The interp command also provides support for safe interpreters. A safe
37 interpreter is a child whose functions have been greatly restricted, so
38 that it is safe to execute untrusted scripts without fear of them dam‐
39 aging other interpreters or the application's environment. For example,
40 all IO channel creation commands and subprocess creation commands are
41 made inaccessible to safe interpreters. See SAFE INTERPRETERS below
42 for more information on what features are present in a safe inter‐
43 preter. The dangerous functionality is not removed from the safe in‐
44 terpreter; instead, it is hidden, so that only trusted interpreters can
45 obtain access to it. For a detailed explanation of hidden commands, see
46 HIDDEN COMMANDS, below. The alias mechanism can be used for protected
47 communication (analogous to a kernel call) between a child interpreter
48 and its parent. See ALIAS INVOCATION, below, for more details on how
49 the alias mechanism works.
50
51 A qualified interpreter name is a proper Tcl list containing a subset
52 of its ancestors in the interpreter hierarchy, terminated by the string
53 naming the interpreter in its immediate parent. Interpreter names are
54 relative to the interpreter in which they are used. For example, if “a”
55 is a child of the current interpreter and it has a child “a1”, which in
56 turn has a child “a11”, the qualified name of “a11” in “a” is the list
57 “a1 a11”.
58
59 The interp command, described below, accepts qualified interpreter
60 names as arguments; the interpreter in which the command is being eval‐
61 uated can always be referred to as {} (the empty list or string). Note
62 that it is impossible to refer to a parent (ancestor) interpreter by
63 name in a child interpreter except through aliases. Also, there is no
64 global name by which one can refer to the first interpreter created in
65 an application. Both restrictions are motivated by safety concerns.
66
68 The interp command is used to create, delete, and manipulate child in‐
69 terpreters, and to share or transfer channels between interpreters. It
70 can have any of several forms, depending on the subcommand argument:
71
72 interp alias srcPath srcToken
73 Returns a Tcl list whose elements are the targetCmd and args as‐
74 sociated with the alias represented by srcToken (this is the
75 value returned when the alias was created; it is possible that
76 the name of the source command in the child is different from
77 srcToken).
78
79 interp alias srcPath srcToken {}
80 Deletes the alias for srcToken in the child interpreter identi‐
81 fied by srcPath. srcToken refers to the value returned when the
82 alias was created; if the source command has been renamed, the
83 renamed command will be deleted.
84
85 interp alias srcPath srcCmd targetPath targetCmd ?arg arg ...?
86 This command creates an alias between one child and another (see
87 the alias child command below for creating aliases between a
88 child and its parent). In this command, either of the child in‐
89 terpreters may be anywhere in the hierarchy of interpreters un‐
90 der the interpreter invoking the command. SrcPath and srcCmd
91 identify the source of the alias. SrcPath is a Tcl list whose
92 elements select a particular interpreter. For example, “a b”
93 identifies an interpreter “b”, which is a child of interpreter
94 “a”, which is a child of the invoking interpreter. An empty
95 list specifies the interpreter invoking the command. srcCmd
96 gives the name of a new command, which will be created in the
97 source interpreter. TargetPath and targetCmd specify a target
98 interpreter and command, and the arg arguments, if any, specify
99 additional arguments to targetCmd which are prepended to any ar‐
100 guments specified in the invocation of srcCmd. TargetCmd may be
101 undefined at the time of this call, or it may already exist; it
102 is not created by this command. The alias arranges for the
103 given target command to be invoked in the target interpreter
104 whenever the given source command is invoked in the source in‐
105 terpreter. See ALIAS INVOCATION below for more details. The
106 command returns a token that uniquely identifies the command
107 created srcCmd, even if the command is renamed afterwards. The
108 token may but does not have to be equal to srcCmd.
109
110 interp aliases ?path?
111 This command returns a Tcl list of the tokens of all the source
112 commands for aliases defined in the interpreter identified by
113 path. The tokens correspond to the values returned when the
114 aliases were created (which may not be the same as the current
115 names of the commands).
116
117 interp bgerror path ?cmdPrefix?
118 This command either gets or sets the current background excep‐
119 tion handler for the interpreter identified by path. If cmdPre‐
120 fix is absent, the current background exception handler is re‐
121 turned, and if it is present, it is a list of words (of minimum
122 length one) that describes what to set the interpreter's back‐
123 ground exception handler to. See the BACKGROUND EXCEPTION HAN‐
124 DLING section for more details.
125
126 interp cancel ?-unwind? ?--? ?path? ?result?
127 Cancels the script being evaluated in the interpreter identified │
128 by path. Without the -unwind switch the evaluation stack for the │
129 interpreter is unwound until an enclosing catch command is found │
130 or there are no further invocations of the interpreter left on │
131 the call stack. With the -unwind switch the evaluation stack for │
132 the interpreter is unwound without regard to any intervening │
133 catch command until there are no further invocations of the in‐ │
134 terpreter left on the call stack. The -- switch can be used to │
135 mark the end of switches; it may be needed if path is an unusual │
136 value such as -safe. If result is present, it will be used as │
137 the error message string; otherwise, a default error message │
138 string will be used.
139
140 interp create ?-safe? ?--? ?path?
141 Creates a child interpreter identified by path and a new com‐
142 mand, called a child command. The name of the child command is
143 the last component of path. The new child interpreter and the
144 child command are created in the interpreter identified by the
145 path obtained by removing the last component from path. For ex‐
146 ample, if path is a b c then a new child interpreter and child
147 command named c are created in the interpreter identified by the
148 path a b. The child command may be used to manipulate the new
149 interpreter as described below. If path is omitted, Tcl creates
150 a unique name of the form interpx, where x is an integer, and
151 uses it for the interpreter and the child command. If the -safe
152 switch is specified (or if the parent interpreter is a safe in‐
153 terpreter), the new child interpreter will be created as a safe
154 interpreter with limited functionality; otherwise the child will
155 include the full set of Tcl built-in commands and variables. The
156 -- switch can be used to mark the end of switches; it may be
157 needed if path is an unusual value such as -safe. The result of
158 the command is the name of the new interpreter. The name of a
159 child interpreter must be unique among all the children for its
160 parent; an error occurs if a child interpreter by the given
161 name already exists in this parent. The initial recursion limit
162 of the child interpreter is set to the current recursion limit
163 of its parent interpreter.
164
165 interp debug path ?-frame ?bool??
166 Controls whether frame-level stack information is captured in
167 the child interpreter identified by path. If no arguments are
168 given, option and current setting are returned. If -frame is
169 given, the debug setting is set to the given boolean if provided
170 and the current setting is returned. This only affects the out‐
171 put of info frame, in that exact frame-level information for
172 command invocation at the bytecode level is only captured with
173 this setting on.
174
175 For example, with code like
176
177 proc mycontrol {... script} {
178 ...
179 uplevel 1 $script
180 ...
181 }
182
183 proc dosomething {...} {
184 ...
185 mycontrol {
186 somecode
187 }
188 }
189
190 the standard setting will provide a relative line number for the
191 command somecode and the relevant frame will be of type eval.
192 With frame-debug active on the other hand the tracking extends
193 so far that the system will be able to determine the file and
194 absolute line number of this command, and return a frame of type
195 source. This more exact information is paid for with slower exe‐
196 cution of all commands.
197
198 Note that once it is on, this flag cannot be switched back off:
199 such attempts are silently ignored. This is needed to maintain
200 the consistency of the underlying interpreter's state.
201
202 interp delete ?path ...?
203 Deletes zero or more interpreters given by the optional path ar‐
204 guments, and for each interpreter, it also deletes its children.
205 The command also deletes the child command for each interpreter
206 deleted. For each path argument, if no interpreter by that name
207 exists, the command raises an error.
208
209 interp eval path arg ?arg ...?
210 This command concatenates all of the arg arguments in the same
211 fashion as the concat command, then evaluates the resulting
212 string as a Tcl script in the child interpreter identified by
213 path. The result of this evaluation (including all return op‐
214 tions, such as -errorinfo and -errorcode information, if an er‐
215 ror occurs) is returned to the invoking interpreter. Note that
216 the script will be executed in the current context stack frame
217 of the path interpreter; this is so that the implementations (in
218 a parent interpreter) of aliases in a child interpreter can exe‐
219 cute scripts in the child that find out information about the
220 child's current state and stack frame.
221
222 interp exists path
223 Returns 1 if a child interpreter by the specified path exists in
224 this parent, 0 otherwise. If path is omitted, the invoking in‐
225 terpreter is used.
226
227 interp expose path hiddenName ?exposedCmdName?
228 Makes the hidden command hiddenName exposed, eventually bringing
229 it back under a new exposedCmdName name (this name is currently
230 accepted only if it is a valid global name space name without
231 any ::), in the interpreter denoted by path. If an exposed com‐
232 mand with the targeted name already exists, this command fails.
233 Hidden commands are explained in more detail in HIDDEN COMMANDS,
234 below.
235
236 interp hide path exposedCmdName ?hiddenCmdName?
237 Makes the exposed command exposedCmdName hidden, renaming it to
238 the hidden command hiddenCmdName, or keeping the same name if
239 hiddenCmdName is not given, in the interpreter denoted by path.
240 If a hidden command with the targeted name already exists, this
241 command fails. Currently both exposedCmdName and hiddenCmdName
242 can not contain namespace qualifiers, or an error is raised.
243 Commands to be hidden by interp hide are looked up in the global
244 namespace even if the current namespace is not the global one.
245 This prevents children from fooling a parent interpreter into
246 hiding the wrong command, by making the current namespace be
247 different from the global one. Hidden commands are explained in
248 more detail in HIDDEN COMMANDS, below.
249
250 interp hidden path
251 Returns a list of the names of all hidden commands in the inter‐
252 preter identified by path.
253
254 interp invokehidden path ?-option ...? hiddenCmdName ?arg ...?
255 Invokes the hidden command hiddenCmdName with the arguments sup‐
256 plied in the interpreter denoted by path. No substitutions or
257 evaluation are applied to the arguments. Three -options are sup‐
258 ported, all of which start with -: -namespace (which takes a
259 single argument afterwards, nsName), -global, and --. If the
260 -namespace flag is present, the hidden command is invoked in the
261 namespace called nsName in the target interpreter. If the
262 -global flag is present, the hidden command is invoked at the
263 global level in the target interpreter; otherwise it is invoked
264 at the current call frame and can access local variables in that
265 and outer call frames. The -- flag allows the hiddenCmdName ar‐
266 gument to start with a “-” character, and is otherwise unneces‐
267 sary. If both the -namespace and -global flags are present, the
268 -namespace flag is ignored. Note that the hidden command will
269 be executed (by default) in the current context stack frame of
270 the path interpreter. Hidden commands are explained in more de‐
271 tail in HIDDEN COMMANDS, below.
272
273 interp issafe ?path?
274 Returns 1 if the interpreter identified by the specified path is
275 safe, 0 otherwise.
276
277 interp limit path limitType ?-option? ?value ...?
278 Sets up, manipulates and queries the configuration of the re‐
279 source limit limitType for the interpreter denoted by path. If
280 no -option is specified, return the current configuration of the
281 limit. If -option is the sole argument, return the value of
282 that option. Otherwise, a list of -option/value argument pairs
283 must supplied. See RESOURCE LIMITS below for a more detailed ex‐
284 planation of what limits and options are supported.
285
286 interp marktrusted path
287 Marks the interpreter identified by path as trusted. Does not
288 expose the hidden commands. This command can only be invoked
289 from a trusted interpreter. The command has no effect if the
290 interpreter identified by path is already trusted.
291
292 interp recursionlimit path ?newlimit?
293 Returns the maximum allowable nesting depth for the interpreter
294 specified by path. If newlimit is specified, the interpreter
295 recursion limit will be set so that nesting of more than
296 newlimit calls to Tcl_Eval and related procedures in that inter‐
297 preter will return an error. The newlimit value is also re‐
298 turned. The newlimit value must be a positive integer between 1
299 and the maximum value of a non-long integer on the platform.
300
301 The command sets the maximum size of the Tcl call stack only. It
302 cannot by itself prevent stack overflows on the C stack being
303 used by the application. If your machine has a limit on the size
304 of the C stack, you may get stack overflows before reaching the
305 limit set by the command. If this happens, see if there is a
306 mechanism in your system for increasing the maximum size of the
307 C stack.
308
309 interp share srcPath channelId destPath
310 Causes the IO channel identified by channelId to become shared
311 between the interpreter identified by srcPath and the inter‐
312 preter identified by destPath. Both interpreters have the same
313 permissions on the IO channel. Both interpreters must close it
314 to close the underlying IO channel; IO channels accessible in an
315 interpreter are automatically closed when an interpreter is de‐
316 stroyed.
317
318 interp slaves ?path?
319 Returns a Tcl list of the names of all the child interpreters
320 associated with the interpreter identified by path. If path is
321 omitted, the invoking interpreter is used. │
322
323 interp children ?path? │
324 Synonym for . interp slaves ?path?
325
326 interp target path alias
327 Returns a Tcl list describing the target interpreter for an
328 alias. The alias is specified with an interpreter path and
329 source command name, just as in interp alias above. The name of
330 the target interpreter is returned as an interpreter path, rela‐
331 tive to the invoking interpreter. If the target interpreter for
332 the alias is the invoking interpreter then an empty list is re‐
333 turned. If the target interpreter for the alias is not the in‐
334 voking interpreter or one of its descendants then an error is
335 generated. The target command does not have to be defined at
336 the time of this invocation.
337
338 interp transfer srcPath channelId destPath
339 Causes the IO channel identified by channelId to become avail‐
340 able in the interpreter identified by destPath and unavailable
341 in the interpreter identified by srcPath.
342
344 For each child interpreter created with the interp command, a new Tcl
345 command is created in the parent interpreter with the same name as the
346 new interpreter. This command may be used to invoke various operations
347 on the interpreter. It has the following general form:
348
349 child command ?arg arg ...?
350
351 child is the name of the interpreter, and command and the args deter‐
352 mine the exact behavior of the command. The valid forms of this com‐
353 mand are:
354
355 child aliases
356 Returns a Tcl list whose elements are the tokens of all the
357 aliases in child. The tokens correspond to the values returned
358 when the aliases were created (which may not be the same as the
359 current names of the commands).
360
361 child alias srcToken
362 Returns a Tcl list whose elements are the targetCmd and args as‐
363 sociated with the alias represented by srcToken (this is the
364 value returned when the alias was created; it is possible that
365 the actual source command in the child is different from srcTo‐
366 ken).
367
368 child alias srcToken {}
369 Deletes the alias for srcToken in the child interpreter. srcTo‐
370 ken refers to the value returned when the alias was created; if
371 the source command has been renamed, the renamed command will be
372 deleted.
373
374 child alias srcCmd targetCmd ?arg ..?
375 Creates an alias such that whenever srcCmd is invoked in child,
376 targetCmd is invoked in the parent. The arg arguments will be
377 passed to targetCmd as additional arguments, prepended before
378 any arguments passed in the invocation of srcCmd. See ALIAS IN‐
379 VOCATION below for details. The command returns a token that
380 uniquely identifies the command created srcCmd, even if the com‐
381 mand is renamed afterwards. The token may but does not have to
382 be equal to srcCmd.
383
384 child bgerror ?cmdPrefix?
385 This command either gets or sets the current background excep‐
386 tion handler for the child interpreter. If cmdPrefix is absent,
387 the current background exception handler is returned, and if it
388 is present, it is a list of words (of minimum length one) that
389 describes what to set the interpreter's background exception
390 handler to. See the BACKGROUND EXCEPTION HANDLING section for
391 more details.
392
393 child eval arg ?arg ..?
394 This command concatenates all of the arg arguments in the same
395 fashion as the concat command, then evaluates the resulting
396 string as a Tcl script in child. The result of this evaluation
397 (including all return options, such as -errorinfo and -errorcode
398 information, if an error occurs) is returned to the invoking in‐
399 terpreter. Note that the script will be executed in the current
400 context stack frame of child; this is so that the implementa‐
401 tions (in a parent interpreter) of aliases in a child inter‐
402 preter can execute scripts in the child that find out informa‐
403 tion about the child's current state and stack frame.
404
405 child expose hiddenName ?exposedCmdName?
406 This command exposes the hidden command hiddenName, eventually
407 bringing it back under a new exposedCmdName name (this name is
408 currently accepted only if it is a valid global name space name
409 without any ::), in child. If an exposed command with the tar‐
410 geted name already exists, this command fails. For more details
411 on hidden commands, see HIDDEN COMMANDS, below.
412
413 child hide exposedCmdName ?hiddenCmdName?
414 This command hides the exposed command exposedCmdName, renaming
415 it to the hidden command hiddenCmdName, or keeping the same name
416 if the argument is not given, in the child interpreter. If a
417 hidden command with the targeted name already exists, this com‐
418 mand fails. Currently both exposedCmdName and hiddenCmdName can
419 not contain namespace qualifiers, or an error is raised. Com‐
420 mands to be hidden are looked up in the global namespace even if
421 the current namespace is not the global one. This prevents chil‐
422 dren from fooling a parent interpreter into hiding the wrong
423 command, by making the current namespace be different from the
424 global one. For more details on hidden commands, see HIDDEN
425 COMMANDS, below.
426
427 child hidden
428 Returns a list of the names of all hidden commands in child.
429
430 child invokehidden ?-option ...? hiddenName ?arg ..?
431 This command invokes the hidden command hiddenName with the sup‐
432 plied arguments, in child. No substitutions or evaluations are
433 applied to the arguments. Three -options are supported, all of
434 which start with -: -namespace (which takes a single argument
435 afterwards, nsName), -global, and --. If the -namespace flag is
436 given, the hidden command is invoked in the specified namespace
437 in the child. If the -global flag is given, the command is in‐
438 voked at the global level in the child; otherwise it is invoked
439 at the current call frame and can access local variables in that
440 or outer call frames. The -- flag allows the hiddenCmdName ar‐
441 gument to start with a “-” character, and is otherwise unneces‐
442 sary. If both the -namespace and -global flags are given, the
443 -namespace flag is ignored. Note that the hidden command will
444 be executed (by default) in the current context stack frame of
445 child. For more details on hidden commands, see HIDDEN COM‐
446 MANDS, below.
447
448 child issafe
449 Returns 1 if the child interpreter is safe, 0 otherwise.
450
451 child limit limitType ?-option? ?value ...?
452 Sets up, manipulates and queries the configuration of the re‐
453 source limit limitType for the child interpreter. If no -option
454 is specified, return the current configuration of the limit. If
455 -option is the sole argument, return the value of that option.
456 Otherwise, a list of -option/value argument pairs must supplied.
457 See RESOURCE LIMITS below for a more detailed explanation of
458 what limits and options are supported.
459
460 child marktrusted
461 Marks the child interpreter as trusted. Can only be invoked by a
462 trusted interpreter. This command does not expose any hidden
463 commands in the child interpreter. The command has no effect if
464 the child is already trusted.
465
466 child recursionlimit ?newlimit?
467 Returns the maximum allowable nesting depth for the child inter‐
468 preter. If newlimit is specified, the recursion limit in child
469 will be set so that nesting of more than newlimit calls to
470 Tcl_Eval() and related procedures in child will return an error.
471 The newlimit value is also returned. The newlimit value must be
472 a positive integer between 1 and the maximum value of a non-long
473 integer on the platform.
474
475 The command sets the maximum size of the Tcl call stack only. It
476 cannot by itself prevent stack overflows on the C stack being
477 used by the application. If your machine has a limit on the size
478 of the C stack, you may get stack overflows before reaching the
479 limit set by the command. If this happens, see if there is a
480 mechanism in your system for increasing the maximum size of the
481 C stack.
482
484 A safe interpreter is one with restricted functionality, so that is
485 safe to execute an arbitrary script from your worst enemy without fear
486 of that script damaging the enclosing application or the rest of your
487 computing environment. In order to make an interpreter safe, certain
488 commands and variables are removed from the interpreter. For example,
489 commands to create files on disk are removed, and the exec command is
490 removed, since it could be used to cause damage through subprocesses.
491 Limited access to these facilities can be provided, by creating aliases
492 to the parent interpreter which check their arguments carefully and
493 provide restricted access to a safe subset of facilities. For example,
494 file creation might be allowed in a particular subdirectory and subpro‐
495 cess invocation might be allowed for a carefully selected and fixed set
496 of programs.
497
498 A safe interpreter is created by specifying the -safe switch to the in‐
499 terp create command. Furthermore, any child created by a safe inter‐
500 preter will also be safe.
501
502 A safe interpreter is created with exactly the following set of built-
503 in commands:
504
505 after append apply array
506 binary break catch chan
507 clock close concat continue
508 dict eof error eval
509 expr fblocked fcopy fileevent
510 flush for foreach format
511 gets global if incr
512 info interp join lappend
513 lassign lindex linsert list
514 llength lrange lrepeat lreplace
515 lsearch lset lsort namespace
516 package pid proc puts
517 read regexp regsub rename
518 return scan seek set
519 split string subst switch
520 tell time trace unset
521 update uplevel upvar variable
522 vwait while
523
524 The following commands are hidden by interp create when it creates a
525 safe interpreter:
526
527 cd encoding exec exit
528 fconfigure file glob load
529 open pwd socket source
530 unload
531
532 These commands can be recreated later as Tcl procedures or aliases, or
533 re-exposed by interp expose.
534
535 The following commands from Tcl's library of support procedures are not
536 present in a safe interpreter:
537
538 auto_exec_ok auto_import auto_load
539 auto_load_index auto_qualify unknown
540
541 Note in particular that safe interpreters have no default unknown com‐
542 mand, so Tcl's default autoloading facilities are not available. Au‐
543 toload access to Tcl's commands that are normally autoloaded:
544
545 auto_mkindex auto_mkindex_old
546 auto_reset history
547 parray pkg_mkIndex
548 ::pkg::create ::safe::interpAddToAccessPath
549 ::safe::interpCreate ::safe::interpConfigure
550 ::safe::interpDelete ::safe::interpFindInAccessPath
551 ::safe::interpInit ::safe::setLogCmd
552 tcl_endOfWord tcl_findLibrary
553 tcl_startOfNextWord tcl_startOfPreviousWord
554 tcl_wordBreakAfter tcl_wordBreakBefore
555
556 can only be provided by explicit definition of an unknown command in
557 the safe interpreter. This will involve exposing the source command.
558 This is most easily accomplished by creating the safe interpreter with
559 Tcl's Safe-Tcl mechanism. Safe-Tcl provides safe versions of source,
560 load, and other Tcl commands needed to support autoloading of commands
561 and the loading of packages.
562
563 In addition, the env variable is not present in a safe interpreter, so
564 it cannot share environment variables with other interpreters. The env
565 variable poses a security risk, because users can store sensitive in‐
566 formation in an environment variable. For example, the PGP manual rec‐
567 ommends storing the PGP private key protection password in the environ‐
568 ment variable PGPPASS. Making this variable available to untrusted code
569 executing in a safe interpreter would incur a security risk.
570
571 If extensions are loaded into a safe interpreter, they may also re‐
572 strict their own functionality to eliminate unsafe commands. For a dis‐
573 cussion of management of extensions for safety see the manual entries
574 for Safe-Tcl and the load Tcl command.
575
576 A safe interpreter may not alter the recursion limit of any inter‐
577 preter, including itself.
578
580 The alias mechanism has been carefully designed so that it can be used
581 safely in an untrusted script which is being executed in a safe inter‐
582 preter even if the target of the alias is not a safe interpreter. The
583 most important thing in guaranteeing safety is to ensure that informa‐
584 tion passed from the child to the parent is never evaluated or substi‐
585 tuted in the parent; if this were to occur, it would enable an evil
586 script in the child to invoke arbitrary functions in the parent, which
587 would compromise security.
588
589 When the source for an alias is invoked in the child interpreter, the
590 usual Tcl substitutions are performed when parsing that command. These
591 substitutions are carried out in the source interpreter just as they
592 would be for any other command invoked in that interpreter. The com‐
593 mand procedure for the source command takes its arguments and merges
594 them with the targetCmd and args for the alias to create a new array of
595 arguments. If the words of srcCmd were “srcCmd arg1 arg2 ... argN”,
596 the new set of words will be “targetCmd arg arg ... arg arg1 arg2 ...
597 argN”, where targetCmd and args are the values supplied when the alias
598 was created. TargetCmd is then used to locate a command procedure in
599 the target interpreter, and that command procedure is invoked with the
600 new set of arguments. An error occurs if there is no command named
601 targetCmd in the target interpreter. No additional substitutions are
602 performed on the words: the target command procedure is invoked di‐
603 rectly, without going through the normal Tcl evaluation mechanism.
604 Substitutions are thus performed on each word exactly once: targetCmd
605 and args were substituted when parsing the command that created the
606 alias, and arg1 - argN are substituted when the alias's source command
607 is parsed in the source interpreter.
608
609 When writing the targetCmds for aliases in safe interpreters, it is
610 very important that the arguments to that command never be evaluated or
611 substituted, since this would provide an escape mechanism whereby the
612 child interpreter could execute arbitrary code in the parent. This in
613 turn would compromise the security of the system.
614
616 Safe interpreters greatly restrict the functionality available to Tcl
617 programs executing within them. Allowing the untrusted Tcl program to
618 have direct access to this functionality is unsafe, because it can be
619 used for a variety of attacks on the environment. However, there are
620 times when there is a legitimate need to use the dangerous functional‐
621 ity in the context of the safe interpreter. For example, sometimes a
622 program must be sourced into the interpreter. Another example is Tk,
623 where windows are bound to the hierarchy of windows for a specific in‐
624 terpreter; some potentially dangerous functions, e.g. window manage‐
625 ment, must be performed on these windows within the interpreter con‐
626 text.
627
628 The interp command provides a solution to this problem in the form of
629 hidden commands. Instead of removing the dangerous commands entirely
630 from a safe interpreter, these commands are hidden so they become un‐
631 available to Tcl scripts executing in the interpreter. However, such
632 hidden commands can be invoked by any trusted ancestor of the safe in‐
633 terpreter, in the context of the safe interpreter, using interp invoke.
634 Hidden commands and exposed commands reside in separate name spaces. It
635 is possible to define a hidden command and an exposed command by the
636 same name within one interpreter.
637
638 Hidden commands in a child interpreter can be invoked in the body of
639 procedures called in the parent during alias invocation. For example,
640 an alias for source could be created in a child interpreter. When it is
641 invoked in the child interpreter, a procedure is called in the parent
642 interpreter to check that the operation is allowable (e.g. it asks to
643 source a file that the child interpreter is allowed to access). The
644 procedure then it invokes the hidden source command in the child inter‐
645 preter to actually source in the contents of the file. Note that two
646 commands named source exist in the child interpreter: the alias, and
647 the hidden command.
648
649 Because a parent interpreter may invoke a hidden command as part of
650 handling an alias invocation, great care must be taken to avoid evalu‐
651 ating any arguments passed in through the alias invocation. Otherwise,
652 malicious child interpreters could cause a trusted parent interpreter
653 to execute dangerous commands on their behalf. See the section on ALIAS
654 INVOCATION for a more complete discussion of this topic. To help avoid
655 this problem, no substitutions or evaluations are applied to arguments
656 of interp invokehidden.
657
658 Safe interpreters are not allowed to invoke hidden commands in them‐
659 selves or in their descendants. This prevents them from gaining access
660 to hidden functionality in themselves or their descendants.
661
662 The set of hidden commands in an interpreter can be manipulated by a
663 trusted interpreter using interp expose and interp hide. The interp ex‐
664 pose command moves a hidden command to the set of exposed commands in
665 the interpreter identified by path, potentially renaming the command in
666 the process. If an exposed command by the targeted name already exists,
667 the operation fails. Similarly, interp hide moves an exposed command to
668 the set of hidden commands in that interpreter. Safe interpreters are
669 not allowed to move commands between the set of hidden and exposed com‐
670 mands, in either themselves or their descendants.
671
672 Currently, the names of hidden commands cannot contain namespace quali‐
673 fiers, and you must first rename a command in a namespace to the global
674 namespace before you can hide it. Commands to be hidden by interp hide
675 are looked up in the global namespace even if the current namespace is
676 not the global one. This prevents children from fooling a parent inter‐
677 preter into hiding the wrong command, by making the current namespace
678 be different from the global one.
679
681 Every interpreter has two kinds of resource limits that may be imposed
682 by any parent interpreter upon its children. Command limits (of type
683 command) restrict the total number of Tcl commands that may be executed
684 by an interpreter (as can be inspected via the info cmdcount command),
685 and time limits (of type time) place a limit by which execution within
686 the interpreter must complete. Note that time limits are expressed as
687 absolute times (as in clock seconds) and not relative times (as in af‐
688 ter) because they may be modified after creation.
689
690 When a limit is exceeded for an interpreter, first any handler call‐
691 backs defined by parent interpreters are called. If those callbacks in‐
692 crease or remove the limit, execution within the (previously) limited
693 interpreter continues. If the limit is still in force, an error is gen‐
694 erated at that point and normal processing of errors within the inter‐
695 preter (by the catch command) is disabled, so the error propagates out‐
696 wards (building a stack-trace as it goes) to the point where the lim‐
697 ited interpreter was invoked (e.g. by interp eval) where it becomes the
698 responsibility of the calling code to catch and handle.
699
700 LIMIT OPTIONS
701 Every limit has a number of options associated with it, some of which
702 are common across all kinds of limits, and others of which are particu‐
703 lar to the kind of limit.
704
705 -command
706 This option (common for all limit types) specifies (if non-
707 empty) a Tcl script to be executed in the global namespace of
708 the interpreter reading and writing the option when the particu‐
709 lar limit in the limited interpreter is exceeded. The callback
710 may modify the limit on the interpreter if it wishes the limited
711 interpreter to continue executing. If the callback generates an
712 exception, it is reported through the background exception mech‐
713 anism (see BACKGROUND EXCEPTION HANDLING). Note that the call‐
714 backs defined by one interpreter are completely isolated from
715 the callbacks defined by another, and that the order in which
716 those callbacks are called is undefined.
717
718 -granularity
719 This option (common for all limit types) specifies how fre‐
720 quently (out of the points when the Tcl interpreter is in a con‐
721 sistent state where limit checking is possible) that the limit
722 is actually checked. This allows the tuning of how frequently a
723 limit is checked, and hence how often the limit-checking over‐
724 head (which may be substantial in the case of time limits) is
725 incurred.
726
727 -milliseconds
728 This option specifies the number of milliseconds after the mo‐
729 ment defined in the -seconds option that the time limit will
730 fire. It should only ever be specified in conjunction with the
731 -seconds option (whether it was set previously or is being set
732 this invocation.)
733
734 -seconds
735 This option specifies the number of seconds after the epoch (see
736 clock seconds) that the time limit for the interpreter will be
737 triggered. The limit will be triggered at the start of the sec‐
738 ond unless specified at a sub-second level using the -millisec‐
739 onds option. This option may be the empty string, which indi‐
740 cates that a time limit is not set for the interpreter.
741
742 -value This option specifies the number of commands that the inter‐
743 preter may execute before triggering the command limit. This op‐
744 tion may be the empty string, which indicates that a command
745 limit is not set for the interpreter.
746
747 Where an interpreter with a resource limit set on it creates a child
748 interpreter, that child interpreter will have resource limits imposed
749 on it that are at least as restrictive as the limits on the creating
750 parent interpreter. If the parent interpreter of the limited parent
751 wishes to relax these conditions, it should hide the interp command in
752 the child and then use aliases and the interp invokehidden subcommand
753 to provide such access as it chooses to the interp command to the lim‐
754 ited parent as necessary.
755
757 When an exception happens in a situation where it cannot be reported
758 directly up the stack (e.g. when processing events in an update or
759 vwait call) the exception is instead reported through the background
760 exception handling mechanism. Every interpreter has a background ex‐
761 ception handler registered; the default exception handler arranges for
762 the bgerror command in the interpreter's global namespace to be called,
763 but other exception handlers may be installed and process background
764 exceptions in substantially different ways.
765
766 A background exception handler consists of a non-empty list of words to
767 which will be appended two further words at invocation time. The first
768 word will be the interpreter result at time of the exception, typically
769 an error message, and the second will be the dictionary of return op‐
770 tions at the time of the exception. These are the same values that
771 catch can capture when it controls script evaluation in a non-back‐
772 ground situation. The resulting list will then be executed in the in‐
773 terpreter's global namespace without further substitutions being per‐
774 formed.
775
777 The safe interpreter mechanism is based on the Safe-Tcl prototype im‐
778 plemented by Nathaniel Borenstein and Marshall Rose.
779
781 Creating and using an alias for a command in the current interpreter:
782
783 interp alias {} getIndex {} lsearch {alpha beta gamma delta}
784 set idx [getIndex delta]
785
786 Executing an arbitrary command in a safe interpreter where every invo‐
787 cation of lappend is logged:
788
789 set i [interp create -safe]
790 interp hide $i lappend
791 interp alias $i lappend {} loggedLappend $i
792 proc loggedLappend {i args} {
793 puts "logged invocation of lappend $args"
794 interp invokehidden $i lappend {*}$args
795 }
796 interp eval $i $someUntrustedScript
797
798 Setting a resource limit on an interpreter so that an infinite loop
799 terminates.
800
801 set i [interp create]
802 interp limit $i command -value 1000
803 interp eval $i {
804 set x 0
805 while {1} {
806 puts "Counting up... [incr x]"
807 }
808 }
809
811 bgerror(n), load(n), safe(n), Tcl_CreateChild(3), Tcl_Eval(3),
812 Tcl_BackgroundException(3)
813
815 alias, parent interpreter, safe interpreter, child interpreter
816
817
818
819Tcl 8.6 interp(n)