\documentclass[]{article}
\usepackage{amsmath,graphicx,supertabular,hyperref,tabularx,ifthen}
\title{TIP \#285: Script Cancellation with [interp cancel] and Tcl\_CancelEval}
\date{June 04, 2006}
\author{Joe Mistachkin, Dawson Cowals}
\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 \#285}&\textbf{Script Cancellation with [interp cancel] and Tcl\_CancelEval}\\\hline
Author&

Joe Mistachkin \tipmail{joe}{mistachkin.com}
\par
Dawson Cowals \tipmail{dawson}{dawsoncowals.com}
\\
Created&Sunday, \(\text{4}^{\text{th}}\) June 2006\\
Type&Project\\
Tcl Version&\(8.6\)\\
State&Final\\
Vote&Done\\
Version&\tipversion$Revision: 1.11 $\\
Keywords&eval, cancel, unwind, terminate, runaway, async, thread, safe\\
Post History&\\
\hline\end{tabularx}\end{center}
\thispagestyle{empty}\pagestyle{empty}
\begin{tipabstract}

This TIP introduces the ability to quickly and safely cancel a script within a specified interpreter from any thread in the process.
\end{tipabstract}
\tableofcontents\setcounter{page}{0}\clearpage\pagestyle{plain}

\section{Key Use-Case Scenario}

When using Tcl inside a context such as a web-browser (e.g. as a plugin), it is often necessary for the execution of a particular script to be terminated cleanly without waiting for the script to get to a point where it is able to respond to events. For example, if the user encounters a page that contains a script that starts a long-running execution but then decides to navigate away from the page, it's important to stop the script as soon as possible.

But we do not want to stop the script by means of just terminating the thread, as this can result in various resources being still allocated, as browsers are long-running applications. Some of the problems (e.g. memory waste) can be worked around by running the script in a separate process, but there are other resources that aren't cleaned up that way, such as locked files or shared memory blocks, and it is always better to give the Tcl interpreter itself an opportunity to clean up after itself. Furthermore, there are other possible applications (such as using Tcl to implement COM objects on Windows) where the separate-process method will not work so well.

Instead, what is needed is a way to programmatically make a script stop its execution even when that script is otherwise determined to continue. This is different from a resource limit in that the cancellation is not caused by the exceeding of a predetermined value, but rather by some external event that is possibly even not processed initially by Tcl at all.

\section{Technical Rationale}

Currently, once the evaluation of a script has been initiated it will do one of the following:
\begin{itemize}
\item{}
run to completion,
\item{}
run until it encounters an uncaught error,
\item{}
run until it exceeds a pre-determined limit as specified in \cite{tip143}, or
\item{}
run indefinitely.
\end{itemize}

In each of the cases above, neither the host application nor an interactive user have any recourse to terminate the script prior to it running its course.

There are many situations for which it is absolutely necessary to be able to cancel a running script without its cooperation and without setting an arbitrary limit on the amount of time it can run (\cite{tip143}). This is especially true in a multi-threaded application embedding environment, or where a user interface is present.
\begin{enumerate}
\item{}
In the case where the completion time for a script is unknown, non-existent, or non-deterministic a user may want or need to terminate the script prematurely.
\setcounter{enumi}{1}
\item{}
When evaluating an untrusted --- or marginally trusted --- script in either a safe or standard interpreter, there is a risk that the script might never terminate. In such a situation it is not reasonable to forcibly terminate the thread or the entire process.
\begin{enumerate}
\item{}
Forcibly terminating a thread prevents Tcl and Tk from cleaning up their thread-specific memory and resources.
\setcounter{enumii}{1}
\item{}
The host application may suffer similar memory and resource leaks as well as other serious side-effects that may corrupt data, prevent other threads from properly synchronizing, or leave the process in an unknown and unrecoverable state.
\setcounter{enumii}{2}
\item{}
For an interactive host application valuable work may be lost without providing an opportunity to save pending modifications. Even in the absence of modifications the host application might have been holding locks that left unreleased would prevent other processes and users from using important resources.
\end{enumerate}
\end{enumerate}

The basic building blocks needed for any scripting language to seamlessly integrate with an enterprise-ready host application are:
\begin{itemize}
\item{}
Engine Initialization
\item{}
Evaluation
\item{}
Extensibility
\item{}
Cancellation
\item{}
Engine Finalization
\end{itemize}

Tcl now provides full support for all of the above except script cancellation. \cite{tip143} allows for scripts to be prematurely terminated after reaching resource limits that were pre-arranged by the host application. However, this only handles terminating scripts based on a narrow set of deterministic criteria. Full support would require the ability to immediately and unconditionally terminate the evaluation of a script without adversely affecting the execution environment of the host application. In addition the following issues must be addressed:
\begin{itemize}
\item{}
Scripts being evaluated in nested slave interpreters.
\item{}
Interaction with third-party extensions.
\item{}
Safely usable by arbitrary threads.
\end{itemize}

Several other mainstream scripting engines (e.g., JavaScript, Microsoft Active Scripting, etc.) currently provide this capability to cancel the evaluation of a script. This TIP proposes an implementation that would bring this necessary aspect of application integration to Tcl. This must be implemented in the core, because access to and modification of internal Tcl functions and data structures is required.

\section{Specification}

A new \textbf{interp cancel} script command will be added, as follows:

\begin{quote}
\textbf{interp cancel} ?\textbf{-unwind}? ?\textbf{-{}-}? ?\textit{path}? ?\textit{result}?
\end{quote}

This command cancels the script being evaluated in the interpreter.

\subsection{Arguments}

\begin{quote}
\textbf{-unwind}
\end{quote}

This argument is optional. Without \textit{-unwind}, the evaluation stack for the interpreter is unwound until an enclosing \textbf{catch} command is found or there are no further invocations of the interpreter left on the call-stack. With \textit{-unwind}, the evaluation stack for the interpreter is unwound without regard to any intervening \textbf{catch} command until there are no further invocations of the interpreter left on the call-stack.

\begin{quote}
\textbf{-{}-}
\end{quote}

This argument is optional, and marks the end of options. The argument following this one will be treated as being the \textit{path} argument even if it starts with a ``-''.

\begin{quote}
\textit{path}
\end{quote}

This argument is optional. If not supplied, the current interpreter is assumed; otherwise, the interpreter specified by \textit{path} is used.

\begin{quote}
\textit{result}
\end{quote}

This argument is optional. If not supplied, a default error message is left in the result of the interpreter; otherwise, the result specified by \textit{result} is used.

\subsection{Behavior}

When a script is canceled, the following occur:
\begin{itemize}
\item{}
The \textit{CANCELED} flag, and possibly the \textit{TCL\_CANCEL\_UNWIND} flag, are set in the interpreter to mark the evaluation in progress as having been canceled.
\item{}
The currently executing command/script in the interpreter is made to return with code \textit{TCL\_ERROR}. (This is superior to using a novel return code, as third-party extensions are usually far better at handling error cases!)
\item{}
The \textbf{catch} command will only catch errors if the interpreter containing it does not have the \textit{TCL\_CANCEL\_UNWIND} flag set.
\item{}
Additional trips through the internal loops of the \textbf{after}, \textbf{vwait}, \textbf{update} and \textbf{tkwait} commands will not proceed with the \textit{CANCELED} or \textit{TCL\_CANCEL\_UNWIND} flags set. (Extensions can find this information out by using \textit{Tcl\_Canceled}; see below.)
\item{}
Once the execution unwinds out of the interpreter, so that no further invocations of the interpreter are left on the call-stack, both of the script cancellation related flags are reset.
\item{}
If there are no invocations of the interpreter on the call-stack when \textit{Tcl\_CancelEval} or \textbf{interp cancel} are called, then the next script to be evaluated will be preemptively canceled.
\end{itemize}

\subsection{Notes}
\begin{itemize}
\item{}
Going forward, all ``long running commands'' in the Tcl/Tk core should make every effort to comply with the script cancellation functionality by calling \textit{Tcl\_Canceled} at times when it is appropriate to abort processing.
\item{}
Extensions can optionally check if they should abort processing by calling \textit{Tcl\_Canceled}.
\end{itemize}

\section{C API}

\subsection{Constants}
\begin{description}
\item[TCL\_CANCEL\_UNWIND]
New eval-flag bit that applies to \textit{Tcl\_CancelEval} and \textit{Tcl\_Canceled}.

When used in \textit{flags} for \textit{Tcl\_CancelEval}, the evaluation stack for \textit{interp} is unwound without regard to any intervening \textbf{catch} command until there are no further invocations of \textit{interp} left on the call stack. When not set, the evaluation stack for the interpreter is unwound until an enclosing \textbf{catch} command is found or there are no further invocations of \textit{interp} left on the call-stack.

When used in \textit{flags} for \textit{Tcl\_Canceled}, checks if the script being evaluated has been canceled using the \textit{TCL\_CANCEL\_UNWIND} flag (i.e., the evaluation stack for \textit{interp} is being completely unwound).
\item[TCL\_LEAVE\_ERR\_MSG]
Existing variable-related flag bit that applies to \textit{Tcl\_Canceled} only.

When used in \textit{flags} for \textit{Tcl\_Canceled}, an error message will be left in the result of \textit{interp} if the script being evaluated has been canceled.
\end{description}

\subsection{Functions}

\begin{quote}
int \textbf{Tcl\_CancelEval}(Tcl\_Interp *\textit{interp}, Tcl\_Obj *\textit{resultObjPtr}, ClientData \textit{clientData}, int \textit{flags})
\end{quote}

The \textbf{Tcl\_CancelEval} function initiates cancellation of the script being evaluated in \textit{interp}. It returns a standard Tcl result. If \textit{resultObjPtr} is NULL, a default error message will be left in the result of \textit{interp} indicating that the script was canceled or unwound. If \textit{resultObjPtr} is not NULL, it will be used verbatim to supply the result of \textit{interp}. The \textit{clientData} is reserved for future use and must be zero. This function may be called from any thread in the process, regardless of which thread created \textit{interp}.

\begin{quote}
int \textbf{Tcl\_Canceled}(Tcl\_Interp *\textit{interp}, int \textit{flags})
\end{quote}

The \textbf{Tcl\_Canceled} function checks whether the script being evaluated in \textit{interp} has been canceled. Returns a standard Tcl result (i.e., \textit{TCL\_ERROR} if the script being evaluated has been canceled). This function should only be called from the thread which created \textit{interp}; otherwise, its behavior is undefined.

\section{Reference Implementation}

A reference implementation of this TIP is available [\url{http://sf.net/tracker/?func=detail&aid=1499394&group_id=10894&atid=310894}].

\section{Copyright}

This document has been placed in the public domain.

\section{Colophon}

\textit{TIP AutoGenerator --- written by Donal K. Fellows}
\begin{thebibliography}{TIP \#1}
\addcontentsline{toc}{section}{References}
\bibitem[TIP \#143]{tip143}
Donal K. Fellows,
\emph{An Interpreter Resource Limiting Framework},
on-line at \url{http://purl.org/tcl/tip/143.html}
\end{thebibliography}
\end{document}
