Ignore:
Timestamp:
Feb 4, 2021, 10:03:29 PM (2 years ago)
Author:
Thierry Delisle <tdelisle@…>
Branches:
ADT, arm-eh, enum, forall-pointer-decay, jacob/cs343-translation, master, new-ast-unique-expr, pthread-emulation, qualifiedEnum
Children:
5ce9bea
Parents:
c292244 (diff), 9af0fe2d (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge branch 'master' of plg.uwaterloo.ca:software/cfa/cfa-cc

Location:
doc/theses/andrew_beach_MMath
Files:
9 edited

Legend:

Unmodified
Added
Removed
  • doc/theses/andrew_beach_MMath/existing.tex

    rc292244 ref0b456  
    1 \chapter{\texorpdfstring{\CFA Existing Features}{Cforall Existing Features}}
     1\chapter{\CFA Existing Features}
    22
    33\CFA (C-for-all)~\cite{Cforall} is an open-source project extending ISO C with
     
    1212obvious to the reader.
    1313
    14 \section{\texorpdfstring{Overloading and \lstinline|extern|}{Overloading and extern}}
     14\section{Overloading and \lstinline{extern}}
    1515\CFA has extensive overloading, allowing multiple definitions of the same name
    1616to be defined.~\cite{Moss18}
     
    4242
    4343\section{Reference Type}
    44 \CFA adds a rebindable reference type to C, but more expressive than the \CC
     44\CFA adds a rebindable reference type to C, but more expressive than the \Cpp
    4545reference.  Multi-level references are allowed and act like auto-dereferenced
    4646pointers using the ampersand (@&@) instead of the pointer asterisk (@*@). \CFA
     
    5959
    6060Both constructors and destructors are operators, which means they are just
    61 functions with special operator names rather than type names in \CC. The
     61functions with special operator names rather than type names in \Cpp. The
    6262special operator names may be used to call the functions explicitly (not
    63 allowed in \CC for constructors).
     63allowed in \Cpp for constructors).
    6464
    6565In general, operator names in \CFA are constructed by bracketing an operator
     
    8888matching overloaded destructor @void ^?{}(T &);@ is called.  Without explicit
    8989definition, \CFA creates a default and copy constructor, destructor and
    90 assignment (like \CC). It is possible to define constructors/destructors for
     90assignment (like \Cpp). It is possible to define constructors/destructors for
    9191basic and existing types.
    9292
     
    9494\CFA uses parametric polymorphism to create functions and types that are
    9595defined over multiple types. \CFA polymorphic declarations serve the same role
    96 as \CC templates or Java generics. The ``parametric'' means the polymorphism is
     96as \Cpp templates or Java generics. The ``parametric'' means the polymorphism is
    9797accomplished by passing argument operations to associate \emph{parameters} at
    9898the call site, and these parameters are used in the function to differentiate
     
    134134
    135135Note, a function named @do_once@ is not required in the scope of @do_twice@ to
    136 compile it, unlike \CC template expansion. Furthermore, call-site inferencing
     136compile it, unlike \Cpp template expansion. Furthermore, call-site inferencing
    137137allows local replacement of the most specific parametric functions needs for a
    138138call.
     
    178178}
    179179\end{cfa}
    180 The generic type @node(T)@ is an example of a polymorphic-type usage.  Like \CC
     180The generic type @node(T)@ is an example of a polymorphic-type usage.  Like \Cpp
    181181templates usage, a polymorphic-type usage must specify a type parameter.
    182182
  • doc/theses/andrew_beach_MMath/features.tex

    rc292244 ref0b456  
    55
    66\section{Virtuals}
     7Virtual types and casts are not part of the exception system nor are they
     8required for an exception system. But an object-oriented style hierarchy is a
     9great way of organizing exceptions so a minimal virtual system has been added
     10to \CFA.
     11
     12The pattern of a simple hierarchy was borrowed from object-oriented
     13programming was chosen for several reasons.
     14The first is that it allows new exceptions to be added in user code
     15and in libraries independently of each other. Another is it allows for
     16different levels of exception grouping (all exceptions, all IO exceptions or
     17a particular IO exception). Also it also provides a simple way of passing
     18data back and forth across the throw.
     19
    720Virtual types and casts are not required for a basic exception-system but are
    821useful for advanced exception features. However, \CFA is not object-oriented so
    9 there is no obvious concept of virtuals.  Hence, to create advanced exception
    10 features for this work, I needed to designed and implemented a virtual-like
     22there is no obvious concept of virtuals. Hence, to create advanced exception
     23features for this work, I needed to design and implement a virtual-like
    1124system for \CFA.
    1225
     26% NOTE: Maybe we should but less of the rational here.
    1327Object-oriented languages often organized exceptions into a simple hierarchy,
    1428\eg Java.
     
    3044\end{center}
    3145The hierarchy provides the ability to handle an exception at different degrees
    32 of specificity (left to right).  Hence, it is possible to catch a more general
     46of specificity (left to right). Hence, it is possible to catch a more general
    3347exception-type in higher-level code where the implementation details are
    3448unknown, which reduces tight coupling to the lower-level implementation.
     
    6175While much of the virtual infrastructure is created, it is currently only used
    6276internally for exception handling. The only user-level feature is the virtual
    63 cast, which is the same as the \CC \lstinline[language=C++]|dynamic_cast|.
     77cast, which is the same as the \Cpp \lstinline[language=C++]|dynamic_cast|.
     78\label{p:VirtualCast}
    6479\begin{cfa}
    6580(virtual TYPE)EXPRESSION
    6681\end{cfa}
    67 Note, the syntax and semantics matches a C-cast, rather than the unusual \CC
    68 syntax for special casts. Both the type of @EXPRESSION@ and @TYPE@ must be a
    69 pointer to a virtual type. The cast dynamically checks if the @EXPRESSION@ type
    70 is the same or a subtype of @TYPE@, and if true, returns a pointer to the
     82Note, the syntax and semantics matches a C-cast, rather than the function-like
     83\Cpp syntax for special casts. Both the type of @EXPRESSION@ and @TYPE@ must be
     84a pointer to a virtual type.
     85The cast dynamically checks if the @EXPRESSION@ type is the same or a subtype
     86of @TYPE@, and if true, returns a pointer to the
    7187@EXPRESSION@ object, otherwise it returns @0p@ (null pointer).
    7288
     
    7793
    7894Exceptions are defined by the trait system; there are a series of traits, and
    79 if a type satisfies them, then it can be used as an exception.  The following
     95if a type satisfies them, then it can be used as an exception. The following
    8096is the base trait all exceptions need to match.
    8197\begin{cfa}
    8298trait is_exception(exceptT &, virtualT &) {
    83         virtualT const & @get_exception_vtable@(exceptT *);
     99        virtualT const & get_exception_vtable(exceptT *);
    84100};
    85101\end{cfa}
    86 The function takes any pointer, including the null pointer, and returns a
    87 reference to the virtual-table object. Defining this function also establishes
    88 the virtual type and a virtual-table pair to the \CFA type-resolver and
    89 promises @exceptT@ is a virtual type and a child of the base exception-type.
    90 
    91 {\color{blue} PAB: I do not understand this paragraph.}
    92 One odd thing about @get_exception_vtable@ is that it should always be a
    93 constant function, returning the same value regardless of its argument.  A
    94 pointer or reference to the virtual table instance could be used instead,
    95 however using a function has some ease of implementation advantages and allows
    96 for easier disambiguation because the virtual type name (or the address of an
    97 instance that is in scope) can be used instead of the mangled virtual table
    98 name.  Also note the use of the word ``promise'' in the trait
    99 description. Currently, \CFA cannot check to see if either @exceptT@ or
    100 @virtualT@ match the layout requirements. This is considered part of
    101 @get_exception_vtable@'s correct implementation.
     102The trait is defined over two types, the exception type and the virtual table
     103type. This should be one-to-one, each exception type has only one virtual
     104table type and vice versa. The only assertion in the trait is
     105@get_exception_vtable@, which takes a pointer of the exception type and
     106returns a reference to the virtual table type instance.
     107
     108The function @get_exception_vtable@ is actually a constant function.
     109Recardless of the value passed in (including the null pointer) it should
     110return a reference to the virtual table instance for that type.
     111The reason it is a function instead of a constant is that it make type
     112annotations easier to write as you can use the exception type instead of the
     113virtual table type; which usually has a mangled name.
     114% Also \CFA's trait system handles functions better than constants and doing
     115% it this way
     116
     117% I did have a note about how it is the programmer's responsibility to make
     118% sure the function is implemented correctly. But this is true of every
     119% similar system I know of (except Agda's I guess) so I took it out.
    102120
    103121\section{Raise}
    104 \CFA provides two kinds of exception raise: termination (see
    105 \VRef{s:Termination}) and resumption (see \VRef{s:Resumption}), which are
     122\CFA provides two kinds of exception raise: termination
     123\see{\VRef{s:Termination}} and resumption \see{\VRef{s:Resumption}}, which are
    106124specified with the following traits.
    107125\begin{cfa}
    108126trait is_termination_exception(
    109127                exceptT &, virtualT & | is_exception(exceptT, virtualT)) {
    110         void @defaultTerminationHandler@(exceptT &);
     128        void defaultTerminationHandler(exceptT &);
    111129};
    112130\end{cfa}
     
    118136trait is_resumption_exception(
    119137                exceptT &, virtualT & | is_exception(exceptT, virtualT)) {
    120         void @defaultResumptionHandler@(exceptT &);
     138        void defaultResumptionHandler(exceptT &);
    121139};
    122140\end{cfa}
     
    125143
    126144Finally there are three convenience macros for referring to the these traits:
    127 @IS_EXCEPTION@, @IS_TERMINATION_EXCEPTION@ and @IS_RESUMPTION_EXCEPTION@.  Each
    128 takes the virtual type's name, and for polymorphic types only, the
    129 parenthesized list of polymorphic arguments. These macros do the name mangling
    130 to get the virtual-table name and provide the arguments to both sides
    131 {\color{blue}(PAB: What's a ``side''?)}
     145@IS_EXCEPTION@, @IS_TERMINATION_EXCEPTION@ and @IS_RESUMPTION_EXCEPTION@.
     146All three traits are hard to use while naming the virtual table as it has an
     147internal mangled name. These macros take the exception name as their first
     148argument and do the mangling. They all take a second argument for polymorphic
     149types which is the parenthesized list of polymorphic arguments. These
     150arguments are passed to both the exception type and the virtual table type as
     151the arguments do have to match.
     152
     153For example consider a function that is polymorphic over types that have a
     154defined arithmetic exception:
     155\begin{cfa}
     156forall(Num | IS_EXCEPTION(Arithmetic, (Num)))
     157void some_math_function(Num & left, Num & right);
     158\end{cfa}
    132159
    133160\subsection{Termination}
     
    146173throw EXPRESSION;
    147174\end{cfa}
    148 The expression must return a termination-exception reference, where the
    149 termination exception has a type with a @void defaultTerminationHandler(T &)@
    150 (default handler) defined. The handler is found at the call site using \CFA's
    151 trait system and passed into the exception system along with the exception
    152 itself.
    153 
    154 At runtime, a representation of the exception type and an instance of the
    155 exception type is copied into managed memory (heap) to ensure it remains in
     175The expression must return a reference to a termination exception, where the
     176termination exception is any type that satifies @is_termination_exception@
     177at the call site.
     178Through \CFA's trait system the functions in the traits are passed into the
     179throw code. A new @defaultTerminationHandler@ can be defined in any scope to
     180change the throw's behavior (see below).
     181
     182At runtime, the exception returned by the expression
     183is copied into managed memory (heap) to ensure it remains in
    156184scope during unwinding. It is the user's responsibility to ensure the original
    157185exception object at the throw is freed when it goes out of scope. Being
     
    165193try {
    166194        GUARDED_BLOCK
    167 } @catch (EXCEPTION_TYPE$\(_1\)$ * NAME)@ { // termination handler 1
     195} catch (EXCEPTION_TYPE$\(_1\)$ * NAME$\(_1\)$) { // termination handler 1
    168196        HANDLER_BLOCK$\(_1\)$
    169 } @catch (EXCEPTION_TYPE$\(_2\)$ * NAME)@ { // termination handler 2
     197} catch (EXCEPTION_TYPE$\(_2\)$ * NAME$\(_2\)$) { // termination handler 2
    170198        HANDLER_BLOCK$\(_2\)$
    171199}
     
    178206Exception matching checks the representation of the thrown exception-type is
    179207the same or a descendant type of the exception types in the handler clauses. If
    180 there is a match, a pointer to the exception object created at the throw is
    181 bound to @NAME@ and the statements in the associated @HANDLER_BLOCK@ are
    182 executed. If control reaches the end of the handler, the exception is freed,
    183 and control continues after the try statement.
     208it is the same of a descendent of @EXCEPTION_TYPE@$_i$ then @NAME@$_i$ is
     209bound to a pointer to the exception and the statements in @HANDLER_BLOCK@$_i$
     210are executed. If control reaches the end of the handler, the exception is
     211freed and control continues after the try statement.
    184212
    185213The default handler visible at the throw statement is used if no matching
    186214termination handler is found after the entire stack is searched. At that point,
    187215the default handler is called with a reference to the exception object
    188 generated at the throw. If the default handler returns, the system default
    189 action is executed, which often terminates the program. This feature allows
     216generated at the throw. If the default handler returns, control continues
     217from after the throw statement. This feature allows
    190218each exception type to define its own action, such as printing an informative
    191219error message, when an exception is not handled in the program.
     220However the default handler for all exception types triggers a cancellation
     221using the exception.
    192222
    193223\subsection{Resumption}
     
    196226Resumption raise, called ``resume'', is as old as termination
    197227raise~\cite{Goodenough75} but is less popular. In many ways, resumption is
    198 simpler and easier to understand, as it is simply a dynamic call (as in
    199 Lisp). The semantics of resumption is: search the stack for a matching handler,
     228simpler and easier to understand, as it is simply a dynamic call.
     229The semantics of resumption is: search the stack for a matching handler,
    200230execute the handler, and continue execution after the resume. Notice, the stack
    201231cannot be unwound because execution returns to the raise point. Resumption is
     
    209239\end{cfa}
    210240The semantics of the @throwResume@ statement are like the @throw@, but the
    211 expression has a type with a @void defaultResumptionHandler(T &)@ (default
    212 handler) defined, where the handler is found at the call site by the type
    213 system.  At runtime, a representation of the exception type and an instance of
    214 the exception type is \emph{not} copied because the stack is maintained during
    215 the handler search.
     241expression has return a reference a type that satifies the trait
     242@is_resumption_exception@. Like with termination the exception system can
     243use these assertions while (throwing/raising/handling) the exception.
     244
     245At runtime, no copies are made. As the stack is not unwound the exception and
     246any values on the stack will remain in scope while the resumption is handled.
    216247
    217248Then the exception system searches the stack starting from the resume and
    218 proceeding towards the base of the stack, from callee to caller. At each stack
     249proceeding to the base of the stack, from callee to caller. At each stack
    219250frame, a check is made for resumption handlers defined by the @catchResume@
    220251clauses of a @try@ statement.
     
    222253try {
    223254        GUARDED_BLOCK
    224 } @catchResume (EXCEPTION_TYPE$\(_1\)$ * NAME)@ { // resumption handler 1
     255} catchResume (EXCEPTION_TYPE$\(_1\)$ * NAME$\(_1\)$) {
    225256        HANDLER_BLOCK$\(_1\)$
    226 } @catchResume (EXCEPTION_TYPE$\(_2\)$ * NAME)@ { // resumption handler 2
     257} catchResume (EXCEPTION_TYPE$\(_2\)$ * NAME$\(_2\)$) {
    227258        HANDLER_BLOCK$\(_2\)$
    228259}
     
    253284current point on the stack because new try statements may have been pushed by
    254285the handler or functions called from the handler. If there is no match back to
    255 the point of the current handler, the search skips the stack frames already
    256 searched by the first resume and continues after the try statement. The default
    257 handler always continues from default handler associated with the point where
    258 the exception is created.
     286the point of the current handler, the search skips\label{p:searchskip} the
     287stack frames already searched by the first resume and continues after
     288the try statement. The default handler always continues from default
     289handler associated with the point where the exception is created.
    259290
    260291% This might need a diagram. But it is an important part of the justification
     
    275306\end{verbatim}
    276307
    277 This resumption search-pattern reflect the one for termination, which matches
    278 with programmer expectations. However, it avoids the \emph{recursive
    279 resumption} problem. If parts of the stack are searched multiple times, loops
     308This resumption search pattern reflects the one for termination, and so
     309should come naturally to most programmers.
     310However, it avoids the \emph{recursive resumption} problem.
     311If parts of the stack are searched multiple times, loops
    280312can easily form resulting in infinite recursion.
    281313
     
    283315\begin{cfa}
    284316try {
    285         throwResume$\(_1\)$ (E &){};
    286 } catch( E * ) {
    287         throwResume;
    288 }
    289 \end{cfa}
    290 Based on termination semantics, programmer expectation is for the re-resume to
    291 continue searching the stack frames after the try statement. However, the
    292 current try statement is still on the stack below the handler issuing the
    293 reresume (see \VRef{s:Reraise}). Hence, the try statement catches the re-raise
    294 again and does another re-raise \emph{ad infinitum}, which is confusing and
    295 difficult to debug. The \CFA resumption search-pattern skips the try statement
    296 so the reresume search continues after the try, mathcing programmer
    297 expectation.
     317        throwResume (E &){}; // first
     318} catchResume(E *) {
     319        throwResume (E &){}; // second
     320}
     321\end{cfa}
     322If this handler is ever used it will be placed on top of the stack above the
     323try statement. If the stack was not masked than the @throwResume@ in the
     324handler would always be caught by the handler, leading to an infinite loop.
     325Masking avoids this problem and other more complex versions of it involving
     326multiple handlers and exception types.
     327
     328Other masking stratagies could be used; such as masking the handlers that
     329have caught an exception. This one was choosen because it creates a symmetry
     330with termination (masked sections of the stack would be unwound with
     331termination) and having only one pattern to learn is easier.
    298332
    299333\section{Conditional Catch}
    300 Both termination and resumption handler-clauses may perform conditional matching:
     334Both termination and resumption handler clauses can be given an additional
     335condition to further control which exceptions they handle:
    301336\begin{cfa}
    302337catch (EXCEPTION_TYPE * NAME ; @CONDITION@)
     
    305340exception matches, @CONDITION@ is executed. The condition expression may
    306341reference all names in scope at the beginning of the try block and @NAME@
    307 introduced in the handler clause.  If the condition is true, then the handler
     342introduced in the handler clause. If the condition is true, then the handler
    308343matches. Otherwise, the exception search continues at the next appropriate kind
    309344of handler clause in the try block.
     
    322357
    323358\section{Reraise}
     359\color{red}{From Andrew: I recomend we talk about why the language doesn't
     360have rethrows/reraises instead.}
     361
    324362\label{s:Reraise}
    325363Within the handler block or functions called from the handler block, it is
     
    327365@throwResume@, respective.
    328366\begin{cfa}
    329 catch( ... ) {
     367try {
     368        ...
     369} catch( ... ) {
    330370        ... throw; // rethrow
    331371} catchResume( ... ) {
     
    340380handler is generated that does a program-level abort.
    341381
    342 
    343382\section{Finally Clauses}
    344383A @finally@ clause may be placed at the end of a @try@ statement.
     
    346385try {
    347386        GUARDED_BLOCK
    348 } ...   // any number or kind of handler clauses
    349 } finally {
     387} ... // any number or kind of handler clauses
     388... finally {
    350389        FINALLY_BLOCK
    351390}
    352391\end{cfa}
    353 The @FINALLY_BLOCK@ is executed when the try statement is unwound from the
    354 stack, \ie when the @GUARDED_BLOCK@ or any handler clause finishes. Hence, the
    355 finally block is always executed.
     392The @FINALLY_BLOCK@ is executed when the try statement is removed from the
     393stack, including when the @GUARDED_BLOCK@ or any handler clause finishes or
     394during an unwind.
     395The only time the block is not executed is if the program is exited before
     396that happens.
    356397
    357398Execution of the finally block should always finish, meaning control runs off
    358399the end of the block. This requirement ensures always continues as if the
    359400finally clause is not present, \ie finally is for cleanup not changing control
    360 flow.  Because of this requirement, local control flow out of the finally block
    361 is forbidden.  The compiler precludes any @break@, @continue@, @fallthru@ or
     401flow. Because of this requirement, local control flow out of the finally block
     402is forbidden. The compiler precludes any @break@, @continue@, @fallthru@ or
    362403@return@ that causes control to leave the finally block. Other ways to leave
    363404the finally block, such as a long jump or termination are much harder to check,
     
    369410possible forwards the cancellation exception to a different stack.
    370411
     412Cancellation is not an exception operation like termination or resumption.
    371413There is no special statement for starting a cancellation; instead the standard
    372 library function @cancel_stack@ is called passing an exception.  Unlike a
     414library function @cancel_stack@ is called passing an exception. Unlike a
    373415raise, this exception is not used in matching only to pass information about
    374416the cause of the cancellation.
     
    377419\begin{description}
    378420\item[Main Stack:]
    379 
    380421The main stack is the one used by the program main at the start of execution,
    381 and is the only stack in a sequential program.  Hence, when cancellation is
    382 forwarded to the main stack, there is no other forwarding stack, so after the
    383 stack is unwound, there is a program-level abort.
     422and is the only stack in a sequential program. Even in a concurrent program
     423the main stack is only dependent on the environment that started the program.
     424Hence, when the main stack is cancelled there is nowhere else in the program
     425to notify. After the stack is unwound, there is a program-level abort.
    384426
    385427\item[Thread Stack:]
    386428A thread stack is created for a @thread@ object or object that satisfies the
    387 @is_thread@ trait.  A thread only has two points of communication that must
     429@is_thread@ trait. A thread only has two points of communication that must
    388430happen: start and join. As the thread must be running to perform a
    389 cancellation, it must occur after start and before join, so join is a
    390 cancellation point.  After the stack is unwound, the thread halts and waits for
    391 another thread to join with it. The joining thread, checks for a cancellation,
     431cancellation, it must occur after start and before join, so join is used
     432for communication here.
     433After the stack is unwound, the thread halts and waits for
     434another thread to join with it. The joining thread checks for a cancellation,
    392435and if present, resumes exception @ThreadCancelled@.
    393436
     
    397440the exception is not caught. The implicit join does a program abort instead.
    398441
    399 This semantics is for safety. One difficult problem for any exception system is
    400 defining semantics when an exception is raised during an exception search:
    401 which exception has priority, the original or new exception? No matter which
    402 exception is selected, it is possible for the selected one to disrupt or
    403 destroy the context required for the other. {\color{blue} PAB: I do not
    404 understand the following sentences.} This loss of information can happen with
    405 join but as the thread destructor is always run when the stack is being unwound
    406 and one termination/cancellation is already active. Also since they are
    407 implicit they are easier to forget about.
     442This semantics is for safety. If an unwind is triggered while another unwind
     443is underway only one of them can proceed as they both want to ``consume'' the
     444stack. Letting both try to proceed leads to very undefined behaviour.
     445Both termination and cancellation involve unwinding and, since the default
     446@defaultResumptionHandler@ preforms a termination that could more easily
     447happen in an implicate join inside a destructor. So there is an error message
     448and an abort instead.
     449
     450The recommended way to avoid the abort is to handle the intial resumption
     451from the implicate join. If required you may put an explicate join inside a
     452finally clause to disable the check and use the local
     453@defaultResumptionHandler@ instead.
    408454
    409455\item[Coroutine Stack:] A coroutine stack is created for a @coroutine@ object
    410 or object that satisfies the @is_coroutine@ trait.  A coroutine only knows of
    411 two other coroutines, its starter and its last resumer.  The last resumer has
    412 the tightest coupling to the coroutine it activated.  Hence, cancellation of
     456or object that satisfies the @is_coroutine@ trait. A coroutine only knows of
     457two other coroutines, its starter and its last resumer. The last resumer has
     458the tightest coupling to the coroutine it activated. Hence, cancellation of
    413459the active coroutine is forwarded to the last resumer after the stack is
    414460unwound, as the last resumer has the most precise knowledge about the current
  • doc/theses/andrew_beach_MMath/future.tex

    rc292244 ref0b456  
    11\chapter{Future Work}
    22
     3\section{Language Improvements}
     4\CFA is a developing programming language. As such, there are partially or
     5unimplemented features of the language (including several broken components)
     6that I had to workaround while building an exception handling system largely in
     7the \CFA language (some C components).  The following are a few of these
     8issues, and once implemented/fixed, how this would affect the exception system.
     9\begin{itemize}
     10\item
     11The implementation of termination is not portable because it includes
     12hand-crafted assembly statements. These sections must be ported by hand to
     13support more hardware architectures, such as the ARM processor.
     14\item
     15Due to a type-system problem, the catch clause cannot bind the exception to a
     16reference instead of a pointer. Since \CFA has a very general reference
     17capability, programmers will want to use it. Once fixed, this capability should
     18result in little or no change in the exception system.
     19\item
     20Termination handlers cannot use local control-flow transfers, \eg by @break@,
     21@return@, \etc. The reason is that current code generation hoists a handler
     22into a nested function for convenience (versus assemble-code generation at the
     23@try@ statement). Hence, when the handler runs, its code is not in the lexical
     24scope of the @try@ statement, where the local control-flow transfers are
     25meaningful.
     26\item
     27There is no detection of colliding unwinds. It is possible for clean-up code
     28run during an unwind to trigger another unwind that escapes the clean-up code
     29itself; such as a termination exception caught further down the stack or a
     30cancellation. There do exist ways to handle this but currently they are not
     31even detected and the first unwind will simply be forgotten, often leaving
     32it in a bad state.
     33\item
     34Also the exception system did not have a lot of time to be tried and tested.
     35So just letting people use the exception system more will reveal new
     36quality of life upgrades that can be made with time.
     37\end{itemize}
     38
    339\section{Complete Virtual System}
    4 The virtual system should be completed. It was never supposed to be part of
    5 this project and so minimal work was done on it. A draft of what the complete
    6 system might look like was created but it was never finalized or implemented.
    7 A future project in \CFA would be to complete that work and to update the
    8 parts of the exception system that use the current version.
     40The virtual system should be completed. It was not supposed to be part of this
     41project, but was thrust upon it to do exception inheritance; hence, only
     42minimal work was done. A draft for a complete virtual system is available but
     43it is not finalized.  A future \CFA project is to complete that work and then
     44update the exception system that uses the current version.
    945
    10 There are several improvements to the virtual system that would improve
    11 the exception traits. The biggest one is an assertion that checks that one
    12 virtual type is a child of another virtual type. This would capture many of
    13 the requirements much more precisely.
     46There are several improvements to the virtual system that would improve the
     47exception traits. The most important one is an assertion to check one virtual
     48type is a child of another. This check precisely captures many of the
     49correctness requirements.
    1450
    1551The full virtual system might also include other improvement like associated
    16 types. This is a proposed feature that would allow traits to refer to types
    17 not listed in their header. This would allow the exception traits to not
    18 refer to the virtual table type explicatly which would remove the need for
    19 the interface macros.
     52types to allow traits to refer to types not listed in their header. This
     53feature allows exception traits to not refer to the virtual-table type
     54explicitly, removing the need for the current interface macros.
    2055
    21 \section{Additional Throws}
    22 Several other kinds of throws, beyond the termination throw (@throw@),
    23 the resumption throw (@throwResume@) and the re-throws, were considered.
    24 None were as useful as the core throws but they would likely be worth
    25 revising.
     56\section{Additional Raises}
     57Several other kinds of exception raises were considered beyond termination
     58(@throw@), resumption (@throwResume@), and reraise.
    2659
    27 The first ones are throws for asynchronous exceptions, throwing exceptions
    28 from one stack to another. These act like signals allowing for communication
    29 between the stacks. This is usually used with resumption as it allows the
    30 target stack to continue execution normally after the exception has been
    31 handled.
     60The first is a non-local/concurrent raise providing asynchronous exceptions,
     61\ie raising an exception on another stack. This semantics acts like signals
     62allowing for out-of-band communication among coroutines and threads. This kind
     63of raise is often restricted to resumption to allow the target stack to
     64continue execution normally after the exception has been handled. That is,
     65allowing one coroutine/thread to unwind the stack of another via termination is
     66bad software engineering.
    3267
    33 This would much more coordination between the concurrency system and the
    34 exception system to handle. Most of the interesting design decisions around
    35 applying asynchronous exceptions appear to be around masking (controlling
    36 which exceptions may be thrown at a stack). It would likely require more of
    37 the virtual system and would also effect how default handlers are set.
     68Non-local/concurrent requires more coordination between the concurrency system
     69and the exception system. Many of the interesting design decisions centre
     70around masking (controlling which exceptions may be thrown at a stack). It
     71would likely require more of the virtual system and would also effect how
     72default handlers are set.
    3873
    39 The other throws were designed to mimic bidirectional algebraic effects.
    40 Algebraic effects are used in some functional languages and allow a function
     74Other raises were considered to mimic bidirectional algebraic effects.
     75Algebraic effects are used in some functional languages allowing one function
    4176to have another function on the stack resolve an effect (which is defined with
    42 a function-like interface).
    43 These can be mimiced with resumptions and the the new throws were designed
    44 to try and mimic bidirectional algebraic effects, where control can go back
    45 and forth between the function effect caller and handler while the effect
    46 is underway.
     77a functional-like interface).  This semantics can be mimicked with resumptions
     78and new raises were discussed to mimic bidirectional algebraic-effects, where
     79control can go back and forth between the function-effect caller and handler
     80while the effect is underway.
    4781% resume-top & resume-reply
     82These raises would be like the resumption raise except using different search
     83patterns to find the handler.
    4884
    49 These throws would likely be just like the resumption throw except they would
    50 use different search patterns to find the handler to reply to.
     85\section{Zero-Cost Try}
     86\CFA does not have zero-cost try-statements because the compiler generates C
     87code rather than assembler code \see{\VPageref{p:zero-cost}}. When the compiler
     88does create its own assembly (or LLVM byte-code), then zero-cost try-statements
     89are possible. The downside of zero-cost try-statements is the LSDA complexity,
     90its size (program bloat), and the high cost of raising an exception.
    5191
    52 \section{Zero-Cost Exceptions}
    53 \CFA does not have zero-cost exceptions because it does not generate assembly
    54 but instead generates C code. See the implementation section. When the
    55 compiler does start to create its own assembly (or LLVM byte code) then
    56 zero-cost exceptions could be implemented.
     92Alternatively, some research could be done into the simpler alternative method
     93with a non-zero-cost try-statement but much lower cost exception raise. For
     94example, programs are starting to use exception in the normal control path, so
     95more exceptions are thrown. In these cases, the cost balance switches towards
     96low-cost raise. Unfortunately, while exceptions remain exceptional, the
     97libunwind model will probably remain the most effective option.
    5798
    58 Now in zero-cost exceptions the only part that is zero-cost are the try
    59 blocks. Some research could be done into the alternative methods for systems
    60 that expect a lot more exceptions to be thrown, allowing some overhead in
    61 entering and leaving try blocks to make throws faster. But while exceptions
    62 remain exceptional the libunwind model will probably remain the most effective
    63 option.
     99Zero-cost resumptions is still an open problem. First, because libunwind does
     100not support a successful-exiting stack-search without doing an unwind.
     101Workarounds are possible but awkward. Ideally an extension to libunwind could
     102be made, but that would either require separate maintenance or gain enough
     103support to have it folded into the standard.
    64104
    65 Zero-cost resumptions have more problems to solve. First because libunwind
    66 does not support a successful exiting stack search without doing an unwind.
    67 There are several ways to hack that functionality in. Ideally an extension to
    68 libunwind could be made, but that would either require seperate maintenance
    69 or gain enough support to have it folded into the standard.
    70 
    71 Also new techniques to skip previously searched parts of the stack will have
    72 to be developed. The recursive resume problem still remains and ideally the
    73 same pattern of ignoring sections of the stack.
     105Also new techniques to skip previously searched parts of the stack need to be
     106developed to handle the recursive resume problem and support advanced algebraic
     107effects.
    74108
    75109\section{Signal Exceptions}
    76 Exception Handling: Issues and a Proposed Notation suggests there are three
    77 types of exceptions: escape, notify and signal.
    78 Escape exceptions are our termination exceptions, notify exceptions are
    79 resumption exceptions and that leaves signal exception unimplemented.
     110Goodenough~\cite{Goodenough75} suggests three types of exceptions: escape,
     111notify and signal.  Escape are termination exceptions, notify are resumption
     112exceptions, leaving signal unimplemented.
    80113
    81 Signal exceptions allow either behaviour, that is after the exception is
    82 handled control can either return to the throw or from where the handler is
    83 defined.
     114A signal exception allows either behaviour, \ie after an exception is handled,
     115the handler has the option of returning to the raise or after the @try@
     116statement. Currently, \CFA fixes the semantics of the handler return
     117syntactically by the @catch@ or @catchResume@ clause.
    84118
    85 The design should be rexamined and be updated for \CFA. A very direct
    86 translation would perhaps have a new throw and catch pair and a statement
    87 (or statements) could be used to decide if the handler returns to the throw
    88 or continues where it is, but there are other options.
     119Signal exception should be reexamined and possibly be supported in \CFA. A very
     120direct translation is to have a new raise and catch pair, and a new statement
     121(or statements) would indicate if the handler returns to the raise or continues
     122where it is; but there may be other options.
    89123
    90 For instance resumption could be extended to cover this use by allowing
    91 local control flow out of it. This would require an unwind as part of the
    92 transition as there are stack frames that have to be removed.
    93 This would mean there is no notify like throw but because \CFA does not have
    94 exception signatures a termination can be thrown from any resumption handler
    95 already so there are already ways one could try to do this in existing \CFA.
     124For instance, resumption could be extended to cover this use by allowing local
     125control flow out of it. This approach would require an unwind as part of the
     126transition as there are stack frames that have to be removed.  This approach
     127means there is no notify raise, but because \CFA does not have exception
     128signatures, a termination can be thrown from within any resumption handler so
     129there is already a way to do mimic this in existing \CFA.
    96130
    97131% Maybe talk about the escape; and escape CONTROL_STMT; statements or how
    98132% if we could choose if _Unwind_Resume proceeded to the clean-up stage this
    99133% would be much easier to implement.
    100 
    101 \section{Language Improvements}
    102 There is also a lot of work that are not follow ups to this work in terms of
    103 research, some have no interesting research to be done at all, but would
    104 improve \CFA as a programming language. The full list of these would
    105 naturally be quite extensive but here are a few examples that involve
    106 exceptions:
    107 
    108 \begin{itemize}
    109 \item The implementation of termination is not portable because it includes
    110 some assembly statements. These sections will have to be re-written to so
    111 \CFA has full support on more machines.
    112 \item Allowing exception handler to bind the exception to a reference instead
    113 of a pointer. This should actually result in no change in behaviour so there
    114 is no reason not to allow it. It is however a small improvement; giving a bit
    115 of flexibility to the user in what style they want to use.
    116 \item Enabling local control flow (by @break@, @return@ and
    117 similar statements) out of a termination handler. The current set-up makes
    118 this very difficult but the catch function that runs the handler after it has
    119 been matched could be inlined into the function's body, which would make this
    120 much easier. (To do the same for try blocks would probably wait for zero-cost
    121 exceptions, which would allow the try block to be inlined as well.)
    122 \end{itemize}
  • doc/theses/andrew_beach_MMath/implement.tex

    rc292244 ref0b456  
    22% Goes over how all the features are implemented.
    33
     4The implementation work for this thesis covers two components: the virtual
     5system and exceptions. Each component is discussed in detail.
     6
    47\section{Virtual System}
     8\label{s:VirtualSystem}
    59% Virtual table rules. Virtual tables, the pointer to them and the cast.
    6 The \CFA virtual system only has one public facing feature: virtual casts.
    7 However there is a lot of structure to support that and provide some other
    8 features for the standard library.
    9 
    10 All of this is accessed through a field inserted at the beginning of every
    11 virtual type. Currently it is called @virtual_table@ but it is not
    12 ment to be accessed by the user. This field is a pointer to the type's
    13 virtual table instance. It is assigned once during the object's construction
    14 and left alone after that.
    15 
    16 \subsection{Virtual Table Construction}
    17 For each virtual type a virtual table is constructed. This is both a new type
    18 and an instance of that type. Other instances of the type could be created
    19 but the system doesn't use them. So this section will go over the creation of
    20 the type and the instance.
    21 
    22 Creating the single instance is actually very important. The address of the
    23 table acts as the unique identifier for the virtual type. Similarly the first
    24 field in every virtual table is the parent's id; a pointer to the parent
    25 virtual table instance.
    26 
    27 The remaining fields contain the type's virtual members. First come the ones
    28 present on the parent type, in the same order as they were the parent, and
    29 then any that this type introduces. The types of the ones inherited from the
    30 parent may have a slightly modified type, in that references to the
    31 dispatched type are replaced with the current virtual type. These are always
    32 taken by pointer or reference.
    33 
    34 The structure itself is created where the virtual type is created. The name
    35 of the type is created by mangling the name of the base type. The name of the
    36 instance is also generated by name mangling.
    37 
    38 The fields are initialized automatically.
     10While the \CFA virtual system currently has only one public feature, virtual
     11cast \see{\VPageref{p:VirtualCast}}, substantial structure is required to
     12support it, and provide features for exception handling and the standard
     13library.
     14
     15\subsection{Virtual Table}
     16The virtual system is accessed through a private constant field inserted at the
     17beginning of every virtual type, called the virtual-table pointer. This field
     18points at a type's virtual table and is assigned during the object's
     19construction.  The address of a virtual table acts as the unique identifier for
     20the virtual type, and the first field of a virtual table is a pointer to the
     21parent virtual-table or @0p@.  The remaining fields are duplicated from the
     22parent tables in this type's inheritance chain, followed by any fields this type
     23introduces. Parent fields are duplicated so they can be changed (\CC
     24\lstinline[language=c++]|override|), so that references to the dispatched type
     25are replaced with the current virtual type.
     26\PAB{Can you create a simple diagram of the layout?}
     27% These are always taken by pointer or reference.
     28
     29% For each virtual type, a virtual table is constructed. This is both a new type
     30% and an instance of that type. Other instances of the type could be created
     31% but the system doesn't use them. So this section will go over the creation of
     32% the type and the instance.
     33
     34A virtual table is created when the virtual type is created. The name of the
     35type is created by mangling the name of the base type. The name of the instance
     36is also generated by name mangling.  The fields are initialized automatically.
    3937The parent field is initialized by getting the type of the parent field and
    4038using that to calculate the mangled name of the parent's virtual table type.
    4139There are two special fields that are included like normal fields but have
    4240special initialization rules: the @size@ field is the type's size and is
    43 initialized with a sizeof expression, the @align@ field is the type's
    44 alignment and uses an alignof expression. The remaining fields are resolved
    45 to a name matching the field's name and type using the normal visibility
    46 and overload resolution rules of the type system.
    47 
    48 These operations are split up into several groups depending on where they
    49 take place which can vary for monomorphic and polymorphic types. The first
    50 devision is between the declarations and the definitions. Declarations, such
    51 as a function signature or a structure's name, must always be visible but may
    52 be repeated so they go in headers. Definitions, such as function bodies and a
    53 structure's layout, don't have to be visible on use but must occur exactly
    54 once and go into source files.
    55 
     41initialized with a @sizeof@ expression, the @align@ field is the type's
     42alignment and uses an @alignof@ expression. The remaining fields are resolved
     43to a name matching the field's name and type using the normal visibility and
     44overload resolution rules of the type system.
     45
     46These operations are split up into several groups depending on where they take
     47place which varies for monomorphic and polymorphic types. The first devision is
     48between the declarations and the definitions. Declarations, such as a function
     49signature or a aggregate's name, must always be visible but may be repeated in
     50the form of forward declarations in headers. Definitions, such as function
     51bodies and a aggregate's layout, can be separately compiled but must occur
     52exactly once in a source file.
     53
     54\begin{sloppypar}
    5655The declarations include the virtual type definition and forward declarations
    5756of the virtual table instance, constructor, message function and
    58 @get_exception_vtable@. The definition includes the storage and
    59 initialization of the virtual table instance and the bodies of the three
    60 functions.
     57@get_exception_vtable@. The definition includes the storage and initialization
     58of the virtual table instance and the bodies of the three functions.
     59\end{sloppypar}
    6160
    6261Monomorphic instances put all of these two groups in one place each.
    63 
    64 Polymorphic instances also split out the core declarations and definitions
    65 from the per-instance information. The virtual table type and most of the
    66 functions are polymorphic so they are all part of the core. The virtual table
    67 instance and the @get_exception_vtable@ function.
    68 
     62Polymorphic instances also split out the core declarations and definitions from
     63the per-instance information. The virtual table type and most of the functions
     64are polymorphic so they are all part of the core. The virtual table instance
     65and the @get_exception_vtable@ function.
     66
     67\begin{sloppypar}
    6968Coroutines and threads need instances of @CoroutineCancelled@ and
    70 @ThreadCancelled@ respectively to use all of their functionality.
    71 When a new data type is declared with @coroutine@ or @thread@
    72 the forward declaration for the instance is created as well. The definition
    73 of the virtual table is created at the definition of the main function.
     69@ThreadCancelled@ respectively to use all of their functionality.  When a new
     70data type is declared with @coroutine@ or @thread@ the forward declaration for
     71the instance is created as well. The definition of the virtual table is created
     72at the definition of the main function.
     73\end{sloppypar}
    7474
    7575\subsection{Virtual Cast}
    76 Virtual casts are implemented as a function call that does the check and a
    77 old C-style cast to do the type conversion. The C-cast is just to make sure
    78 the generated code is correct so the rest of the section is about that
    79 function.
    80 
    81 The function is @__cfa__virtual_cast@ and it is implemented in the
    82 standard library. It takes a pointer to the target type's virtual table and
    83 the object pointer being cast. The function is very simple, getting the
    84 object's virtual table pointer and then checking to see if it or any of
    85 its ancestors, by using the parent pointers, are the same as the target type
    86 virtual table pointer. It does this in a simple loop.
    87 
    88 For the generated code a forward decaration of the virtual works as follows.
    89 There is a forward declaration of @__cfa__virtual_cast@ in every cfa
    90 file so it can just be used. The object argument is the expression being cast
    91 so that is just placed in the argument list.
    92 
    93 To build the target type parameter the compiler will create a mapping from
    94 concrete type-name -- so for polymorphic types the parameters are filled in
    95 -- to virtual table address. Every virtual table declaraction is added to the
    96 this table; repeats are ignored unless they have conflicting definitions.
    97 This does mean the declaractions have to be in scope, but they should usually
    98 be introduced as part of the type definition.
     76Virtual casts are implemented as a function call that does the subtype check
     77and a C coercion-cast to do the type conversion.
     78% The C-cast is just to make sure the generated code is correct so the rest of
     79% the section is about that function.
     80The function is
     81\begin{cfa}
     82void * __cfa__virtual_cast( struct __cfa__parent_vtable const * parent,
     83        struct __cfa__parent_vtable const * const * child );
     84}
     85\end{cfa}
     86and it is implemented in the standard library. It takes a pointer to the target
     87type's virtual table and the object pointer being cast. The function performs a
     88linear search starting at the object's virtual-table and walking through the
     89the parent pointers, checking to if it or any of its ancestors are the same as
     90the target-type virtual table-pointer.
     91
     92For the generated code, a forward declaration of the virtual works as follows.
     93There is a forward declaration of @__cfa__virtual_cast@ in every \CFA file so
     94it can just be used. The object argument is the expression being cast so that
     95is just placed in the argument list.
     96
     97To build the target type parameter, the compiler creates a mapping from
     98concrete type-name -- so for polymorphic types the parameters are filled in --
     99to virtual table address. Every virtual table declaration is added to the this
     100table; repeats are ignored unless they have conflicting definitions.  Note,
     101these declarations do not have to be in scope, but they should usually be
     102introduced as part of the type definition.
     103
     104\PAB{I do not understood all of \VRef{s:VirtualSystem}. I think you need to
     105write more to make it clear.}
     106
    99107
    100108\section{Exceptions}
     
    106114% resumption doesn't as well.
    107115
    108 Many modern languages work with an interal stack that function push and pop
    109 their local data to. Stack unwinding removes large sections of the stack,
    110 often across functions.
    111 
    112 At a very basic level this can be done with @setjmp@ \& @longjmp@
    113 which simply move the top of the stack, discarding everything on the stack
    114 above a certain point. However this ignores all the clean-up code that should
    115 be run when certain sections of the stack are removed (for \CFA these are from
    116 destructors and finally clauses) and also requires that the point to which the
    117 stack is being unwound is known ahead of time. libunwind is used to address
    118 both of these problems.
    119 
    120 Libunwind, provided in @unwind.h@ on most platorms, is a C library
    121 that provides \CPP style stack unwinding. Its operation is divided into two
    122 phases. The search phase -- phase 1 -- is used to scan the stack and decide
    123 where the unwinding will stop, this allows for a dynamic target. The clean-up
    124 phase -- phase 2 -- does the actual unwinding and also runs any clean-up code
    125 as it goes.
    126 
    127 To use the libunwind each function must have a personality function and an
    128 LSDA (Language Specific Data Area). Libunwind actually does very little, it
    129 simply moves down the stack from function to function. Most of the actions are
    130 implemented by the personality function which libunwind calls on every
    131 function. Since this is shared across many functions or even every function in
    132 a language it will need a bit more information. This is provided by the LSDA
    133 which has the unique information for each function.
    134 
    135 Theoretically the LSDA can contain anything but conventionally it is a table
    136 with entries reperenting areas of the function and what has to be done there
    137 during unwinding. These areas are described in terms of where the instruction
    138 pointer is. If the current value of the instruction pointer is between two
    139 values reperenting the beginning and end of a region then execution is
    140 currently being executed. These are used to mark out try blocks and the
    141 scopes of objects with destructors to run.
    142 
    143 GCC will generate an LSDA and attach its personality function with the
    144 @-fexceptions@ flag. However this only handles the cleanup attribute.
    145 This attribute is used on a variable and specifies a function that should be
    146 run when the variable goes out of scope. The function is passed a pointer to
    147 the object as well so it can be used to mimic destructors. It however cannot
    148 be used to mimic try statements.
    149 
    150 \subsection{Implementing Personality Functions}
    151 Personality functions have a complex interface specified by libunwind.
    152 This section will cover some of the important parts of that interface.
    153 
    154 \begin{lstlisting}
    155 typedef _Unwind_Reason_Code (*_Unwind_Personality_Fn)(
    156     int version,
    157     _Unwind_Action action,
    158     _Unwind_Exception_Class exception_class,
    159     _Unwind_Exception * exception,
    160     struct _Unwind_Context * context);
     116% Many modern languages work with an interal stack that function push and pop
     117% their local data to. Stack unwinding removes large sections of the stack,
     118% often across functions.
     119
     120Stack unwinding is the process of removing stack frames (activations) from the
     121stack. On function entry and return, unwinding is handled directly by the code
     122embedded in the function. Usually, the stack-frame size is known statically
     123based on parameter and local variable declarations.  For dynamically-sized
     124local variables, a runtime computation is necessary to know the frame
     125size. Finally, a function's frame-size may change during execution as local
     126variables (static or dynamic sized) go in and out of scope.
     127Allocating/deallocating stack space is usually an $O(1)$ operation achieved by
     128bumping the hardware stack-pointer up or down as needed.
     129
     130Unwinding across multiple stack frames is more complex because individual stack
     131management code associated with each frame is bypassed. That is, the location
     132of a function's frame-management code is largely unknown and dispersed
     133throughout the function, hence the current frame size managed by that code is
     134also unknown. Hence, code unwinding across frames does not have direct
     135knowledge about what is on the stack, and hence, how much of the stack needs to
     136be removed.
     137
     138% At a very basic level this can be done with @setjmp@ \& @longjmp@ which simply
     139% move the top of the stack, discarding everything on the stack above a certain
     140% point. However this ignores all the cleanup code that should be run when
     141% certain sections of the stack are removed (for \CFA these are from destructors
     142% and finally clauses) and also requires that the point to which the stack is
     143% being unwound is known ahead of time. libunwind is used to address both of
     144% these problems.
     145
     146The traditional unwinding mechanism for C is implemented by saving a snap-shot
     147of a function's state with @setjmp@ and restoring that snap-shot with
     148@longjmp@. This approach bypasses the need to know stack details by simply
     149reseting to a snap-shot of an arbitrary but existing function frame on the
     150stack. It is up to the programmer to ensure the snap-shot is valid when it is
     151reset, making this unwinding approach fragile with potential errors that are
     152difficult to debug because the stack becomes corrupted.
     153
     154However, many languages define cleanup actions that must be taken when objects
     155are deallocated from the stack or blocks end, such as running a variable's
     156destructor or a @try@ statement's @finally@ clause. Handling these mechanisms
     157requires walking the stack and checking each stack frame for these potential
     158actions.
     159
     160For exceptions, it must be possible to walk the stack frames in search of @try@
     161statements to match and execute a handler. For termination exceptions, it must
     162also be possible to unwind all stack frames from the throw to the matching
     163catch, and each of these frames must be checked for cleanup actions. Stack
     164walking is where most of the complexity and expense of exception handling
     165appears.
     166
     167One of the most popular tools for stack management is libunwind, a low-level
     168library that provides tools for stack walking, handler execution, and
     169unwinding. What follows is an overview of all the relevant features of
     170libunwind needed for this work, and how \CFA uses them to implement exception
     171handling.
     172
     173\subsection{libunwind Usage}
     174Libunwind, accessed through @unwind.h@ on most platforms, is a C library that
     175provides \CC-style stack-unwinding. Its operation is divided into two phases:
     176search and cleanup. The dynamic target search -- phase 1 -- is used to scan the
     177stack and decide where unwinding should stop (but no unwinding occurs). The
     178cleanup -- phase 2 -- does the unwinding and also runs any cleanup code.
     179
     180To use libunwind, each function must have a personality function and a Language
     181Specific Data Area (LSDA).  The LSDA has the unique information for each
     182function to tell the personality function where a function is executing, its
     183current stack frame, and what handlers should be checked.  Theoretically, the
     184LSDA can contain any information but conventionally it is a table with entries
     185representing regions of the function and what has to be done there during
     186unwinding. These regions are bracketed by the instruction pointer. If the
     187instruction pointer is within a region's start/end, then execution is currently
     188executing in that region. Regions are used to mark out the scopes of objects
     189with destructors and try blocks.
     190
     191% Libunwind actually does very little, it simply moves down the stack from
     192% function to function. Most of the actions are implemented by the personality
     193% function which libunwind calls on every function. Since this is shared across
     194% many functions or even every function in a language it will need a bit more
     195% information.
     196
     197The GCC compilation flag @-fexceptions@ causes the generation of an LSDA and
     198attaches its personality function. \PAB{to what is it attached?}  However, this
     199flag only handles the cleanup attribute
     200\begin{cfa}
     201void clean_up( int * var ) { ... }
     202int avar __attribute__(( __cleanup(clean_up) ));
     203\end{cfa}
     204which is used on a variable and specifies a function, \eg @clean_up@, run when
     205the variable goes out of scope. The function is passed a pointer to the object
     206so it can be used to mimic destructors. However, this feature cannot be used to
     207mimic @try@ statements.
     208
     209\subsection{Personality Functions}
     210Personality functions have a complex interface specified by libunwind.  This
     211section covers some of the important parts of the interface.
     212
     213A personality function performs four tasks, although not all have to be
     214present.
     215\begin{lstlisting}[language=C,{moredelim=**[is][\color{red}]{@}{@}}]
     216typedef _Unwind_Reason_Code (*@_Unwind_Personality_Fn@) (
     217        _Unwind_Action @action@,
     218        _Unwind_Exception_Class @exception_class@,
     219        _Unwind_Exception * @exception@,
     220        struct _Unwind_Context * @context@
     221);
    161222\end{lstlisting}
    162 
    163 The return value, the reason code, is an enumeration of possible messages
     223The @action@ argument is a bitmask of possible actions:
     224\begin{enumerate}
     225\item
     226@_UA_SEARCH_PHASE@ specifies a search phase and tells the personality function
     227to check for handlers.  If there is a handler in a stack frame, as defined by
     228the language, the personality function returns @_URC_HANDLER_FOUND@; otherwise
     229it return @_URC_CONTINUE_UNWIND@.
     230
     231\item
     232@_UA_CLEANUP_PHASE@ specifies a cleanup phase, where the entire frame is
     233unwound and all cleanup code is run. The personality function does whatever
     234cleanup the language defines (such as running destructors/finalizers) and then
     235generally returns @_URC_CONTINUE_UNWIND@.
     236
     237\item
     238\begin{sloppypar}
     239@_UA_HANDLER_FRAME@ specifies a cleanup phase on a function frame that found a
     240handler. The personality function must prepare to return to normal code
     241execution and return @_URC_INSTALL_CONTEXT@.
     242\end{sloppypar}
     243
     244\item
     245@_UA_FORCE_UNWIND@ specifies a forced unwind call. Forced unwind only performs
     246the cleanup phase and uses a different means to decide when to stop
     247\see{\VRef{s:ForcedUnwind}}.
     248\end{enumerate}
     249
     250The @exception_class@ argument is a copy of the
     251\lstinline[language=C]|exception|'s @exception_class@ field.
     252
     253The \lstinline[language=C]|exception| argument is a pointer to the user
     254provided storage object. It has two public fields, the exception class, which
     255is actually just a number, identifying the exception handling mechanism that
     256created it, and the cleanup function. The cleanup function is called if
     257required by the exception.
     258
     259The @context@ argument is a pointer to an opaque type passed to helper
     260functions called inside the personality function.
     261
     262The return value, @_Unwind_Reason_Code@, is an enumeration of possible messages
    164263that can be passed several places in libunwind. It includes a number of
    165264messages for special cases (some of which should never be used by the
     
    167266personality function should always return @_URC_CONTINUE_UNWIND@.
    168267
    169 The @version@ argument is the verson of the implementation that is
    170 calling the personality function. At this point it appears to always be 1 and
    171 it will likely stay that way until a new version of the API is updated.
    172 
    173 The @action@ argument is set of flags that tell the personality
    174 function when it is being called and what it must do on this invocation.
    175 The flags are as follows:
    176 \begin{itemize}
    177 \item@_UA_SEARCH_PHASE@: This flag is set whenever the personality
    178 function is called during the search phase. The personality function should
    179 decide if unwinding will stop in this function or not. If it does then the
    180 personality function should return @_URC_HANDLER_FOUND@.
    181 \item@_UA_CLEANUP_PHASE@: This flag is set whenever the personality
    182 function is called during the cleanup phase. If no other flags are set this
    183 means the entire frame will be unwound and all cleanup code should be run.
    184 \item@_UA_HANDLER_FRAME@: This flag is set during the cleanup phase
    185 on the function frame that found the handler. The personality function must
    186 prepare to return to normal code execution and return
    187 @_URC_INSTALL_CONTEXT@.
    188 \item@_UA_FORCE_UNWIND@: This flag is set if the personality function
    189 is called through a forced unwind call. Forced unwind only performs the
    190 cleanup phase and uses a different means to decide when to stop. See its
    191 section below.
    192 \end{itemize}
    193 
    194 The @exception_class@ argument is a copy of the @exception@'s
    195 @exception_class@ field.
    196 
    197 The @exception@ argument is a pointer to the user provided storage
    198 object. It has two public fields, the exception class which is actually just
    199 a number that identifies the exception handling mechanism that created it and
    200 the other is the clean-up function. The clean-up function is called if the
    201 exception needs to
    202 
    203 The @context@ argument is a pointer to an opaque type. This is passed
    204 to the many helper functions that can be called inside the personality
    205 function.
    206 
    207268\subsection{Raise Exception}
    208 This could be considered the central function of libunwind. It preforms the
    209 two staged unwinding the library is built around and most of the rest of the
    210 interface of libunwind is here to support it. It's signature is as follows:
    211 
    212 \begin{lstlisting}
     269Raising an exception is the central function of libunwind and it performs a
     270two-staged unwinding.
     271\begin{cfa}
    213272_Unwind_Reason_Code _Unwind_RaiseException(_Unwind_Exception *);
     273\end{cfa}
     274First, the function begins the search phase, calling the personality function
     275of the most recent stack frame. It continues to call personality functions
     276traversing the stack from newest to oldest until a function finds a handler or
     277the end of the stack is reached. In the latter case, raise exception returns
     278@_URC_END_OF_STACK@.
     279
     280Second, when a handler is matched, raise exception continues onto the cleanup
     281phase.
     282Once again, it calls the personality functions of each stack frame from newest
     283to oldest. This pass stops at the stack frame containing the matching handler.
     284If that personality function has not install a handler, it is an error.
     285
     286If an error is encountered, raise exception returns either
     287@_URC_FATAL_PHASE1_ERROR@ or @_URC_FATAL_PHASE2_ERROR@ depending on when the
     288error occurred.
     289
     290\subsection{Forced Unwind}
     291\label{s:ForcedUnwind}
     292Forced Unwind is the other central function in libunwind.
     293\begin{cfa}
     294_Unwind_Reason_Code _Unwind_ForcedUnwind( _Unwind_Exception *,
     295        _Unwind_Stop_Fn, void *);
     296\end{cfa}
     297It also unwinds the stack but it does not use the search phase. Instead another
     298function, the stop function, is used to stop searching.  The exception is the
     299same as the one passed to raise exception. The extra arguments are the stop
     300function and the stop parameter. The stop function has a similar interface as a
     301personality function, except it is also passed the stop parameter.
     302\begin{lstlisting}[language=C,{moredelim=**[is][\color{red}]{@}{@}}]
     303typedef _Unwind_Reason_Code (*@_Unwind_Stop_Fn@)(
     304        _Unwind_Action @action@,
     305        _Unwind_Exception_Class @exception_class@,
     306        _Unwind_Exception * @exception@,
     307        struct _Unwind_Context * @context@,
     308        void * @stop_parameter@);
    214309\end{lstlisting}
    215310
    216 When called the function begins the search phase, calling the personality
    217 function of the most recent stack frame. It will continue to call personality
    218 functions traversing the stack new-to-old until a function finds a handler or
    219 the end of the stack is reached. In the latter case raise exception will
    220 return with @_URC_END_OF_STACK@.
    221 
    222 Once a handler has been found raise exception continues onto the the cleanup
    223 phase. Once again it will call the personality functins of each stack frame
    224 from newest to oldest. This pass will stop at the stack frame that found the
    225 handler last time, if that personality function does not install the handler
    226 it is an error.
    227 
    228 If an error is encountered raise exception will return either
    229 @_URC_FATAL_PHASE1_ERROR@ or @_URC_FATAL_PHASE2_ERROR@ depending
    230 on when the error occured.
    231 
    232 \subsection{Forced Unwind}
    233 This is the second big function in libunwind. It also unwinds a stack but it
    234 does not use the search phase. Instead another function, the stop function,
    235 is used to decide when to stop.
    236 
    237 \begin{lstlisting}
    238 _Unwind_Reason_Code _Unwind_ForcedUnwind(
    239     _Unwind_Exception *, _Unwind_Stop_Fn, void *);
    240 \end{lstlisting}
    241 
    242 The exception is the same as the one passed to raise exception. The extra
    243 arguments are the stop function and the stop parameter. The stop function has
    244 a similar interface as a personality function, except it is also passed the
    245 stop parameter.
    246 
    247 \begin{lstlisting}
    248 typedef _Unwind_Reason_Code (*_Unwind_Stop_Fn)(
    249     int version,
    250     _Unwind_Action action,
    251     _Unwind_Exception_Class exception_class,
    252     _Unwind_Exception * exception,
    253     struct _Unwind_Context * context,
    254     void * stop_parameter);
    255 \end{lstlisting}
    256 
    257311The stop function is called at every stack frame before the personality
    258 function is called and then once more once after all frames of the stack have
    259 been unwound.
    260 
    261 Each time it is called the stop function should return @_URC_NO_REASON@
    262 or transfer control directly to other code outside of libunwind. The
    263 framework does not provide any assistance here.
    264 
    265 Its arguments are the same as the paired personality function.
    266 The actions @_UA_CLEANUP_PHASE@ and @_UA_FORCE_UNWIND@ are always
    267 set when it is called. By the official standard that is all but both GCC and
    268 Clang add an extra action on the last call at the end of the stack:
    269 @_UA_END_OF_STACK@.
     312function is called and then once more after all frames of the stack are
     313unwound.
     314
     315Each time it is called, the stop function should return @_URC_NO_REASON@ or
     316transfer control directly to other code outside of libunwind. The framework
     317does not provide any assistance here.
     318
     319\begin{sloppypar}
     320Its arguments are the same as the paired personality function.  The actions
     321@_UA_CLEANUP_PHASE@ and @_UA_FORCE_UNWIND@ are always set when it is
     322called. Beyond the libunwind standard, both GCC and Clang add an extra action
     323on the last call at the end of the stack: @_UA_END_OF_STACK@.
     324\end{sloppypar}
    270325
    271326\section{Exception Context}
    272327% Should I have another independent section?
    273328% There are only two things in it, top_resume and current_exception. How it is
    274 % stored changes depending on wheither or not the thread-library is linked.
    275 
    276 The exception context is a piece of global storage used to maintain data
    277 across different exception operations and to communicate between different
    278 components.
    279 
    280 Each stack has its own exception context. In a purely sequental program, using
    281 only core Cforall, there is only one stack and the context is global. However
    282 if the library @libcfathread@ is linked then there can be multiple
    283 stacks so they will each need their own.
    284 
    285 To handle this code always gets the exception context from the function
    286 @this_exception_context@. The main exception handling code is in
    287 @libcfa@ and that library also defines the function as a weak symbol
    288 so it acts as a default. Meanwhile in @libcfathread@ the function is
    289 defined as a strong symbol that replaces it when the libraries are linked
    290 together.
    291 
    292 The version of the function defined in @libcfa@ is very simple. It
    293 returns a pointer to a global static variable. With only one stack this
    294 global instance is associated with the only stack.
    295 
    296 The version of the function defined in @libcfathread@ has to handle
    297 more as there are multiple stacks. The exception context is included as
    298 part of the per-stack data stored as part of coroutines. In the cold data
    299 section, stored at the base of each stack, is the exception context for that
    300 stack. The @this_exception_context@ uses the concurrency library to get
    301 the current coroutine and through it the cold data section and the exception
    302 context.
     329% stored changes depending on whether or not the thread-library is linked.
     330
     331The exception context is global storage used to maintain data across different
     332exception operations and to communicate among different components.
     333
     334Each stack must have its own exception context. In a sequential \CFA program,
     335there is only one stack with a single global exception-context. However, when
     336the library @libcfathread@ is linked, there are multiple stacks where each
     337needs its own exception context.
     338
     339General access to the exception context is provided by function
     340@this_exception_context@. For sequential execution, this function is defined as
     341a weak symbol in the \CFA system-library, @libcfa@. When a \CFA program is
     342concurrent, it links with @libcfathread@, where this function is defined with a
     343strong symbol replacing the sequential version.
     344
     345% The version of the function defined in @libcfa@ is very simple. It returns a
     346% pointer to a global static variable. With only one stack this global instance
     347% is associated with the only stack.
     348
     349For coroutines, @this_exception_context@ accesses the exception context stored
     350at the base of the stack. For threads, @this_exception_context@ uses the
     351concurrency library to access the current stack of the thread or coroutine
     352being executed by the thread, and then accesses the exception context stored at
     353the base of this stack.
    303354
    304355\section{Termination}
     
    306357% catches. Talk about GCC nested functions.
    307358
    308 Termination exceptions use libunwind quite heavily because it matches the
    309 intended use from \CPP exceptions very closely. The main complication is that
    310 since the \CFA compiler works by translating to C code it cannot generate the
    311 assembly to form the LSDA for try blocks or destructors.
     359Termination exceptions use libunwind heavily because it matches the intended
     360use from \CC exceptions closely. The main complication for \CFA is that the
     361compiler generates C code, making it very difficult to generate the assembly to
     362form the LSDA for try blocks or destructors.
    312363
    313364\subsection{Memory Management}
    314 The first step of termination is to copy the exception into memory managed by
    315 the exception system. Currently the system just uses malloc, without reserved
    316 memory or and ``small allocation" optimizations. The exception handling
    317 mechanism manages memory for the exception as well as memory for libunwind
    318 and the system's own per-exception storage.
    319 
    320 Exceptions are stored in variable sized block. The first component is a fixed
    321 sized data structure that contains the information for libunwind and the
    322 exception system. The second component is a blob of memory that is big enough
    323 to store the exception. Macros with pointer arthritic and type cast are
    324 used to move between the components or go from the embedded
     365The first step of a termination raise is to copy the exception into memory
     366managed by the exception system. Currently, the system uses @malloc@, rather
     367than reserved memory or the stack top. The exception handling mechanism manages
     368memory for the exception as well as memory for libunwind and the system's own
     369per-exception storage.
     370
     371Exceptions are stored in variable-sized blocks. \PAB{Show a memory layout
     372figure.} The first component is a fixed sized data structure that contains the
     373information for libunwind and the exception system. The second component is an
     374area of memory big enough to store the exception. Macros with pointer arthritic
     375and type cast are used to move between the components or go from the embedded
    325376@_Unwind_Exception@ to the entire node.
    326377
    327 All of these nodes are strung together in a linked list. One linked list per
    328 stack, with the head stored in the exception context. Within each linked list
    329 the most recently thrown exception is at the head and the older exceptions
    330 are further down the list. This list format allows exceptions to be thrown
    331 while a different exception is being handled. Only the exception at the head
    332 of the list is currently being handled, the other will wait for the
    333 exceptions before them to be removed.
    334 
    335 The virtual members in the exception's virtual table. The size of the
    336 exception, the copy function and the free function are all in the virtual
    337 table so they are decided per-exception type. The size and copy function are
    338 used right away when the exception is copied in to managed memory. After the
    339 exception is handled the free function is used to clean up the exception and
    340 then the entire node is passed to free.
    341 
    342 \subsection{Try Statements \& Catch Clauses}
    343 The try statements with termination handlers have a pretty complex conversion
    344 to compensate for the lack of assembly generation. Libunwind requires an LSDA
    345 (Language Specific Data Area) and personality function for a function to
    346 unwind across it. The LSDA in particular is hard to generate at the level of
    347 C which is what the \CFA compiler outputs so a work-around is used.
    348 
    349 This work around is a function called @__cfaehm_try_terminate@ in the
    350 standard library. The contents of a try block and the termination handlers
    351 are converted into functions. These are then passed to the try terminate
    352 function and it calls them. This puts the try statements in their own
    353 functions so that no function has to deal with both termination handlers and
    354 destructors.
    355 
    356 This function has some custom embedded assembly that defines its personality
    357 function and LSDA. This is hand coded in C which is why there is only one
    358 version of it, the compiler has no capability to generate it. The personality
    359 function is structured so that it may be expanded, but really it only handles
    360 this one function. Notably it does not handle any destructors so the function
    361 is constructed so that it does need to run it.
     378All of these nodes are linked together in a list, one list per stack, with the
     379list head stored in the exception context. Within each linked list, the most
     380recently thrown exception is at the head followed by older thrown
     381exceptions. This format allows exceptions to be thrown, while a different
     382exception is being handled. The exception at the head of the list is currently
     383being handled, while other exceptions wait for the exceptions before them to be
     384removed.
     385
     386The virtual members in the exception's virtual table provide the size of the
     387exception, the copy function, and the free function, so they are specific to an
     388exception type. The size and copy function are used immediately to copy an
     389exception into managed memory. After the exception is handled the free function
     390is used to clean up the exception and then the entire node is passed to free.
     391
     392\subsection{Try Statements and Catch Clauses}
     393The try statement with termination handlers is complex because it must
     394compensate for the lack of assembly-code generated from \CFA. Libunwind
     395requires an LSDA and personality function for control to unwind across a
     396function. The LSDA in particular is hard to mimic in generated C code.
     397
     398The workaround is a function called @__cfaehm_try_terminate@ in the standard
     399library. The contents of a try block and the termination handlers are converted
     400into functions. These are then passed to the try terminate function and it
     401calls them. This approach puts a try statement in its own functions so that no
     402function has to deal with both termination handlers and destructors. \PAB{I do
     403not understand the previous sentence.}
     404
     405This function has some custom embedded assembly that defines \emph{its}
     406personality function and LSDA. The assembly is created with handcrafted C @asm@
     407statements, which is why there is only one version of it. The personality
     408function is structured so that it can be expanded, but currently it only
     409handles this one function.  Notably, it does not handle any destructors so the
     410function is constructed so that it does need to run it. \PAB{I do not
     411understand the previous sentence.}
    362412
    363413The three functions passed to try terminate are:
    364 \begin{itemize}
    365 \item The try function: This function is the try block, all the code inside
    366 the try block is placed inside the try function. It takes no parameters and
    367 has no return value. This function is called during regular execution to run
    368 the try block.
    369 \item The match function: This function decides if this try statement should
    370 handle any given termination exception. It takes a pointer to the exception
    371 and returns 0 if the exception is not handled here. Otherwise the return value
    372 is the id of the handler that should handle the exception. It is called
    373 during the search phase.
    374 It is constructed from the conditional part of each handler. It runs each
    375 check in turn, first checking to see if the object
    376 \item The catch function: This function handles the exception. It takes a
    377 pointer to the exception and the handler's id and returns nothing. It is
    378 called after the clean-up phase.
    379 It is constructed by stitching together the bodies of each handler
    380 \end{itemize}
    381 All three are created with GCC nested functions. GCC nested functions can be
    382 used to create closures, functions that can refer to the state of other
    383 functions on the stack. This allows the functions to refer to the main
    384 function and all the variables in scope.
    385 
    386 These nested functions and all other functions besides
    387 @__cfaehm_try_terminate@ in \CFA use the GCC personality function and
    388 the @-fexceptions@ flag to generate the LSDA. This allows destructors
    389 to be implemented with the cleanup attribute.
     414\begin{description}
     415\item[try function:] This function is the try block, all the code inside the
     416try block is placed inside the try function. It takes no parameters and has no
     417return value. This function is called during regular execution to run the try
     418block.
     419
     420\item[match function:] This function is called during the search phase and
     421decides if a catch clause matches the termination exception.  It is constructed
     422from the conditional part of each handler and runs each check, top to bottom,
     423in turn, first checking to see if the exception type matches and then if the
     424condition is true. It takes a pointer to the exception and returns 0 if the
     425exception is not handled here. Otherwise the return value is the id of the
     426handler that matches the exception.
     427
     428\item[handler function:] This function handles the exception. It takes a
     429pointer to the exception and the handler's id and returns nothing. It is called
     430after the cleanup phase.  It is constructed by stitching together the bodies of
     431each handler and dispatches to the selected handler.
     432\end{description}
     433All three functions are created with GCC nested functions. GCC nested functions
     434can be used to create closures, functions that can refer to the state of other
     435functions on the stack. This approach allows the functions to refer to all the
     436variables in scope for the function containing the @try@ statement.  These
     437nested functions and all other functions besides @__cfaehm_try_terminate@ in
     438\CFA use the GCC personality function and the @-fexceptions@ flag to generate
     439the LSDA. This allows destructors to be implemented with the cleanup attribute.
    390440
    391441\section{Resumption}
    392442% The stack-local data, the linked list of nodes.
    393443
    394 Resumption uses a list of nodes for its stack traversal. The head of the list
    395 is stored in the exception context. The nodes in the list just have a pointer
     444Resumption simple to implement because there is no stack unwinding. The
     445resumption raise uses a list of nodes for its stack traversal. The head of the
     446list is stored in the exception context. The nodes in the list have a pointer
    396447to the next node and a pointer to the handler function.
    397448
    398 The on a resumption throw the this list is traversed. At each node the
    399 handler function is called and is passed the exception by pointer. It returns
    400 true if the exception was handled and false otherwise.
    401 
    402 The handler function does both the matching and catching. It tries each
    403 the condition of @catchResume@ in order, top-to-bottom and until it
    404 finds a handler that matches. If no handler matches then the function returns
    405 false. Otherwise the matching handler is run, if it completes successfully
    406 the function returns true. Rethrows, through the @throwResume;@
    407 statement, cause the function to return true.
     449A resumption raise traverses this list. At each node the handler function is
     450called, passing the exception by pointer. It returns true if the exception is
     451handled and false otherwise.
     452
     453The handler function does both the matching and handling. It computes the
     454condition of each @catchResume@ in top-to-bottom order, until it finds a
     455handler that matches. If no handler matches then the function returns
     456false. Otherwise the matching handler is run; if it completes successfully, the
     457function returns true. Reresume, through the @throwResume;@ statement, cause
     458the function to return true.
    408459
    409460% Recursive Resumption Stuff:
    410 Blocking out part of the stack is accomplished by updating the front of the
    411 list as the search continues. Before the handler at a node is called the head
    412 of the list is updated to the next node of the current node. After the search
    413 is complete, successful or not, the head of the list is reset.
    414 
    415 This means the current handler and every handler that has already been
    416 checked are not on the list while a handler is run. If a resumption is thrown
    417 during the handling of another resumption the active handlers and all the
    418 other handler checked up to this point will not be checked again.
     461Search skipping \see{\VPageref{p:searchskip}}, which ignores parts of the stack
     462already examined, is accomplished by updating the front of the list as the
     463search continues. Before the handler at a node is called the head of the list
     464is updated to the next node of the current node. After the search is complete,
     465successful or not, the head of the list is reset.
     466
     467This mechanism means the current handler and every handler that has already
     468been checked are not on the list while a handler is run. If a resumption is
     469thrown during the handling of another resumption the active handlers and all
     470the other handler checked up to this point are not checked again.
    419471
    420472This structure also supports new handler added while the resumption is being
    421473handled. These are added to the front of the list, pointing back along the
    422 stack -- the first one will point over all the checked handlers -- and the
    423 ordering is maintained.
    424 
    425 \subsection{Libunwind Compatibility}
    426 Resumption does not use libunwind for two simple reasons. The first is that
    427 it does not have to unwind anything so would never need to use the clean-up
    428 phase. Still the search phase could be used to make it free to enter or exit
    429 a try statement with resumption handlers in the same way termination handlers
    430 are for the same trade off in the cost of the throw. This is where the second
    431 reason comes in, there is no way to return from a search without installing
    432 a handler or raising an error.
    433 
    434 Although work arounds could be created none seemed to be worth it for the
    435 prototype. This implementation has no difference in behaviour and is much
    436 simpler.
     474stack -- the first one points over all the checked handlers -- and the ordering
     475is maintained.
     476
     477\label{p:zero-cost}
     478Note, the resumption implementation has a cost for entering/exiting a @try@
     479statement with @catchResume@ clauses, whereas a @try@ statement with @catch@
     480clauses has zero-cost entry/exit. While resumption does not need the stack
     481unwinding and cleanup provided by libunwind, it could use the search phase to
     482providing zero-cost enter/exit using the LSDA. Unfortunately, there is no way
     483to return from a libunwind search without installing a handler or raising an
     484error.  Although workarounds might be possible, they are beyond the scope of
     485this thesis. The current resumption implementation has simplicity in its
     486favour.
    437487% Seriously, just compare the size of the two chapters and then consider
    438488% that unwind is required knowledge for that chapter.
     
    440490\section{Finally}
    441491% Uses destructors and GCC nested functions.
    442 Finally clauses are a simple decomposition to some of the existing features.
    443 The code in the block is placed into a GCC nested function with a unique name,
    444 no arguments or return values. This nested function is then set as the
    445 clean-up function of an empty object that is declared at the beginning of a
    446 block placed around the contexts of the try statement.
     492Finally clauses is placed into a GCC nested-function with a unique name, and no
     493arguments or return values. This nested function is then set as the cleanup
     494function of an empty object that is declared at the beginning of a block placed
     495around the context of the associated @try@ statement.
    447496
    448497The rest is handled by GCC. The try block and all handlers are inside the
    449 block. When they are complete control exits the block and the empty object
    450 is cleaned up, which runs the function that contains the finally code.
     498block. At completion, control exits the block and the empty object is cleaned
     499up, which runs the function that contains the finally code.
    451500
    452501\section{Cancellation}
     
    454503
    455504Cancellation also uses libunwind to do its stack traversal and unwinding,
    456 however it uses a different primary function @_Unwind_ForcedUnwind@.
    457 Details of its interface can be found in the unwind section.
    458 
    459 The first step of cancellation is to find the stack was cancelled and which
    460 type of stack it is. Luckily the threads library stores the main thread
    461 pointer and the current thread pointer and every thread stores a pointer to
     505however it uses a different primary function @_Unwind_ForcedUnwind@.  Details
     506of its interface can be found in the \VRef{s:ForcedUnwind}.
     507
     508The first step of cancellation is to find the cancelled stack and its type:
     509coroutine or thread. Fortunately, the thread library stores the main thread
     510pointer and the current thread pointer, and every thread stores a pointer to
    462511its main coroutine and the coroutine it is currently executing.
    463512
    464 So if the the current thread's main and current coroutine do not match, it is
    465 a coroutine cancellation. Otherwise if the main and current thread do not
    466 match, it is a thread cancellation. Otherwise it is a main thread
    467 cancellation.
    468 
    469 However if the threading library is not linked then execution must be on the
    470 main stack as that is the only one that exists. So the entire check is skipped
    471 using the linker and weak symbols. Instead the main thread cancellation is
    472 unconditionally preformed.
    473 
    474 Regardless of how they are choosen afterwords the stop function and the stop
    475 parameter are passed to the forced unwind functon. The general pattern of all
    476 three stop functions is the same, they continue unwinding until the end of
    477 stack when they do there primary work.
    478 
    479 Main stack cancellation it is very simple. The ``transfer" is just an abort,
    480 the program stops executing.
    481 
    482 The coroutine cancellation stores the exception on the coroutine and then
    483 does a coroutine context switch. The rest is handled inside resume. Every time
    484 control returns from a resumed thread there is a check to see if it is
    485 cancelled. If it is the exception is retrieved and the CoroutineCancelled
    486 exception is constructed and loaded. It is then thrown as a regular exception
    487 with the default handler coming from the context of the resumption call.
    488 
    489 The thread cancellation stores the exception on the thread's main stack and
    490 then returns to the scheduler. The rest is handled by the joiner. The wait
    491 for the joined thread to finish works the same but after that it checks
    492 to see if there was a cancellation. If there was the exception is retrieved
    493 and the ThreadCancelled exception is constructed. The default handler is
    494 passed in as a function pointer. If it is null (as it is for the
    495 auto-generated joins on destructor call) it a default is used that simply
    496 calls abort; which gives the required handling on implicate join.
     513The first check is if the current thread's main and current coroutine do not
     514match, implying a coroutine cancellation; otherwise, it is a thread
     515cancellation. Otherwise it is a main thread cancellation. \PAB{Previous
     516sentence does not make sense.}
     517
     518However, if the threading library is not linked, the sequential execution is on
     519the main stack. Hence, the entire check is skipped because the weak-symbol
     520function is loaded. Therefore, a main thread cancellation is unconditionally
     521performed.
     522
     523Regardless of how the stack is chosen, the stop function and parameter are
     524passed to the forced-unwind function. The general pattern of all three stop
     525functions is the same: they continue unwinding until the end of stack when they
     526do there primary work.
     527
     528For main stack cancellation, the transfer is just a program abort.
     529
     530For coroutine cancellation, the exception is stored on the coroutine's stack,
     531and the coroutine context switches to its last resumer. The rest is handled on
     532the backside of the resume, which check if the resumed coroutine is
     533cancelled. If cancelled, the exception is retrieved from the resumed coroutine,
     534and a @CoroutineCancelled@ exception is constructed and loaded with the
     535cancelled exception. It is then resumed as a regular exception with the default
     536handler coming from the context of the resumption call.
     537
     538For thread cancellation, the exception is stored on the thread's main stack and
     539then context switched to the scheduler. The rest is handled by the thread
     540joiner. When the join is complete, the joiner checks if the joined thread is
     541cancelled. If cancelled, the exception is retrieved and the joined thread, and
     542a @ThreadCancelled@ exception is constructed and loaded with the cancelled
     543exception. The default handler is passed in as a function pointer. If it is
     544null (as it is for the auto-generated joins on destructor call), the default is
     545used, which is a program abort.
     546%; which gives the required handling on implicate join.
  • doc/theses/andrew_beach_MMath/thesis-frontpgs.tex

    rc292244 ref0b456  
    3636
    3737        A thesis \\
    38         presented to the University of Waterloo \\ 
     38        presented to the University of Waterloo \\
    3939        in fulfillment of the \\
    4040        thesis requirement for the degree of \\
     
    6464\cleardoublepage
    6565
    66  
     66
    6767%----------------------------------------------------------------------
    6868% EXAMINING COMMITTEE (Required for Ph.D. theses only)
     
    7171\begin{center}\textbf{Examining Committee Membership}\end{center}
    7272  \noindent
    73 The following served on the Examining Committee for this thesis. The decision of the Examining Committee is by majority vote.
    74   \bigskip
    75  
    76   \noindent
    77 \begin{tabbing}
    78 Internal-External Member: \=  \kill % using longest text to define tab length
    79 External Examiner: \>  Bruce Bruce \\
     73The following served on the Examining Committee for this thesis. The decision
     74of the Examining Committee is by majority vote.
     75  \bigskip
     76
     77  \noindent
     78\begin{tabbing}
     79Internal-External Member: \=  \kill % using longest text to define tab length
     80External Examiner: \>  Bruce Bruce \\
    8081\> Professor, Dept. of Philosophy of Zoology, University of Wallamaloo \\
    81 \end{tabbing} 
    82   \bigskip
    83  
     82\end{tabbing}
     83  \bigskip
     84
    8485  \noindent
    8586\begin{tabbing}
     
    9192\end{tabbing}
    9293  \bigskip
    93  
     94
    9495  \noindent
    9596  \begin{tabbing}
     
    99100\end{tabbing}
    100101  \bigskip
    101  
     102
    102103  \noindent
    103104\begin{tabbing}
     
    107108\end{tabbing}
    108109  \bigskip
    109  
     110
    110111  \noindent
    111112\begin{tabbing}
     
    123124  % December 13th, 2006.  It is designed for an electronic thesis.
    124125  \noindent
    125 I hereby declare that I am the sole author of this thesis. This is a true copy of the thesis, including any required final revisions, as accepted by my examiners.
    126 
    127   \bigskip
    128  
     126I hereby declare that I am the sole author of this thesis. This is a true copy
     127of the thesis, including any required final revisions, as accepted by my
     128examiners.
     129
     130  \bigskip
     131
    129132  \noindent
    130133I understand that my thesis may be made electronically available to the public.
  • doc/theses/andrew_beach_MMath/thesis.tex

    rc292244 ref0b456  
    4545% FRONT MATERIAL
    4646%----------------------------------------------------------------------
    47 \input{thesis-frontpgs} 
     47\input{thesis-frontpgs}
    4848
    4949%----------------------------------------------------------------------
     
    6565A \gls{computer} could compute $\pi$ all day long. In fact, subsets of digits
    6666of $\pi$'s decimal approximation would make a good source for psuedo-random
    67 vectors, \gls{rvec} . 
     67vectors, \gls{rvec} .
    6868
    6969%----------------------------------------------------------------------
     
    9696
    9797\begin{itemize}
    98 \item A well-prepared PDF should be 
     98\item A well-prepared PDF should be
    9999  \begin{enumerate}
    100100    \item Of reasonable size, {\it i.e.} photos cropped and compressed.
    101     \item Scalable, to allow enlargment of text and drawings. 
    102   \end{enumerate} 
     101    \item Scalable, to allow enlargment of text and drawings.
     102  \end{enumerate}
    103103\item Photos must be bit maps, and so are not scaleable by definition. TIFF and
    104104BMP are uncompressed formats, while JPEG is compressed. Most photos can be
    105105compressed without losing their illustrative value.
    106 \item Drawings that you make should be scalable vector graphics, \emph{not} 
     106\item Drawings that you make should be scalable vector graphics, \emph{not}
    107107bit maps. Some scalable vector file formats are: EPS, SVG, PNG, WMF. These can
    108 all be converted into PNG or PDF, that pdflatex recognizes. Your drawing 
    109 package probably can export to one of these formats directly. Otherwise, a 
    110 common procedure is to print-to-file through a Postscript printer driver to 
    111 create a PS file, then convert that to EPS (encapsulated PS, which has a 
    112 bounding box to describe its exact size rather than a whole page). 
     108all be converted into PNG or PDF, that pdflatex recognizes. Your drawing
     109package probably can export to one of these formats directly. Otherwise, a
     110common procedure is to print-to-file through a Postscript printer driver to
     111create a PS file, then convert that to EPS (encapsulated PS, which has a
     112bounding box to describe its exact size rather than a whole page).
    113113Programs such as GSView (a Ghostscript GUI) can create both EPS and PDF from
    114114PS files. Appendix~\ref{AppendixA} shows how to generate properly sized Matlab
    115115plots and save them as PDF.
    116116\item It's important to crop your photos and draw your figures to the size that
    117 you want to appear in your thesis. Scaling photos with the 
    118 includegraphics command will cause loss of resolution. And scaling down 
     117you want to appear in your thesis. Scaling photos with the
     118includegraphics command will cause loss of resolution. And scaling down
    119119drawings may cause any text annotations to become too small.
    120120\end{itemize}
    121  
     121
    122122For more information on \LaTeX\, see the uWaterloo Skills for the
    123 Academic Workplace \href{https://uwaterloo.ca/information-systems-technology/services/electronic-thesis-preparation-and-submission-support/ethesis-guide/creating-pdf-version-your-thesis/creating-pdf-files-using-latex/latex-ethesis-and-large-documents}{course notes}. 
     123Academic Workplace \href{https://uwaterloo.ca/information-systems-technology/services/electronic-thesis-preparation-and-submission-support/ethesis-guide/creating-pdf-version-your-thesis/creating-pdf-files-using-latex/latex-ethesis-and-large-documents}{course notes}.
    124124\footnote{
    125125Note that while it is possible to include hyperlinks to external documents,
    126 it is not wise to do so, since anything you can't control may change over time. 
    127 It \emph{would} be appropriate and necessary to provide external links to 
    128 additional resources for a multimedia ``enhanced'' thesis. 
    129 But also note that if the \package{hyperref} package is not included, 
    130 as for the print-optimized option in this thesis template, any \cmmd{href} 
     126it is not wise to do so, since anything you can't control may change over time.
     127It \emph{would} be appropriate and necessary to provide external links to
     128additional resources for a multimedia ``enhanced'' thesis.
     129But also note that if the \package{hyperref} package is not included,
     130as for the print-optimized option in this thesis template, any \cmmd{href}
    131131commands in your logical document are no longer defined.
    132132A work-around employed by this thesis template is to define a dummy
    133 \cmmd{href} command (which does nothing) in the preamble of the document, 
    134 before the \package{hyperref} package is included. 
     133\cmmd{href} command (which does nothing) in the preamble of the document,
     134before the \package{hyperref} package is included.
    135135The dummy definition is then redifined by the
    136136\package{hyperref} package when it is included.
     
    138138
    139139The classic book by Leslie Lamport \cite{lamport.book}, author of \LaTeX , is
    140 worth a look too, and the many available add-on packages are described by 
     140worth a look too, and the many available add-on packages are described by
    141141Goossens \textit{et al} \cite{goossens.book}.
    142142
     
    180180Export Setup button in the figure Property Editor.
    181181
    182 \section{From the Command Line} 
     182\section{From the Command Line}
    183183All figure properties can also be manipulated from the command line. Here's an
    184 example: 
     184example:
    185185\begin{verbatim}
    186186x=[0:0.1:pi];
  • doc/theses/andrew_beach_MMath/unwinding.tex

    rc292244 ref0b456  
    1 \chapter{\texorpdfstring{Unwinding in \CFA}{Unwinding in Cforall}}
     1\chapter{Unwinding in \CFA}
    22
    3 Stack unwinding is the process of removing things from the stack. Within
    4 functions and on function return this is handled directly by the code in the
    5 function itself as it knows exactly what is on the stack just from the
    6 current location in the function. Unwinding across stack frames means that it
    7 is no longer knows exactly what is on the stack or even how much of the stack
    8 needs to be removed.
     3Stack unwinding is the process of removing stack frames (activations) from the
     4stack. On function entry and return, unwinding is handled directly by the code
     5embedded in the function. Usually, the stack-frame size is known statically
     6based on parameters and local variable declarations.  For dynamically-sized
     7local variables, a runtime computation is necessary to know the frame
     8size. Finally, a function's frame-size may change during execution as local
     9variables (static or dynamic sized) go in and out of scope.
     10Allocating/deallocating stack space is usually an $O(1)$ operation achieved by
     11bumping the hardware stack-pointer up or down as needed.
    912
    10 Even this is fairly simple if nothing needs to happen when the stack unwinds.
    11 Traditional C can unwind the stack by saving and restoring state (with
    12 @setjmp@ \& @longjmp@). However many languages define actions that
    13 have to be taken when something is removed from the stack, such as running
    14 a variable's destructor or a @try@ statement's @finally@
    15 clause. Handling this requires walking the stack going through each stack
    16 frame.
     13Unwinding across multiple stack frames is more complex because individual stack
     14management code associated with each frame is bypassed. That is, the location
     15of a function's frame code is largely unknown and dispersed throughout the
     16function, hence the current stack-frame size managed by that code is also
     17unknown. Hence, code unwinding across frames does not have direct knowledge
     18about what is on the stack, and hence, how much of the stack needs to be
     19removed.
    1720
    18 For exceptions, this means everything from the point the exception is raised
    19 to the point it is caught, while checking each frame for handlers during the
    20 stack walk to find out where it should be caught. This is where the most of
    21 the expense and complexity of exception handling comes from.
     21The traditional unwinding mechanism for C is implemented by saving a snap-shot
     22of a function's state with @setjmp@ and restoring that snap-shot with
     23@longjmp@. This approach bypasses the need to know stack details by simply
     24reseting to a snap-shot of an arbitrary but existing function frame on the
     25stack. It is up to the programmer to ensure the snap-shot is valid when it is
     26reset, making the code fragile with potential errors that are difficult to
     27debug because the stack becomes corrupted.
    2228
    23 To do all of this we use libunwind, a low level library that provides tools
    24 for stack walking and stack unwinding. What follows is an overview of all the
    25 relivant features of libunwind and then how \CFA uses them to implement its
    26 exception handling.
     29However, many languages define cleanup actions that have to be taken when
     30something is deallocated from the stack or blocks end, such as running a
     31variable's destructor or a @try@ statement's @finally@ clause. Handling these
     32mechanisms requires walking the stack and checking each stack frame for these
     33potential actions.
     34
     35For exceptions, it must be possible to walk the stack frames in search of try
     36statements with handlers to perform exception matching. For termination
     37exceptions, it must be possible to unwind all stack frames from the throw to
     38the matching catch, and each of these frames must be checked for cleanup
     39actions. Stack walking is where the most of the complexity and expense of
     40exception handling comes from.
     41
     42One of the most popular tools for stack management is libunwind, a low level
     43library that provides tools for stack walking and unwinding. What follows is an
     44overview of all the relevant features of libunwind and how \CFA uses them to
     45implement its exception handling.
    2746
    2847\section{libunwind Usage}
    29 
    30 \CFA uses two primary functions in libunwind to create most of its
    31 exceptional control-flow: @_Unwind_RaiseException@ and
    32 @_Unwind_ForcedUnwind@.
    33 Their operation is divided into two phases: search and clean-up. The search
    34 phase -- phase 1 -- is used to scan the stack but not unwinding it. The
    35 clean-up phase -- phase 2 -- is used for unwinding.
     48\CFA uses two primary functions in libunwind to create most of its exceptional
     49control-flow: @_Unwind_RaiseException@ and @_Unwind_ForcedUnwind@.  Their
     50operation is divided into two phases: search and clean-up. The search phase --
     51phase 1 -- is used to scan the stack but not unwinding it. The clean-up phase
     52-- phase 2 -- is used for unwinding.
    3653
    3754The raise-exception function uses both phases. It starts by searching for a
     
    4461A personality function performs three tasks, although not all have to be
    4562present. The tasks performed are decided by the actions provided.
    46 @_Unwind_Action@ is a bitmask of possible actions and an argument of
    47 this type is passed into the personality function.
     63@_Unwind_Action@ is a bitmask of possible actions and an argument of this type
     64is passed into the personality function.
    4865\begin{itemize}
    49 \item@_UA_SEARCH_PHASE@ is passed in search phase and tells the
    50 personality function to check for handlers. If there is a handler in this
    51 stack frame, as defined by the language, the personality function should
    52 return @_URC_HANDLER_FOUND@. Otherwise it should return
    53 @_URC_CONTINUE_UNWIND@.
    54 \item@_UA_CLEANUP_PHASE@ is passed in during the clean-up phase and
    55 means part or all of the stack frame is removed. The personality function
    56 should do whatever clean-up the language defines
    57 (such as running destructors/finalizers) and then generally returns
    58 @_URC_CONTINUE_UNWIND@.
    59 \item@_UA_HANDLER_FRAME@ means the personality function must install
    60 a handler. It is also passed in during the clean-up phase and is in addition
    61 to the clean-up action. libunwind provides several helpers for the personality
    62 function here. Once it is done, the personality function must return
    63 @_URC_INSTALL_CONTEXT@.
     66\item
     67\begin{sloppypar}
     68@_UA_SEARCH_PHASE@ is passed in for the search phase and tells the personality
     69function to check for handlers. If there is a handler in a stack frame, as
     70defined by the language, the personality function returns @_URC_HANDLER_FOUND@;
     71otherwise it return @_URC_CONTINUE_UNWIND@.
     72\end{sloppypar}
     73\item
     74@_UA_CLEANUP_PHASE@ is passed in during the clean-up phase and means part or
     75all of the stack frame is removed. The personality function does whatever
     76clean-up the language defines (such as running destructors/finalizers) and then
     77generally returns @_URC_CONTINUE_UNWIND@.
     78\item
     79@_UA_HANDLER_FRAME@ means the personality function must install a handler. It
     80is also passed in during the clean-up phase and is in addition to the clean-up
     81action. libunwind provides several helpers for the personality function. Once
     82it is done, the personality function returns @_URC_INSTALL_CONTEXT@.
    6483\end{itemize}
    65 The personality function is given a number of other arguments. Some are for
    66 compatability and there is the @struct _Unwind_Context@ pointer which
    67 passed to many helpers to get information about the current stack frame.
     84The personality function is given a number of other arguments. Some arguments
     85are for compatibility, and there is the @struct _Unwind_Context@ pointer which
     86is passed to many helpers to get information about the current stack frame.
    6887
    69 Forced-unwind only performs the clean-up phase. It takes three arguments:
    70 a pointer to the exception, a pointer to the stop function and a pointer to
    71 the stop parameter. It does most of the same things as phase two of
    72 raise-exception but with some extras.
    73 The first it passes in an extra action to the personality function on each
    74 stack frame, @_UA_FORCE_UNWIND@, which means a handler cannot be
     88For cancellation, forced-unwind only performs the clean-up phase. It takes
     89three arguments: a pointer to the exception, a pointer to the stop function and
     90a pointer to the stop parameter. It does most of the same actions as phase two
     91of raise-exception but passes in an extra action to the personality function on
     92each stack frame, @_UA_FORCE_UNWIND@, which means a handler cannot be
    7593installed.
    7694
    77 The big change is that forced-unwind calls the stop function. Each time it
    78 steps into a frame, before calling the personality function, it calls the
    79 stop function. The stop function receives all the same arguments as the
    80 personality function will and the stop parameter supplied to forced-unwind.
     95As well, forced-unwind calls the stop function each time it steps into a frame,
     96before calling the personality function. The stop function receives all the
     97same arguments as the personality function and the stop parameter supplied to
     98forced-unwind.
    8199
    82100The stop function is called one more time at the end of the stack after all
    83 stack frames have been removed. By the standard API this is marked by setting
     101stack frames have been removed. The standard API marks this frame by setting
    84102the stack pointer inside the context passed to the stop function. However both
    85103GCC and Clang add an extra action for this case @_UA_END_OF_STACK@.
    86104
    87 Each time function the stop function is called it can do one or two things.
    88 When it is not the end of the stack it can return @_URC_NO_REASON@ to
    89 continue unwinding.
     105Each time the stop function is called, it can do one or two things.  When it is
     106not the end of the stack it can return @_URC_NO_REASON@ to continue unwinding.
    90107% Is there a reason that NO_REASON is used instead of CONTINUE_UNWIND?
    91 Its only other option is to use its own means to transfer control elsewhere
    92 and never return to its caller. It may always do this and no additional tools
    93 are provided to do it.
     108The other option is to use some other means to transfer control elsewhere and
     109never return to its caller. libunwind provides no additional tools for
     110alternate transfers of control.
    94111
    95 \section{\texorpdfstring{\CFA Implementation}{Cforall Implementation}}
     112\section{\CFA Implementation}
    96113
    97 To use libunwind, \CFA provides several wrappers, its own storage,
    98 personality functions, and a stop function.
     114To use libunwind, \CFA provides several wrappers, its own storage, personality
     115functions, and a stop function.
    99116
    100117The wrappers perform three tasks: set-up, clean-up and controlling the
     
    108125The core control code is called every time a throw -- after set-up -- or
    109126re-throw is run. It uses raise-exception to search for a handler and to run it
    110 if one is found. If no handler is found and raise-exception returns then
     127if one is found. If no handler is found and raise-exception returns, then
    111128forced-unwind is called to run all destructors on the stack before terminating
    112129the process.
    113130
    114 The stop function is very simple. It checks the end of stack flag to see if
    115 it is finished unwinding. If so, it calls @exit@ to end the process,
    116 otherwise it returns with no-reason to continue unwinding.
     131The stop function is simple. It checks for the end of stack flag to see if
     132unwinding is finished. If so, it calls @exit@ to end the process, otherwise it
     133returns with no-reason to continue unwinding.
    117134% Yeah, this is going to have to change.
    118135
    119136The personality routine is more complex because it has to obtain information
    120 about the function by scanning the LSDA (Language Specific Data Area). This
     137about the function by scanning the Language Specific Data Area (LSDA). This
    121138step allows a single personality function to be used for multiple functions and
    122 let that personaliity function figure out exactly where in the function
    123 execution was, what is currently in the stack frame and what handlers should
    124 be checked.
     139lets that personality function figure out exactly where in the function
     140execution is, what is currently in the stack frame, and what handlers should be
     141checked.
    125142% Not that we do that yet.
    126143
    127 However, generating the LSDA is difficult. It requires knowledge about the
    128 location of the instruction pointer and stack layout, which varies with
    129 compiler and optimization levels. So for frames where there are only
    130 destructors, GCC's attribute cleanup with the @-fexception@ flag is
    131 sufficient to handle unwinding.
     144It is also necessary to generate the LSDA, which is difficult. It requires
     145knowledge about the location of the instruction pointer and stack layout, which
     146varies with compiler and optimization levels. Fortunately, for frames where
     147there are only destructors, GCC's attribute cleanup with the @-fexception@ flag
     148is sufficient to handle unwinding.
    132149
    133 The only functions that require more than that are those that contain
    134 @try@ statements. A @try@ statement has a @try@
    135 clause, some number of @catch@ clauses and @catchResume@
    136 clauses and may have a @finally@ clause. Of these only @try@
    137 statements with @catch@ clauses need to be transformed and only they
    138 and the @try@ clause are involved.
     150The only functions that require more information are those containing @try@
     151statements. Specifically, only @try@ statements with @catch@ clauses need to be
     152transformed.  The @try@ statement is converted into a series of closures that
     153can access other parts of the function according to scoping rules but can be
     154passed around. The @catch@ clauses are converted into two functions: the match
     155function and the handler function.
    139156
    140 The @try@ statement is converted into a series of closures which can
    141 access other parts of the function according to scoping rules but can be
    142 passed around. The @try@ clause is converted into the try functions,
    143 almost entirely unchanged. The @catch@ clauses are converted into two
    144 functions; the match function and the catch function.
     157Together the match function and the catch function form the code that runs when
     158an exception passes out of the guarded block for a try statement. The match
     159function is used during the search phase: it is passed an exception and checks
     160each handler to see if the raised exception matches the handler exception. It
     161returns an index that represents which handler matched or there is no
     162match. The catch function is used during the clean-up phase, it is passed an
     163exception and the index of a handler. It casts the exception to the exception
     164type declared in that handler and then runs the handler's body.
    145165
    146 Together the match function and the catch function form the code that runs
    147 when an exception passes out of a try block. The match function is used during
    148 the search phase, it is passed an exception and checks each handler to see if
    149 it will handle the exception. It returns an index that repersents which
    150 handler matched or that none of them did. The catch function is used during
    151 the clean-up phase, it is passed an exception and the index of a handler. It
    152 casts the exception to the exception type declared in that handler and then
    153 runs the handler's body.
    154 
    155 These three functions are passed to @try_terminate@. This is an
     166These three functions are passed to @try_terminate@, which is an
    156167% Maybe I shouldn't quote that, it isn't its actual name.
    157 internal hand-written function that has its own personality function and
    158 custom assembly LSD does the exception handling in \CFA. During normal
    159 execution all this function does is call the try function and then return.
    160 It is only when exceptions are thrown that anything interesting happens.
     168internal hand-written function that has its own personality function and custom
     169assembly LSDA for doing the exception handling in \CFA. During normal
     170execution, this function calls the try function and then return.  It is only
     171when exceptions are thrown that anything interesting happens.
    161172
    162173During the search phase the personality function gets the pointer to the match
    163 function and calls it. If the match function returns a handler index the
     174function and calls it. If the match function returns a handler index, the
    164175personality function saves it and reports that the handler has been found,
    165 otherwise unwinding continues.
    166 During the clean-up phase the personality function only does anything if the
    167 handler was found in this frame. If it was then the personality function
    168 installs the handler, which is setting the instruction pointer in
    169 @try_terminate@ to an otherwise unused section that calls the catch
    170 function, passing it the current exception and handler index.
    171 @try_terminate@ returns as soon as the catch function returns.
     176otherwise unwinding continues.  During the clean-up phase, the personality
     177function only performs an action, when a handler is found in a frame. For each
     178found frame, the personality function installs the handler, which sets the
     179instruction pointer in @try_terminate@ to an otherwise unused section that
     180calls the catch function, passing it the current exception and handler index.
     181@try_terminate@ returns as soon as the catch function returns.  At this point
     182control has returned to normal control flow.
    172183
    173 At this point control has returned to normal control flow.
     184\PAB{Maybe a diagram would be helpful?}
  • doc/theses/andrew_beach_MMath/uw-ethesis-frontpgs.tex

    rc292244 ref0b456  
    1313        \vspace*{1.0cm}
    1414
    15         \Huge
    16         {\bf Exception Handling in \CFA}
     15        {\Huge\bf Exception Handling in \CFA}
    1716
    1817        \vspace*{1.0cm}
    1918
    20         \normalsize
    2119        by \\
    2220
    2321        \vspace*{1.0cm}
    2422
    25         \Large
    26         Andrew James Beach \\
     23        {\Large Andrew James Beach} \\
    2724
    2825        \vspace*{3.0cm}
    2926
    30         \normalsize
    3127        A thesis \\
    32         presented to the University of Waterloo \\ 
     28        presented to the University of Waterloo \\
    3329        in fulfillment of the \\
    3430        thesis requirement for the degree of \\
     
    4339        \vspace*{1.0cm}
    4440
    45         \copyright\ Andrew James Beach \the\year \\
     41        \copyright{} Andrew James Beach \the\year \\
    4642        \end{center}
    4743\end{titlepage}
    4844
    49 % The rest of the front pages should contain no headers and be numbered using Roman numerals starting with `ii'
     45% The rest of the front pages should contain no headers and be numbered using
     46% Roman numerals starting with `ii'.
    5047\pagestyle{plain}
    5148\setcounter{page}{2}
    5249
    53 \cleardoublepage % Ends the current page and causes all figures and tables that have so far appeared in the input to be printed.
    54 % In a two-sided printing style, it also makes the next page a right-hand (odd-numbered) page, producing a blank page if necessary.
     50\cleardoublepage % Ends the current page and causes all figures and tables
     51% that have so far appeared in the input to be printed. In a two-sided
     52% printing style, it also makes the next page a right-hand (odd-numbered)
     53% page, producing a blank page if necessary.
    5554
    56 \begin{comment} 
     55\begin{comment}
    5756% E X A M I N I N G   C O M M I T T E E (Required for Ph.D. theses only)
    5857% Remove or comment out the lines below to remove this page
    5958\begin{center}\textbf{Examining Committee Membership}\end{center}
    6059  \noindent
    61 The following served on the Examining Committee for this thesis. The decision of the Examining Committee is by majority vote.
     60The following served on the Examining Committee for this thesis.
     61The decision of the Examining Committee is by majority vote.
    6262  \bigskip
    63  
     63
    6464  \noindent
    6565\begin{tabbing}
    6666Internal-External Member: \=  \kill % using longest text to define tab length
    67 External Examiner: \>  Bruce Bruce \\ 
     67External Examiner: \>  Bruce Bruce \\
    6868\> Professor, Dept. of Philosophy of Zoology, University of Wallamaloo \\
    69 \end{tabbing} 
     69\end{tabbing}
    7070  \bigskip
    71  
     71
    7272  \noindent
    7373\begin{tabbing}
     
    7979\end{tabbing}
    8080  \bigskip
    81  
     81
    8282  \noindent
    8383  \begin{tabbing}
     
    8787\end{tabbing}
    8888  \bigskip
    89  
     89
    9090  \noindent
    9191\begin{tabbing}
     
    9595\end{tabbing}
    9696  \bigskip
    97  
     97
    9898  \noindent
    9999\begin{tabbing}
     
    111111  % December 13th, 2006.  It is designed for an electronic thesis.
    112112 \begin{center}\textbf{Author's Declaration}\end{center}
    113  
     113
    114114 \noindent
    115 I hereby declare that I am the sole author of this thesis. This is a true copy of the thesis, including any required final revisions, as accepted by my examiners.
     115I hereby declare that I am the sole author of this thesis. This is a true copy
     116of the thesis, including any required final revisions, as accepted by my
     117examiners.
    116118
    117119  \bigskip
    118  
     120
    119121  \noindent
    120122I understand that my thesis may be made electronically available to the public.
  • doc/theses/andrew_beach_MMath/uw-ethesis.tex

    rc292244 ref0b456  
    11%======================================================================
    2 % University of Waterloo Thesis Template for LaTeX 
    3 % Last Updated November, 2020 
    4 % by Stephen Carr, IST Client Services, 
     2% University of Waterloo Thesis Template for LaTeX
     3% Last Updated November, 2020
     4% by Stephen Carr, IST Client Services,
    55% University of Waterloo, 200 University Ave. W., Waterloo, Ontario, Canada
    66% FOR ASSISTANCE, please send mail to request@uwaterloo.ca
    77
    88% DISCLAIMER
    9 % To the best of our knowledge, this template satisfies the current uWaterloo thesis requirements.
    10 % However, it is your responsibility to assure that you have met all requirements of the University and your particular department.
    11 
    12 % Many thanks for the feedback from many graduates who assisted the development of this template.
    13 % Also note that there are explanatory comments and tips throughout this template.
     9% To the best of our knowledge, this template satisfies the current uWaterloo
     10% thesis requirements. However, it is your responsibility to assure that you
     11% have met all requirements of the University and your particular department.
     12
     13% Many thanks for the feedback from many graduates who assisted the
     14% development of this template. Also note that there are explanatory comments
     15% and tips throughout this template.
    1416%======================================================================
    1517% Some important notes on using this template and making it your own...
    1618
    17 % The University of Waterloo has required electronic thesis submission since October 2006.
    18 % See the uWaterloo thesis regulations at
    19 % https://uwaterloo.ca/graduate-studies/thesis.
    20 % This thesis template is geared towards generating a PDF version optimized for viewing on an electronic display, including hyperlinks within the PDF.
    21 
    22 % DON'T FORGET TO ADD YOUR OWN NAME AND TITLE in the "hyperref" package configuration below.
    23 % THIS INFORMATION GETS EMBEDDED IN THE PDF FINAL PDF DOCUMENT.
    24 % You can view the information if you view properties of the PDF document.
    25 
    26 % Many faculties/departments also require one or more printed copies.
    27 % This template attempts to satisfy both types of output.
     19% The University of Waterloo has required electronic thesis submission since
     20% October 2006. See the uWaterloo thesis regulations at:
     21%   https://uwaterloo.ca/graduate-studies/thesis.
     22% This thesis template is geared towards generating a PDF version optimized
     23% for viewing on an electronic display, including hyperlinks within the PDF.
     24
     25% DON'T FORGET TO ADD YOUR OWN NAME AND TITLE in the "hyperref" package
     26% configuration below. THIS INFORMATION GETS EMBEDDED IN THE FINAL PDF
     27% DOCUMENT. You can view the information if you view properties of the PDF.
     28
     29% Many faculties/departments also require one or more printed copies.
     30% This template attempts to satisfy both types of output.
    2831% See additional notes below.
    29 % It is based on the standard "book" document class which provides all necessary sectioning structures and allows multi-part theses.
    30 
    31 % If you are using this template in Overleaf (cloud-based collaboration service), then it is automatically processed and previewed for you as you edit.
    32 
    33 % For people who prefer to install their own LaTeX distributions on their own computers, and process the source files manually, the following notes provide the sequence of tasks:
    34  
     32% It is based on the standard "book" document class which provides all
     33% necessary sectioning structures and allows multi-part theses.
     34
     35% If you are using this template in Overleaf (cloud-based collaboration
     36% service), then it is automatically processed and previewed for you as you
     37% edit.
     38
     39% For people who prefer to install their own LaTeX distributions on their own
     40% computers, and process the source files manually, the following notes
     41% provide the sequence of tasks:
     42
    3543% E.g. to process a thesis called "mythesis.tex" based on this template, run:
    3644
    3745% pdflatex mythesis     -- first pass of the pdflatex processor
    3846% bibtex mythesis       -- generates bibliography from .bib data file(s)
    39 % makeindex         -- should be run only if an index is used
    40 % pdflatex mythesis     -- fixes numbering in cross-references, bibliographic references, glossaries, index, etc.
    41 % pdflatex mythesis     -- it takes a couple of passes to completely process all cross-references
    42 
    43 % If you use the recommended LaTeX editor, Texmaker, you would open the mythesis.tex file, then click the PDFLaTeX button. Then run BibTeX (under the Tools menu).
    44 % Then click the PDFLaTeX button two more times.
    45 % If you have an index as well,you'll need to run MakeIndex from the Tools menu as well, before running pdflatex
    46 % the last two times.
    47 
    48 % N.B. The "pdftex" program allows graphics in the following formats to be included with the "\includegraphics" command: PNG, PDF, JPEG, TIFF
    49 % Tip: Generate your figures and photos in the size you want them to appear in your thesis, rather than scaling them with \includegraphics options.
    50 % Tip: Any drawings you do should be in scalable vector graphic formats: SVG, PNG, WMF, EPS and then converted to PNG or PDF, so they are scalable in the final PDF as well.
     47% makeindex         -- should be run only if an index is used
     48% pdflatex mythesis     -- fixes numbering in cross-references, bibliographic
     49%                      references, glossaries, index, etc.
     50% pdflatex mythesis     -- it takes a couple of passes to completely process all
     51%                      cross-references
     52
     53% If you use the recommended LaTeX editor, Texmaker, you would open the
     54% mythesis.tex file, then click the PDFLaTeX button. Then run BibTeX (under
     55% the Tools menu). Then click the PDFLaTeX button two more times.
     56% If you have an index as well, you'll need to run MakeIndex from the Tools
     57% menu as well, before running pdflatex the last two times.
     58
     59% N.B. The "pdftex" program allows graphics in the following formats to be
     60% included with the "\includegraphics" command: PNG, PDF, JPEG, TIFF
     61% Tip: Generate your figures and photos in the size you want them to appear
     62% in your thesis, rather than scaling them with \includegraphics options.
     63% Tip: Any drawings you do should be in scalable vector graphic formats: SVG,
     64% PNG, WMF, EPS and then converted to PNG or PDF, so they are scalable in the
     65% final PDF as well.
    5166% Tip: Photographs should be cropped and compressed so as not to be too large.
    5267
    53 % To create a PDF output that is optimized for double-sided printing:
    54 % 1) comment-out the \documentclass statement in the preamble below, and un-comment the second \documentclass line.
    55 % 2) change the value assigned below to the boolean variable "PrintVersion" from " false" to "true".
    56 
    57 %======================================================================
     68% To create a PDF output that is optimized for double-sided printing:
     69% 1) comment-out the \documentclass statement in the preamble below, and
     70%    un-comment the second \documentclass line.
     71% 2) change the value assigned below to the boolean variable "PrintVersion"
     72%    from "false" to "true".
     73
     74% ======================================================================
    5875%   D O C U M E N T   P R E A M B L E
    59 % Specify the document class, default style attributes, and page dimensions, etc.
     76% Specify the document class, default style attributes, page dimensions, etc.
    6077% For hyperlinked PDF, suitable for viewing on a computer, use this:
    6178\documentclass[letterpaper,12pt,titlepage,oneside,final]{book}
    6279
    63 % For PDF, suitable for double-sided printing, change the PrintVersion variable below to "true" and use this \documentclass line instead of the one above:
     80% For PDF, suitable for double-sided printing, change the PrintVersion
     81% variable below to "true" and use this \documentclass line instead of the
     82% one above:
    6483%\documentclass[letterpaper,12pt,titlepage,openright,twoside,final]{book}
    6584
     85\usepackage{etoolbox}
     86
    6687% Some LaTeX commands I define for my own nomenclature.
    67 % If you have to, it's easier to make changes to nomenclature once here than in a million places throughout your thesis!
     88% If you have to, it's easier to make changes to nomenclature once here than
     89% in a million places throughout your thesis!
    6890\newcommand{\package}[1]{\textbf{#1}} % package names in bold text
    69 \newcommand{\cmmd}[1]{\textbackslash\texttt{#1}} % command name in tt font 
    70 \newcommand{\href}[1]{#1} % does nothing, but defines the command so the print-optimized version will ignore \href tags (redefined by hyperref pkg).
    71 %\newcommand{\texorpdfstring}[2]{#1} % does nothing, but defines the command
     91\newcommand{\cmmd}[1]{\textbackslash\texttt{#1}} % command name in tt font
     92\newcommand{\href}[1]{#1} % does nothing, but defines the command so the
     93% print-optimized version will ignore \href tags (redefined by hyperref pkg).
    7294% Anything defined here may be redefined by packages added below...
    7395
     
    7698\newboolean{PrintVersion}
    7799\setboolean{PrintVersion}{false}
    78 % CHANGE THIS VALUE TO "true" as necessary, to improve printed results for hard copies by overriding some options of the hyperref package, called below.
     100% CHANGE THIS VALUE TO "true" as necessary, to improve printed results for
     101% hard copies by overriding some options of the hyperref package, called below.
    79102
    80103%\usepackage{nomencl} % For a nomenclature (optional; available from ctan.org)
    81 \usepackage{amsmath,amssymb,amstext} % Lots of math symbols and environments
    82 \usepackage[pdftex]{graphicx} % For including graphics N.B. pdftex graphics driver
     104% Lots of math symbols and environments
     105\usepackage{amsmath,amssymb,amstext}
     106% For including graphics N.B. pdftex graphics driver
     107\usepackage[pdftex]{graphicx}
     108% Removes large sections of the document.
     109\usepackage{comment}
    83110
    84111% Hyperlinks make it very easy to navigate an electronic document.
    85 % In addition, this is where you should specify the thesis title and author as they appear in the properties of the PDF document.
     112% In addition, this is where you should specify the thesis title and author as
     113% they appear in the properties of the PDF document.
    86114% Use the "hyperref" package
    87115% N.B. HYPERREF MUST BE THE LAST PACKAGE LOADED; ADD ADDITIONAL PKGS ABOVE
    88116\usepackage[pdftex,pagebackref=true]{hyperref} % with basic options
    89117%\usepackage[pdftex,pagebackref=true]{hyperref}
    90                 % N.B. pagebackref=true provides links back from the References to the body text. This can cause trouble for printing.
     118% N.B. pagebackref=true provides links back from the References to the body
     119% text. This can cause trouble for printing.
    91120\hypersetup{
    92121    plainpages=false,       % needed if Roman numbers in frontpages
    93     unicode=false,          % non-Latin characters in Acrobats bookmarks
    94     pdftoolbar=true,        % show Acrobats toolbar?
    95     pdfmenubar=true,        % show Acrobats menu?
     122    unicode=false,          % non-Latin characters in Acrobat's bookmarks
     123    pdftoolbar=true,        % show Acrobat's toolbar?
     124    pdfmenubar=true,        % show Acrobat's menu?
    96125    pdffitwindow=false,     % window fit to page when opened
    97126    pdfstartview={FitH},    % fits the width of the page to the window
    98 %    pdftitle={uWaterloo\ LaTeX\ Thesis\ Template},    % title: CHANGE THIS TEXT!
     127%    pdftitle={uWaterloo\ LaTeX\ Thesis\ Template}, % title: CHANGE THIS TEXT!
    99128%    pdfauthor={Author},    % author: CHANGE THIS TEXT! and uncomment this line
    100129%    pdfsubject={Subject},  % subject: CHANGE THIS TEXT! and uncomment this line
    101 %    pdfkeywords={keyword1} {key2} {key3}, % list of keywords, and uncomment this line if desired
     130%    pdfkeywords={keyword1} {key2} {key3}, % optional list of keywords
    102131    pdfnewwindow=true,      % links in new window
    103132    colorlinks=true,        % false: boxed links; true: colored links
     
    107136    urlcolor=cyan           % color of external links
    108137}
    109 \ifthenelse{\boolean{PrintVersion}}{   % for improved print quality, change some hyperref options
     138% for improved print quality, change some hyperref options
     139\ifthenelse{\boolean{PrintVersion}}{
    110140\hypersetup{    % override some previously defined hyperref options
    111141%    colorlinks,%
     
    116146}{} % end of ifthenelse (no else)
    117147
    118 \usepackage[automake,toc,abbreviations]{glossaries-extra} % Exception to the rule of hyperref being the last add-on package
    119 % If glossaries-extra is not in your LaTeX distribution, get it from CTAN (http://ctan.org/pkg/glossaries-extra),
    120 % although it's supposed to be in both the TeX Live and MikTeX distributions. There are also documentation and
    121 % installation instructions there.
     148% Exception to the rule of hyperref being the last add-on package
     149\usepackage[automake,toc,abbreviations]{glossaries-extra}
     150% If glossaries-extra is not in your LaTeX distribution, get it from CTAN
     151% (http://ctan.org/pkg/glossaries-extra), although it's supposed to be in
     152% both the TeX Live and MikTeX distributions. There are also documentation
     153% and installation instructions there.
    122154
    123155% Setting up the page margins...
    124 \setlength{\textheight}{9in}\setlength{\topmargin}{-0.45in}\setlength{\headsep}{0.25in}
    125 % uWaterloo thesis requirements specify a minimum of 1 inch (72pt) margin at the
    126 % top, bottom, and outside page edges and a 1.125 in. (81pt) gutter margin (on binding side).
    127 % While this is not an issue for electronic viewing, a PDF may be printed, and so we have the same page layout for both printed and electronic versions, we leave the gutter margin in.
    128 % Set margins to minimum permitted by uWaterloo thesis regulations:
     156\setlength{\textheight}{9in}
     157\setlength{\topmargin}{-0.45in}
     158\setlength{\headsep}{0.25in}
     159% uWaterloo thesis requirements specify a minimum of 1 inch (72pt) margin at
     160% the top, bottom, and outside page edges and a 1.125 in. (81pt) gutter margin
     161% (on binding side). While this is not an issue for electronic viewing, a PDF
     162% may be printed, and so we have the same page layout for both printed and
     163% electronic versions, we leave the gutter margin in. Set margins to minimum
     164% permitted by uWaterloo thesis regulations:
    129165\setlength{\marginparwidth}{0pt} % width of margin notes
    130166% N.B. If margin notes are used, you must adjust \textwidth, \marginparwidth
    131167% and \marginparsep so that the space left between the margin notes and page
    132168% edge is less than 15 mm (0.6 in.)
    133 \setlength{\marginparsep}{0pt} % width of space between body text and margin notes
    134 \setlength{\evensidemargin}{0.125in} % Adds 1/8 in. to binding side of all
     169% width of space between body text and margin notes
     170\setlength{\marginparsep}{0pt}
     171% Adds 1/8 in. to binding side of all
    135172% even-numbered pages when the "twoside" printing option is selected
    136 \setlength{\oddsidemargin}{0.125in} % Adds 1/8 in. to the left of all pages when "oneside" printing is selected, and to the left of all odd-numbered pages when "twoside" printing is selected
    137 \setlength{\textwidth}{6.375in} % assuming US letter paper (8.5 in. x 11 in.) and side margins as above
     173\setlength{\evensidemargin}{0.125in}
     174% Adds 1/8 in. to the left of all pages when "oneside" printing is selected,
     175% and to the left of all odd-numbered pages when "twoside" printing is selected
     176\setlength{\oddsidemargin}{0.125in}
     177% assuming US letter paper (8.5 in. x 11 in.) and side margins as above
     178\setlength{\textwidth}{6.375in}
    138179\raggedbottom
    139180
    140 % The following statement specifies the amount of space between paragraphs. Other reasonable specifications are \bigskipamount and \smallskipamount.
     181% The following statement specifies the amount of space between paragraphs.
     182% Other reasonable specifications are \bigskipamount and \smallskipamount.
    141183\setlength{\parskip}{\medskipamount}
    142184
    143 % The following statement controls the line spacing. 
    144 % The default spacing corresponds to good typographic conventions and only slight changes (e.g., perhaps "1.2"), if any, should be made.
     185% The following statement controls the line spacing.
     186% The default spacing corresponds to good typographic conventions and only
     187% slight changes (e.g., perhaps "1.2"), if any, should be made.
    145188\renewcommand{\baselinestretch}{1} % this is the default line space setting
    146189
    147190% By default, each chapter will start on a recto (right-hand side) page.
    148 % We also force each section of the front pages to start on a recto page by inserting \cleardoublepage commands.
    149 % In many cases, this will require that the verso (left-hand) page be blank, and while it should be counted, a page number should not be printed.
    150 % The following statements ensure a page number is not printed on an otherwise blank verso page.
     191% We also force each section of the front pages to start on a recto page by
     192% inserting \cleardoublepage commands. In many cases, this will require that
     193% the verso (left-hand) page be blank, and while it should be counted, a page
     194% number should not be printed. The following statements ensure a page number
     195% is not printed on an otherwise blank verso page.
    151196\let\origdoublepage\cleardoublepage
    152197\newcommand{\clearemptydoublepage}{%
     
    154199\let\cleardoublepage\clearemptydoublepage
    155200
    156 % Define Glossary terms (This is properly done here, in the preamble and could also be \input{} from a separate file...)
     201% Define Glossary terms (This is properly done here, in the preamble and
     202% could also be \input{} from a separate file...)
    157203\input{glossaries}
    158204\makeglossaries
    159205
    160 \usepackage{comment}
    161206% cfa macros used in the document
    162207%\usepackage{cfalab}
     208% I'm going to bring back eventually.
     209\makeatletter
     210% Combines all \CC* commands:
     211\newrobustcmd*\Cpp[1][\xspace]{\cfalab@Cpp#1}
     212\newcommand\cfalab@Cpp{C\kern-.1em\hbox{+\kern-.25em+}}
     213% Optional arguments do not work with pdf string. (Some fix-up required.)
     214\pdfstringdefDisableCommands{\def\Cpp{C++}}
     215\makeatother
     216
    163217\input{common}
    164 \CFAStyle                                               % CFA code-style for all languages
    165 \lstset{language=CFA,basicstyle=\linespread{0.9}\tt}    % CFA default lnaguage
     218% CFA code-style for all languages
     219\CFAStyle
     220% CFA default lnaguage
     221\lstset{language=CFA,basicstyle=\linespread{0.9}\tt}
     222% Annotations from Peter:
     223\newcommand{\PAB}[1]{{\color{blue}PAB: #1}}
     224% Change the style of abbreviations:
     225\renewcommand{\abbrevFont}{}
    166226
    167227%======================================================================
    168228%   L O G I C A L    D O C U M E N T
    169229% The logical document contains the main content of your thesis.
    170 % Being a large document, it is a good idea to divide your thesis into several files, each one containing one chapter or other significant chunk of content, so you can easily shuffle things around later if desired.
     230% Being a large document, it is a good idea to divide your thesis into several
     231% files, each one containing one chapter or other significant chunk of content,
     232% so you can easily shuffle things around later if desired.
    171233%======================================================================
    172234\begin{document}
     
    175237% FRONT MATERIAL
    176238% title page,declaration, borrowers' page, abstract, acknowledgements,
    177 % dedication, table of contents, list of tables, list of figures, nomenclature, etc.
    178 %----------------------------------------------------------------------
    179 \input{uw-ethesis-frontpgs}
     239% dedication, table of contents, list of tables, list of figures,
     240% nomenclature, etc.
     241%----------------------------------------------------------------------
     242\input{uw-ethesis-frontpgs}
    180243
    181244%----------------------------------------------------------------------
    182245% MAIN BODY
    183246% We suggest using a separate file for each chapter of your thesis.
    184 % Start each chapter file with the \chapter command.
    185 % Only use \documentclass or \begin{document} and \end{document} commands in this master document.
     247% Start each chapter file with the \chapter command. Only use \documentclass,
     248% \begin{document} and \end{document} commands in this master document.
    186249% Tip: Putting each sentence on a new line is a way to simplify later editing.
    187250%----------------------------------------------------------------------
    188251\input{existing}
    189252\input{features}
    190 \input{unwinding}
     253\input{implement}
     254%\input{unwinding}
    191255\input{future}
    192256
     
    198262% Bibliography
    199263
    200 % The following statement selects the style to use for references. 
    201 % It controls the sort order of the entries in the bibliography and also the formatting for the in-text labels.
     264% The following statement selects the style to use for references.
     265% It controls the sort order of the entries in the bibliography and also the
     266% formatting for the in-text labels.
    202267\bibliographystyle{plain}
    203 % This specifies the location of the file containing the bibliographic information. 
    204 % It assumes you're using BibTeX to manage your references (if not, why not?).
    205 \cleardoublepage % This is needed if the "book" document class is used, to place the anchor in the correct page, because the bibliography will start on its own page.
    206 % Use \clearpage instead if the document class uses the "oneside" argument
    207 \phantomsection  % With hyperref package, enables hyperlinking from the table of contents to bibliography             
    208 % The following statement causes the title "References" to be used for the bibliography section:
     268% This specifies the location of the file containing the bibliographic
     269% information. It assumes you're using BibTeX to manage your references (if
     270% not, why not?).
     271\cleardoublepage % This is needed if the "book" document class is used, to
     272% place the anchor in the correct page, because the bibliography will start
     273% on its own page.
     274% Use \clearpage instead if the document class uses the "oneside" argument.
     275\phantomsection  % With hyperref package, enables hyperlinking from the table
     276% of contents to bibliography.
     277% The following statement causes the title "References" to be used for the
     278% bibliography section:
    209279\renewcommand*{\bibname}{References}
    210280
     
    213283
    214284\bibliography{uw-ethesis,pl}
    215 % Tip: You can create multiple .bib files to organize your references.
    216 % Just list them all in the \bibliogaphy command, separated by commas (no spaces).
    217 
    218 % The following statement causes the specified references to be added to the bibliography even if they were not cited in the text.
    219 % The asterisk is a wildcard that causes all entries in the bibliographic database to be included (optional).
     285% Tip: You can create multiple .bib files to organize your references. Just
     286% list them all in the \bibliogaphy command, separated by commas (no spaces).
     287
     288% The following statement causes the specified references to be added to the
     289% bibliography even if they were not cited in the text. The asterisk is a
     290% wildcard that causes all entries in the bibliographic database to be
     291% included (optional).
    220292% \nocite{*}
    221293%----------------------------------------------------------------------
     
    225297% The \appendix statement indicates the beginning of the appendices.
    226298\appendix
    227 % Add an un-numbered title page before the appendices and a line in the Table of Contents
     299% Add an un-numbered title page before the appendices and a line in the Table
     300% of Contents
    228301% \chapter*{APPENDICES}
    229302% \addcontentsline{toc}{chapter}{APPENDICES}
    230 % Appendices are just more chapters, with different labeling (letters instead of numbers).
     303% Appendices are just more chapters, with different labeling (letters instead
     304% of numbers).
    231305% \input{appendix-matlab_plots.tex}
    232306
    233 % GLOSSARIES (Lists of definitions, abbreviations, symbols, etc. provided by the glossaries-extra package)
     307% GLOSSARIES (Lists of definitions, abbreviations, symbols, etc.
     308% provided by the glossaries-extra package)
    234309% -----------------------------
    235310\printglossaries
Note: See TracChangeset for help on using the changeset viewer.