\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#62: Add Support for Command Tracing}
\date{September 18, 2001}
\author{Hemang Lavana, Vince Darley}
\urlstyle{sf}
\setlength{\parskip}{1ex}
\setlength{\parindent}{0pt}
\def\tipversion$#1${\texttt{\$#1\$}}
\def\tiplangle#1{\ensuremath{<}}
\def\tiprangle#1{\ensuremath{>}}
\def\tipbar#1{\ensuremath{|}}
\def\tipmail#1#2{\(\langle\){\small\expandafter\url{#1@#2}}\(\rangle\)}
\ifx\pdfoutput\undefined
\newcommand{\tipimage}[2]{\typeout{Make sure you download #1.eps}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.eps}}{\includegraphics[width=0.8\textwidth]{#1.eps}}}
\newcommand{\tipxref}[1]{}
\newcommand{\tipxrefend}{}
\else
\newcommand{\tipimage}[2]{\typeout{Make sure you create #1.pdf}\ifthenelse{\lengthtest{0.8\textwidth>#2}\and\lengthtest{0pt<#2}}{\includegraphics{#1.pdf}}{\includegraphics[width=0.8\textwidth]{#1.pdf}}}
\pdfcatalog{/PageMode /UseOutlines}
\newcommand{\tipxref}[1]{\pdfannotlink attr {/C [0.5 0.5 1.0] /Border [0 0 1]} goto name {#1}}
\newcommand{\tipxrefend}{\pdfendlink}
\fi
\newenvironment{tipabstract}{\begin{abstract}}{\end{abstract}}
\begin{document}\maketitle
\begin{center}\begin{tabularx}{\linewidth}{|r@{: }X|}\hline
\textbf{TIP \#62}&\textbf{Add Support for Command Tracing}\\\hline
Author&

Hemang Lavana \tipmail{HemangLavana}{users.sourceforge.net}
\par
Vince Darley \tipmail{vince.darley}{eurobios.com}
\\
Created&Tuesday, \(\text{18}^{\text{th}}\) September 2001\\
Type&Project\\
Tcl Version&\(8.4\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.11 $\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP proposes that the Tcl's trace command be extended to include the following features: 1. tracing of command execution for the specified tcl command, and 2. step-wise tracing of any command execution within a specified procedure.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Rationale}

One of the main strengths of Tcl is the ability to trace \textit{read}, \textit{write} or \textit{delete} operations on variables. Moreover, Tcl8.4 has already added support for tracing \textit{rename} or \textit{delete} operations on Tcl commands. Addition of the proposed subcommand for tracing executions will further improve the capabilities of Tcl without any loss of performance (see \textit{Benchmark Results} section below).

I can see several applications of this feature, including:
\begin{itemize}
\item{}
 overloading/wrapping of Tcl commands, please see \url{http://mini.net/tcl/1494.html}
\item{}
 aid developer in debugging Tcl scripts
\item{}
 profiler module in \textit{tcllib} can benefit from this feature
\end{itemize}

\section{Specification}

This TIP proposes an enhancement to the trace command with the following syntax:
\begingroup\small\begin{verbatim}
        trace add execution name ops command
\end{verbatim}
\endgroup

The type \textit{execution} is used to arrange for \textit{command} to be executed whenever the command \textit{name} is invoked for execution. \textit{Name} may refer to any of the tcl commands or procedures that have been previously defined. It is an error to create an \textit{execution} trace on a non-existant command or a procedure.

The \textit{ops} argument can accept \textit{enter}, \textit{leave}, \textit{enterstep}, and \textit{leavestep} as valid operations:
\begin{enumerate}
\item{}
\textit{enter} --- Invoke \textit{command} whenever the command \textit{name} is executed, just before the actual execution takes place.
\setcounter{enumi}{1}
\item{}
\textit{leave} --- Invoke \textit{command} whenever the command \textit{name} is executed, just after the actual execution takes place.
\setcounter{enumi}{2}
\item{}
\textit{enterstep} --- Invoke \textit{command} for every tcl command which is executed inside the procedure \textit{name}, just before the actual execution takes place. Setting a \textit{enterstep} trace on a \textit{command} will not result in an error and is simply ignored.
\setcounter{enumi}{3}
\item{}
\textit{leavestep} --- Invoke \textit{command} for every tcl command which is executed inside the procedure \textit{name}, just after the actual execution takes place. Setting a \textit{leavestep} trace on a \textit{command} will not result in an error and is simply ignored.
\end{enumerate}

When the trace triggers, depending on the operations being traced, a number of arguments are appended to command so that the actual command is as follows:

For \textit{enter} and \textit{enterstep} operations:
\begingroup\small\begin{verbatim}
    command command-string op
\end{verbatim}
\endgroup

\textit{command-string} gives the complete current command being executed, including all arguments in their fully expanded form. \textit{Op} indicates what operation is being performed on the variable, and is one of \textit{enter} or \textit{enterstep} here. The trace operation can be used to stop the command from executing, by deleting the command in question. Of course when the command is subsequently executed, an 'invalid command' error will occur.

For \textit{leave} and \textit{leavestep} operations:
\begingroup\small\begin{verbatim}
   command command-string code result op
\end{verbatim}
\endgroup

\textit{command-string} gives the complete current command being executed, including all arguments in their fully expanded form. \textit{code} gives the result code of that execution, and \textit{result} gives its result string. \textit{Op} indicates what operation is being performed on the variable, and is one of \textit{leave} or \textit{leavestep} here.

\textit{Command} executes in the same context as the code that invoked the traced operation: thus the \textit{command}, if invoked from a procedure, will have access to the same local variables as code in the procedure. This context may be different than the context in which the trace was created. If \textit{command} invokes a procedure (which it normally does) then the procedure will have to use upvar or uplevel commands if it wishes to access the local variables of the code which invoked the trace operation. Note that if the value of a local variable is passed as an argument to the traced command \textit{name} and is modified by the \textit{command} procedure, the traced command \textit{name} will still be invoked with the old value of the local variable. This is because the argument list to \textit{name} is formed before the traced \textit{command} is invoked. Please see the section on \textit{Future Scope} below on how to modify the arguments passed to \textit{name}.

While \textit{command} is executing during an \textit{execution} trace, traces on \textit{name} are temporarily disabled. This allows the \textit{command} to execute \textit{name} in its body without invoking any other traces again. If an error occurs while executing the \textit{command} body, then the command \textit{name} as a whole will return that same error. Therefore, if \textit{catch} command is used for invocation of the \textit{name} command, it will also ignore errors resulting from such traces.

When multiple traces are set on \textit{name}, then the sequence of trace command invocation is as follows:
\begin{enumerate}
\item{}
 For \textit{enter} and \textit{enterstep} operations, the traced commands are invoked in the reverse order of how these traces were created.
\setcounter{enumi}{1}
\item{}
 For \textit{leave} and \textit{leavestep} operations, the traced commands are invoked in the same order as how these traces were created.
\end{enumerate}

For example, if we have two traces on proc foo:
\begingroup\small\begin{verbatim}
    trace add execution foo {enter leave} {barA}
    trace add execution foo {enter leave} {barB}
\end{verbatim}
\endgroup

then the trace commands \textit{barA} and \textit{barB} will be invoked in the following sequence:
\begingroup\small\begin{verbatim}
    barB {foo x} {enter}
    barA {foo x} {enter}
      foo x
    barA {foo x} 0 {} {leave}
    barB {foo x} 0 {} {leave}
\end{verbatim}
\endgroup

The creation of many \textit{enterstep} or \textit{leavestep} traces can lead to unintuitive results, since the invoked commands from one trace can themselves lead to further command invocations for other traces. However, these unintuitive results are completely predictable and safe (and tested in the test suite). Nevertheless the user will probably only want to have one such trace active at a time.

Once created, the trace remains in effect either until the trace is removed with the \textit{trace remove execution} command, until the \textit{name} is deleted or until the interpreter is deleted. Note that renaming the command \textit{name} will not remove the execution traces.

To implement \textit{enterstep} and \textit{leavestep} traces, it is necessary to invoke traces regardless of at what level the \textit{command} is being traced. This means that the value for \textit{level} argument to Tcl\_CreateTrace and Tcl\_CreateObjTrace APIs should also accept \textit{0}. A value of \textit{0} implies that commands at all levels will be traced. 

\section{Examples}

The following script defines a procedure \textit{foo} and illustrates several cases as to how its execution can be traced.
\begingroup\small\begin{verbatim}
    # Define the proc foo
    proc foo {var} {
         return [string index $var [expr {$var*2}]]
    }
    
    # Command to invoke on trace activation
    proc print {args} {
        puts stdout "PRINT: $args"
    }
    
    proc main {} {
        puts stdout "================CASE 1========================="
        puts stdout "Trace proc foo only"
        trace add execution foo {enter leave} {print exec}
        foo 4
    
        puts stdout "================CASE 2========================="
        puts stdout "Trace proc foo as well as all commands within it"
        trace add execution foo {enterstep leavestep} {print step}
        foo 4
    
        # Remove all traces
        trace remove execution foo {enter leave} {print exec}
        trace remove execution foo {enterstep leavestep} {print step}
    
        puts stdout "================CASE 3========================="
        puts stdout "Add a trace on string command"
        trace add execution string {enter leave} {print exec}
        foo 4
        trace remove execution string {enter leave} {print exec}
    }
    main
\end{verbatim}
\endgroup

The expected output of running the above script would be:
\begingroup\small\begin{verbatim}
    ===================CASE 1========================
    Trace proc foo only
    PRINT: exec {foo 4} enter
    PRINT: exec {foo 4} 0 {} leave
    ===================CASE 2=======================
    Trace proc foo as well as all commands within it
    PRINT: exec {foo 4} enter
    PRINT: step {expr {$var*2}} enterstep
    PRINT: step {expr {$var*2}} 0 8 leavestep
    PRINT: step {string index 4 8} enterstep
    PRINT: step {string index 4 8} 0 {} leavestep
    PRINT: step {return {}} enterstep
    PRINT: step {return {}} 2 {} leavestep
    PRINT: exec {foo 4} 0 {} leave
    ===================CASE 3=======================
    Add a trace on string command
    PRINT: exec {string index 4 8} enter
    PRINT: exec {string index 4 8} 0 {} leave
\end{verbatim}
\endgroup

Case 1 specifies a enter and leave trace on proc foo. Here the proc foo is fully byte-code-compiled.

Case 2 additionally invokes a enterstep and leavestep trace on proc foo. This means that it will trace each command that is inovked within the proc foo. Here the proc foo is *not* byte-code-compiled. This is implemented by setting the DONT\_COMPILE\_CMDS\_INLINE flag.

Case 3 specifies a trace on string command only. Here all commands within proc foo, except string command, is byte-code-compiled. This is implemented by modifying compilation engine to check for CMD\_HAS\_EXEC\_TRACES flag before generating any byte-code.

\section{Reference Implementation}

This proposal was originally implemented by Vince Darley. Please see Feature Request \#462580: \url{http://sf.net/tracker/?func=detail&aid=462580&group_id=10894&atid=360894}

The original patch from Vince Darley has been modified in the following respects:
\begin{enumerate}
\item{}
 For \textit{enter} and \textit{enterstep} operations, the original patch passed arguments to the \textit{command} in its unexpanded form. This behavior has been changed to pass the arguments in its fully expanded form since it should be more useful for debugging scripts.
\setcounter{enumi}{1}
\item{}
 The original patch could not trace Tcl commands that were invoked inside a procedure because tracing is currently not possible for compiled commands. Therefore, the patch was modified such that Tcl commands are no longer internally compiled if a trace has been set on a command.
\setcounter{enumi}{2}
\item{}
 For multiple traces on same command, the original patch invoked the traces in the same order as they were created. This behavior was changed so that for \textit{enter} and \textit{enterstep} operations, the traces are invoked in the reverse order of its creation. For \textit{leave} and \textit{leavestep}, the traces are still invoked in the original order.
\setcounter{enumi}{3}
\item{}
 The original patch was created on 2000-Sept-14. It was updated to work with the current CVS head.
\end{enumerate}

The latest patch for this tip 62 is available at:

 \url{http://www.employees.org/~hlavana/tcl/}

The main changes for the patch are described in brief next.

Two new flags have been defined in tcl.h:
\begingroup\small\begin{verbatim}
  #define TCL_TRACE_ENTER_EXEC          1
  #define TCL_TRACE_LEAVE_EXEC          2
\end{verbatim}
\endgroup

These flag values are passed to Tcl\_CreateObjTrace and used by command execution traces. More internal flags for slots 4, 8, 15, 16, 32 are defined in tclCmdMZ.c file: TCL\_TRACE\_ENTER\_DURING\_EXEC, TCL\_TRACE\_LEAVE\_DURING\_EXEC, TCL\_TRACE\_ANY\_EXEC, TCL\_TRACE\_EXEC\_IN\_PROGRESS and TCL\_TRACE\_EXEC\_DIRECT.

A new function TclTraceExecutionObjCmd function implements the \textit{trace \{add\tipbar{}remove\tipbar{}list\} execution ...} subcommands. A new function TclCheckExecutionTraces is defined to check for traces added by the execution subcommand. A new function TclCheckInterpTraces is defined to check for global traces added by the Tcl\_CreateObjTrace command. The TclEvalObjvInternal has been modified to call the above two functions before as well as after the original command is executed. A new function TraceExecutionProc is invoked, when necessary, to execute the actual trace command in the interpreter.

A new structure ActiveInterpTrace has been defined for internal use so that it behaves reasonably when traces are deleted while active. In tclVar.c file, the function CallTraces has been renamed to CallVarTraces and iPtr-\tiprangle{}activeTracePtr has been renamed to iPtr-\tiprangle{}activeTraceVarPtr.

An additional check for (tracePtr-\tiprangle{}level == 0) has been added in Tcl\_EvalObjv and TclExecuteByteCode functions, so as to enable command tracing at all levels.

\section{Benchmark Results}

The benchmark results corresponds to \textit{Version 1.1} of the reference implementation.

One potential objection to this TIP could be that it may affect the performance of the Tcl-core. Therefore, I have run the \textit{runbench.tcl} script from the tclbench module for comparison on a Sun Ultra5, Solaris2.6 machine. The results have been posted at \url{http://sf.net/tracker/?func=detail&aid=462580&group_id=10894&atid=360894}

These results show that there is hardly any performance hit, if any, by addition of this feature. Of course when you activate a trace on a command, then you will see a performance hit, but since primary uses of traces will be in profiling and debugging, that isn't an issue.

\section{Future Scope}

This proposal does not allow for the trace invocation \textit{command} to do the following:
\begin{enumerate}
\item{}
modify the number of arguments passed to \textit{name}
\setcounter{enumi}{1}
\item{}
modify the value of arguments passed to \textit{name}
\setcounter{enumi}{2}
\item{}
modify the result value and result code returned by \textit{name}
\setcounter{enumi}{3}
\item{}
skip invocation of \textit{name} altogether if desired.
\end{enumerate}

Consider the example of adding a sub-command ``string reverse ...'' as shown on \url{http://mini.net/tcl/1570.html.} Instead of using the rename command, it should be possible to use the trace command to do the same, as follows:
\begingroup\small\begin{verbatim}
    trace add execution string {enter} {::mylib::stringx}
    proc ::mylib::stringx {subcmd args} {
        switch -exact -- $subcmd {
            "reverse" {
                # Hmm ... this is my subcommand, process it here
                set returnValue [code_to_reverse_string_value]

                # We need a mechansim to return immediately here
                # with the processed results and an appropriate
                # code value and not invoke the original string command.
            }
            default {
                # This is probably a vaild subcommand, so do nothing
                # and let the original string command handle it
            }
        }
    }
\end{verbatim}
\endgroup

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\end{document}
