[26ca815] | 1 | \chapter{Implementation}
|
---|
[553f8abe] | 2 | \label{c:implement}
|
---|
[26ca815] | 3 |
|
---|
[d02e547] | 4 | % Local Helpers:
|
---|
| 5 | \newcommand\transformline[1][becomes...]{
|
---|
| 6 | \hrulefill#1\hrulefill
|
---|
| 7 | \medskip
|
---|
| 8 | }
|
---|
| 9 |
|
---|
[5a4f1a8] | 10 | The implementation work for this thesis covers the two components: virtual
|
---|
[7eb6eb5] | 11 | system and exceptions. Each component is discussed in detail.
|
---|
| 12 |
|
---|
[26ca815] | 13 | \section{Virtual System}
|
---|
[7eb6eb5] | 14 | \label{s:VirtualSystem}
|
---|
[26ca815] | 15 | % Virtual table rules. Virtual tables, the pointer to them and the cast.
|
---|
[e8bad5c8] | 16 | While the \CFA virtual system currently has only one public features, virtual
|
---|
| 17 | cast and virtual tables,
|
---|
| 18 | % ??? refs (see the virtual cast feature \vpageref{p:VirtualCast}),
|
---|
| 19 | substantial structure is required to support them,
|
---|
[df24d37] | 20 | and provide features for exception handling and the standard library.
|
---|
[7eb6eb5] | 21 |
|
---|
[830299f] | 22 | \subsection{Virtual Type}
|
---|
[ba2e8f0] | 23 | A virtual type~(see \autoref{s:virtuals}) has a pointer to a virtual table,
|
---|
| 24 | called the \emph{virtual-table pointer},
|
---|
| 25 | which binds each instance of a virtual type to a virtual table.
|
---|
| 26 | Internally, the field is called \snake{virtual_table}
|
---|
| 27 | and is fixed after construction.
|
---|
| 28 | This pointer is also the table's id and how the system accesses the
|
---|
| 29 | virtual table and the virtual members there.
|
---|
| 30 | It is always the first field in the
|
---|
[7372065] | 31 | structure so that its location is always known.
|
---|
[9d7e5cb] | 32 |
|
---|
[ba2e8f0] | 33 | % We have no special rules for these constructors.
|
---|
| 34 | Virtual table pointers are passed to the constructors of virtual types
|
---|
| 35 | as part of field-by-field construction.
|
---|
[e56eabac] | 36 |
|
---|
[7372065] | 37 | \subsection{Type Id}
|
---|
| 38 | Every virtual type has a unique id.
|
---|
[ba2e8f0] | 39 | These are used in type equality, to check if the representation of two values
|
---|
| 40 | are the same, and to access the type's type information.
|
---|
| 41 | This uniqueness means across a program composed of multiple translation
|
---|
| 42 | units (TU), not uniqueness across all programs or even across multiple
|
---|
| 43 | processes on the same machine.
|
---|
| 44 |
|
---|
| 45 | Our approach for program uniqueness is using a static declaration for each
|
---|
| 46 | type id, where the run-time storage address of that variable is guaranteed to
|
---|
| 47 | be unique during program execution.
|
---|
| 48 | The type id storage can also be used for other purposes,
|
---|
| 49 | and is used for type information.
|
---|
| 50 |
|
---|
| 51 | The problem is that a type id may appear in multiple TUs that compose a
|
---|
| 52 | program (see \autoref{ss:VirtualTable}); so the initial solution would seem
|
---|
[0a55a53] | 53 | to be make it external in each translation unit. Hovever, the type id must
|
---|
[ba2e8f0] | 54 | have a declaration in (exactly) one of the TUs to create the storage.
|
---|
| 55 | No other declaration related to the virtual type has this property, so doing
|
---|
| 56 | this through standard C declarations would require the user to do it manually.
|
---|
| 57 |
|
---|
| 58 | Instead the linker is used to handle this problem.
|
---|
| 59 | % I did not base anything off of C++17; they are solving the same problem.
|
---|
| 60 | A new feature has been added to \CFA for this purpose, the special attribute
|
---|
| 61 | \snake{cfa_linkonce}, which uses the special section @.gnu.linkonce@.
|
---|
| 62 | When used as a prefix (\eg @.gnu.linkonce.example@) the linker does
|
---|
| 63 | not combine these sections, but instead discards all but one with the same
|
---|
| 64 | full name.
|
---|
| 65 |
|
---|
| 66 | So each type id must be given a unique section name with the linkonce
|
---|
| 67 | prefix. Luckily \CFA already has a way to get unique names, the name mangler.
|
---|
| 68 | For example, this could be written directly in \CFA:
|
---|
| 69 | \begin{cfa}
|
---|
| 70 | __attribute__((cfa_linkonce)) void f() {}
|
---|
| 71 | \end{cfa}
|
---|
| 72 | This is translated to:
|
---|
| 73 | \begin{cfa}
|
---|
| 74 | __attribute__((section(".gnu.linkonce._X1fFv___1"))) void _X1fFv___1() {}
|
---|
| 75 | \end{cfa}
|
---|
| 76 | This is done internally to access the name manglers.
|
---|
| 77 | This attribute is useful for other purposes, any other place a unique
|
---|
| 78 | instance required, and should eventually be made part of a public and
|
---|
| 79 | stable feature in \CFA.
|
---|
| 80 |
|
---|
| 81 | \subsection{Type Information}
|
---|
| 82 |
|
---|
| 83 | There is data stored at the type id's declaration, the type information.
|
---|
[9d7e5cb] | 84 | The type information currently is only the parent's type id or, if the
|
---|
[5a4f1a8] | 85 | type has no parent, the null pointer.
|
---|
| 86 | The ancestors of a virtual type are found by traversing type ids through
|
---|
| 87 | the type information.
|
---|
[ba2e8f0] | 88 | An example using helper macros looks like:
|
---|
| 89 | \begin{cfa}
|
---|
| 90 | struct INFO_TYPE(TYPE) {
|
---|
| 91 | INFO_TYPE(PARENT) const * parent;
|
---|
| 92 | };
|
---|
| 93 |
|
---|
| 94 | __attribute__((cfa_linkonce))
|
---|
| 95 | INFO_TYPE(TYPE) const INFO_NAME(TYPE) = {
|
---|
| 96 | &INFO_NAME(PARENT),
|
---|
| 97 | };
|
---|
| 98 | \end{cfa}
|
---|
[7372065] | 99 |
|
---|
| 100 | Type information is constructed as follows:
|
---|
[cd03b76d] | 101 | \begin{enumerate}[nosep]
|
---|
[5a4f1a8] | 102 | \item
|
---|
[ba2e8f0] | 103 | Use the type's name to generate a name for the type information structure,
|
---|
| 104 | which is saved so it can be reused.
|
---|
[5a4f1a8] | 105 | \item
|
---|
| 106 | Generate a new structure definition to store the type
|
---|
[9d7e5cb] | 107 | information. The layout is the same in each case, just the parent's type id,
|
---|
[5a4f1a8] | 108 | but the types used change from instance to instance.
|
---|
[ba2e8f0] | 109 | The generated name is used for both this structure and, if relevant, the
|
---|
[5a4f1a8] | 110 | parent pointer.
|
---|
[b51e389c] | 111 | If the virtual type is polymorphic then the type information structure is
|
---|
[9d7e5cb] | 112 | polymorphic as well, with the same polymorphic arguments.
|
---|
[5a4f1a8] | 113 | \item
|
---|
[ba2e8f0] | 114 | A separate name for instances is generated from the type's name.
|
---|
[5a4f1a8] | 115 | \item
|
---|
[ba2e8f0] | 116 | The definition is generated and initialized.
|
---|
[5a4f1a8] | 117 | The parent id is set to the null pointer or to the address of the parent's
|
---|
| 118 | type information instance. Name resolution handles the rest.
|
---|
| 119 | \item
|
---|
| 120 | \CFA's name mangler does its regular name mangling encoding the type of
|
---|
[ba2e8f0] | 121 | the declaration into the instance name.
|
---|
| 122 | This process gives a completely unique name
|
---|
[5a4f1a8] | 123 | including different instances of the same polymorphic type.
|
---|
| 124 | \end{enumerate}
|
---|
[b51e389c] | 125 |
|
---|
[7372065] | 126 | Writing that code manually, with helper macros for the early name mangling,
|
---|
| 127 | would look like this:
|
---|
| 128 | \begin{cfa}
|
---|
| 129 | struct INFO_TYPE(TYPE) {
|
---|
| 130 | INFO_TYPE(PARENT) const * parent;
|
---|
| 131 | };
|
---|
| 132 |
|
---|
| 133 | __attribute__((cfa_linkonce))
|
---|
| 134 | INFO_TYPE(TYPE) const INFO_NAME(TYPE) = {
|
---|
| 135 | &INFO_NAME(PARENT),
|
---|
| 136 | };
|
---|
| 137 | \end{cfa}
|
---|
[830299f] | 138 |
|
---|
[ba2e8f0] | 139 | \begin{comment}
|
---|
[5a4f1a8] | 140 | \subsubsection{\lstinline{cfa\_linkonce} Attribute}
|
---|
[ba2e8f0] | 141 | % I just realized: This is an extension of the inline keyword.
|
---|
[5a4f1a8] | 142 | % An extension of C's at least, it is very similar to C++'s.
|
---|
[c21f5a9] | 143 | Another feature added to \CFA is a new attribute: \texttt{cfa\_linkonce}.
|
---|
[5a4f1a8] | 144 | This attribute is attached to an object or function definition
|
---|
| 145 | (any global declaration with a name and a type)
|
---|
| 146 | allowing it to be defined multiple times.
|
---|
| 147 | All matching definitions mush have the link-once attribute
|
---|
| 148 | and their implementations should be identical as well.
|
---|
| 149 |
|
---|
| 150 | A single definition with the attribute can be included in a header
|
---|
| 151 | file as if it was a forward declaration, except no definition is required.
|
---|
| 152 |
|
---|
| 153 | This technique is used for type-id instances. A link-once definition is
|
---|
| 154 | generated each time the structure is seen. This will result in multiple
|
---|
| 155 | copies but the link-once attribute ensures all but one are removed for a
|
---|
| 156 | unique instance.
|
---|
| 157 |
|
---|
| 158 | Internally, @cfa_linkonce@ is replaced with
|
---|
[c21f5a9] | 159 | @section(".gnu.linkonce.NAME")@ where \texttt{NAME} is replaced by the
|
---|
| 160 | mangled name of the object.
|
---|
[5a4f1a8] | 161 | Any other @section@ attributes are removed from the declaration.
|
---|
[c21f5a9] | 162 | The prefix \texttt{.gnu.linkonce} in section names is recognized by the
|
---|
[5a4f1a8] | 163 | linker. If two of these sections appear with the same name, including
|
---|
| 164 | everything that comes after the special prefix, then only one is used
|
---|
| 165 | and the other is discarded.
|
---|
[ba2e8f0] | 166 | \end{comment}
|
---|
[c21f5a9] | 167 |
|
---|
[7eb6eb5] | 168 | \subsection{Virtual Table}
|
---|
[5a4f1a8] | 169 | \label{ss:VirtualTable}
|
---|
[9d7e5cb] | 170 | Each virtual type has a virtual table type that stores its type id and
|
---|
| 171 | virtual members.
|
---|
| 172 | Each virtual type instance is bound to a table instance that is filled with
|
---|
| 173 | the values of virtual members.
|
---|
| 174 | Both the layout of the fields and their value are decided by the rules given
|
---|
| 175 | below.
|
---|
| 176 |
|
---|
[cd03b76d] | 177 | The layout always comes in three parts (see \autoref{f:VirtualTableLayout}).
|
---|
[9d7e5cb] | 178 | The first section is just the type id at the head of the table. It is always
|
---|
[5a4f1a8] | 179 | there to ensure that it can be found even when the accessing code does not
|
---|
| 180 | know which virtual type it has.
|
---|
[9d7e5cb] | 181 | The second section are all the virtual members of the parent, in the same
|
---|
| 182 | order as they appear in the parent's virtual table. Note that the type may
|
---|
[0a55a53] | 183 | change slightly as references to the ``this" change. This is limited to
|
---|
[9d7e5cb] | 184 | inside pointers/references and via function pointers so that the size (and
|
---|
| 185 | hence the offsets) are the same.
|
---|
| 186 | The third section is similar to the second except that it is the new virtual
|
---|
| 187 | members introduced at this level in the hierarchy.
|
---|
| 188 |
|
---|
| 189 | \begin{figure}
|
---|
[cd03b76d] | 190 | \begin{center}
|
---|
[9b0bb79] | 191 | \input{vtable-layout}
|
---|
[cd03b76d] | 192 | \end{center}
|
---|
[9d7e5cb] | 193 | \caption{Virtual Table Layout}
|
---|
| 194 | \label{f:VirtualTableLayout}
|
---|
| 195 | \end{figure}
|
---|
| 196 |
|
---|
| 197 | The first and second sections together mean that every virtual table has a
|
---|
| 198 | prefix that has the same layout and types as its parent virtual table.
|
---|
[7372065] | 199 | This, combined with the fixed offset to the virtual table pointer, means that
|
---|
[5a4f1a8] | 200 | for any virtual type, it is always safe to access its virtual table and,
|
---|
| 201 | from there, it is safe to check the type id to identify the exact type of the
|
---|
[b51e389c] | 202 | underlying object, access any of the virtual members and pass the object to
|
---|
[9d7e5cb] | 203 | any of the method-like virtual members.
|
---|
| 204 |
|
---|
[5a4f1a8] | 205 | When a virtual table is declared, the user decides where to declare it and its
|
---|
[9d7e5cb] | 206 | name. The initialization of the virtual table is entirely automatic based on
|
---|
| 207 | the context of the declaration.
|
---|
| 208 |
|
---|
[5a4f1a8] | 209 | The type id is always fixed; with each virtual table type having
|
---|
[9d7e5cb] | 210 | exactly one possible type id.
|
---|
[5a4f1a8] | 211 | The virtual members are usually filled in by type resolution.
|
---|
| 212 | The best match for a given name and type at the declaration site is used.
|
---|
| 213 | There are two exceptions to that rule: the @size@ field, the type's size,
|
---|
| 214 | is set using a @sizeof@ expression and the @align@ field, the
|
---|
| 215 | type's alignment, is set using an @alignof@ expression.
|
---|
[9d7e5cb] | 216 |
|
---|
[0a55a53] | 217 | Most of these tools are already inside the compiler. Using simple
|
---|
| 218 | code transformations early on in compilation, allows most of that work to be
|
---|
[e8bad5c8] | 219 | handed off to the existing tools. \autoref{f:VirtualTableTransformation}
|
---|
| 220 | shows an example transformation, this example shows an exception virtual table.
|
---|
[0a55a53] | 221 | It also shows the transformation on the full declaration.
|
---|
| 222 | For a forward declaration, the @extern@ keyword is preserved and the
|
---|
[e8bad5c8] | 223 | initializer is not added.
|
---|
| 224 |
|
---|
| 225 | \begin{figure}[htb]
|
---|
| 226 | \begin{cfa}
|
---|
| 227 | vtable(example_type) example_name;
|
---|
| 228 | \end{cfa}
|
---|
| 229 | \transformline
|
---|
| 230 | % Check mangling.
|
---|
| 231 | \begin{cfa}
|
---|
| 232 | const struct example_type_vtable example_name = {
|
---|
| 233 | .__cfavir_typeid : &__cfatid_example_type,
|
---|
| 234 | .size : sizeof(example_type),
|
---|
| 235 | .copy : copy,
|
---|
| 236 | .^?{} : ^?{},
|
---|
| 237 | .msg : msg,
|
---|
| 238 | };
|
---|
| 239 | \end{cfa}
|
---|
| 240 | \caption{Virtual Table Transformation}
|
---|
| 241 | \label{f:VirtualTableTransformation}
|
---|
| 242 | \end{figure}
|
---|
| 243 |
|
---|
[ba2e8f0] | 244 | \subsection{Concurrency Integration}
|
---|
[f28fdee] | 245 | Coroutines and threads need instances of @CoroutineCancelled@ and
|
---|
[830299f] | 246 | @ThreadCancelled@ respectively to use all of their functionality. When a new
|
---|
[5a4f1a8] | 247 | data type is declared with @coroutine@ or @thread@, a forward declaration for
|
---|
[7eb6eb5] | 248 | the instance is created as well. The definition of the virtual table is created
|
---|
| 249 | at the definition of the main function.
|
---|
[c21f5a9] | 250 |
|
---|
[ba2e8f0] | 251 | These transformations are shown through code re-writing in
|
---|
| 252 | \autoref{f:CoroutineTypeTransformation} and
|
---|
| 253 | \autoref{f:CoroutineMainTransformation}.
|
---|
| 254 | Threads use the same pattern, with some names and types changed.
|
---|
| 255 | In both cases, the original declaration is not modified,
|
---|
[7372065] | 256 | only new ones are added.
|
---|
[5a4f1a8] | 257 |
|
---|
[ba2e8f0] | 258 | \begin{figure}[htb]
|
---|
[c21f5a9] | 259 | \begin{cfa}
|
---|
| 260 | coroutine Example {
|
---|
| 261 | // fields
|
---|
[9b0bb79] | 262 | };
|
---|
[c21f5a9] | 263 | \end{cfa}
|
---|
| 264 |
|
---|
[d02e547] | 265 | \transformline[appends...]
|
---|
| 266 |
|
---|
[c21f5a9] | 267 | \begin{cfa}
|
---|
| 268 | __attribute__((cfa_linkonce))
|
---|
| 269 | struct __cfatid_struct_CoroutineCancelled(Example)
|
---|
| 270 | __cfatid_CoroutineCancelled = {
|
---|
| 271 | &EXCEPTION_TYPE_ID,
|
---|
| 272 | };
|
---|
| 273 | extern CoroutineCancelled_vtable _default_vtable_object_declaration;
|
---|
| 274 | extern CoroutineCancelled_vtable & _default_vtable;
|
---|
| 275 | \end{cfa}
|
---|
[ba2e8f0] | 276 | \caption{Coroutine Type Transformation}
|
---|
| 277 | \label{f:CoroutineTypeTransformation}
|
---|
[7372065] | 278 | \end{figure}
|
---|
[e56eabac] | 279 |
|
---|
[e8bad5c8] | 280 | \begin{figure}[htb]
|
---|
[c21f5a9] | 281 | \begin{cfa}
|
---|
| 282 | void main(Example & this) {
|
---|
| 283 | // body
|
---|
| 284 | }
|
---|
| 285 | \end{cfa}
|
---|
| 286 |
|
---|
[d02e547] | 287 | \transformline[appends...]
|
---|
| 288 |
|
---|
[c21f5a9] | 289 | \begin{cfa}
|
---|
| 290 | CoroutineCancelled_vtable _default_vtable_object_declaration = {
|
---|
| 291 | __cfatid_CoroutineCancelled,
|
---|
| 292 | // Virtual member initialization.
|
---|
| 293 | };
|
---|
| 294 |
|
---|
| 295 | CoroutineCancelled_vtable & _default_vtable =
|
---|
| 296 | &_default_vtable_object_declaration;
|
---|
| 297 | \end{cfa}
|
---|
[ba2e8f0] | 298 | \caption{Coroutine Main Transformation}
|
---|
| 299 | \label{f:CoroutineMainTransformation}
|
---|
[c21f5a9] | 300 | \end{figure}
|
---|
[26ca815] | 301 |
|
---|
| 302 | \subsection{Virtual Cast}
|
---|
[7eb6eb5] | 303 | Virtual casts are implemented as a function call that does the subtype check
|
---|
| 304 | and a C coercion-cast to do the type conversion.
|
---|
| 305 | % The C-cast is just to make sure the generated code is correct so the rest of
|
---|
| 306 | % the section is about that function.
|
---|
[9d7e5cb] | 307 | The function is implemented in the standard library and has the following
|
---|
| 308 | signature:
|
---|
[7eb6eb5] | 309 | \begin{cfa}
|
---|
[0c4df43] | 310 | void * __cfa__virtual_cast(
|
---|
[ba2e8f0] | 311 | struct __cfavir_type_id * parent,
|
---|
| 312 | struct __cfavir_type_id * const * child );
|
---|
[7eb6eb5] | 313 | \end{cfa}
|
---|
[ba2e8f0] | 314 | The type id for the target type of the virtual cast is passed in as
|
---|
| 315 | @parent@ and
|
---|
[9d7e5cb] | 316 | the cast target is passed in as @child@.
|
---|
[ba2e8f0] | 317 | The generated C code wraps both arguments and the result with type casts.
|
---|
[5a4f1a8] | 318 | There is also an internal check inside the compiler to make sure that the
|
---|
[9d7e5cb] | 319 | target type is a virtual type.
|
---|
| 320 | % It also checks for conflicting definitions.
|
---|
| 321 |
|
---|
[5a4f1a8] | 322 | The virtual cast either returns the original pointer or the null pointer
|
---|
| 323 | as the new type.
|
---|
| 324 | So the function does the parent check and returns the appropriate value.
|
---|
[9d7e5cb] | 325 | The parent check is a simple linear search of child's ancestors using the
|
---|
| 326 | type information.
|
---|
[26ca815] | 327 |
|
---|
| 328 | \section{Exceptions}
|
---|
[e8bad5c8] | 329 | % The implementation of exception types.
|
---|
| 330 |
|
---|
| 331 | Creating exceptions can roughly divided into two parts,
|
---|
| 332 | the exceptions themselves and the virtual system interactions.
|
---|
| 333 |
|
---|
[0a55a53] | 334 | Creating an exception type is just a matter of prepending the field
|
---|
[e8bad5c8] | 335 | with the virtual table pointer to the list of the fields
|
---|
| 336 | (see \autoref{f:ExceptionTypeTransformation}).
|
---|
| 337 |
|
---|
| 338 | \begin{figure}[htb]
|
---|
| 339 | \begin{cfa}
|
---|
| 340 | exception new_exception {
|
---|
| 341 | // EXISTING FIELDS
|
---|
| 342 | };
|
---|
| 343 | \end{cfa}
|
---|
| 344 | \transformline
|
---|
| 345 | \begin{cfa}
|
---|
| 346 | struct new_exception {
|
---|
| 347 | struct new_exception_vtable const * virtual_table;
|
---|
| 348 | // EXISTING FIELDS
|
---|
| 349 | };
|
---|
| 350 | \end{cfa}
|
---|
| 351 | \caption{Exception Type Transformation}
|
---|
| 352 | \label{f:ExceptionTypeTransformation}
|
---|
| 353 | \end{figure}
|
---|
| 354 |
|
---|
| 355 | The integration between exceptions and the virtual system is a bit more
|
---|
| 356 | complex simply because of the nature of the virtual system prototype.
|
---|
| 357 | The primary issue is that the virtual system has no way to detect when it
|
---|
| 358 | should generate any of its internal types and data. This is handled by
|
---|
| 359 | the exception code, which tells the virtual system when to generate
|
---|
| 360 | its components.
|
---|
| 361 |
|
---|
| 362 | All types associated with a virtual type,
|
---|
| 363 | the types of the virtual table and the type id,
|
---|
| 364 | are generated when the virtual type (the exception) is first found.
|
---|
[0a55a53] | 365 | The type id (the instance) is generated with the exception, if it is
|
---|
[e8bad5c8] | 366 | a monomorphic type.
|
---|
[0a55a53] | 367 | However, if the exception is polymorphic, then a different type id has to
|
---|
| 368 | be generated for every instance. In this case, generation is delayed
|
---|
[e8bad5c8] | 369 | until a virtual table is created.
|
---|
| 370 | % There are actually some problems with this, which is why it is not used
|
---|
| 371 | % for monomorphic types.
|
---|
[0a55a53] | 372 | When a virtual table is created and initialized, two functions are created
|
---|
[e8bad5c8] | 373 | to fill in the list of virtual members.
|
---|
[0a55a53] | 374 | The first is a copy function that adapts the exception's copy constructor
|
---|
[e8bad5c8] | 375 | to work with pointers, avoiding some issues with the current copy constructor
|
---|
| 376 | interface.
|
---|
[0a55a53] | 377 | Second is the msg function that returns a C-string with the type's name,
|
---|
[e8bad5c8] | 378 | including any polymorphic parameters.
|
---|
[26ca815] | 379 |
|
---|
| 380 | \section{Unwinding}
|
---|
| 381 | % Adapt the unwind chapter, just describe the sections of libunwind used.
|
---|
| 382 | % Mention that termination and cancellation use it. Maybe go into why
|
---|
| 383 | % resumption doesn't as well.
|
---|
| 384 |
|
---|
[5a4f1a8] | 385 | % Many modern languages work with an internal stack that function push and pop
|
---|
[7eb6eb5] | 386 | % their local data to. Stack unwinding removes large sections of the stack,
|
---|
| 387 | % often across functions.
|
---|
| 388 |
|
---|
| 389 | Stack unwinding is the process of removing stack frames (activations) from the
|
---|
[9d7e5cb] | 390 | stack. On function entry and return, unwinding is handled directly by the
|
---|
| 391 | call/return code embedded in the function.
|
---|
| 392 |
|
---|
[ba2e8f0] | 393 | % Discussing normal stack unwinding:
|
---|
[9d7e5cb] | 394 | Usually, the stack-frame size is known statically based on parameter and
|
---|
[ba2e8f0] | 395 | local variable declarations. Even for a dynamic stack-size, the information
|
---|
[5a4f1a8] | 396 | to determine how much of the stack has to be removed is still contained
|
---|
[9d7e5cb] | 397 | within the function.
|
---|
[7eb6eb5] | 398 | Allocating/deallocating stack space is usually an $O(1)$ operation achieved by
|
---|
| 399 | bumping the hardware stack-pointer up or down as needed.
|
---|
[5a4f1a8] | 400 | Constructing/destructing values within a stack frame has
|
---|
[ba2e8f0] | 401 | a similar complexity but larger constants.
|
---|
[7eb6eb5] | 402 |
|
---|
[ba2e8f0] | 403 | % Discussing multiple frame stack unwinding:
|
---|
[9d7e5cb] | 404 | Unwinding across multiple stack frames is more complex because that
|
---|
| 405 | information is no longer contained within the current function.
|
---|
[0a55a53] | 406 | With separate compilation,
|
---|
[ba2e8f0] | 407 | a function does not know its callers nor their frame layout.
|
---|
| 408 | Even using the return address, that information is encoded in terms of
|
---|
| 409 | actions in code, intermixed with the actions required finish the function.
|
---|
| 410 | Without changing the main code path it is impossible to select one of those
|
---|
| 411 | two groups of actions at the return site.
|
---|
[7eb6eb5] | 412 |
|
---|
| 413 | The traditional unwinding mechanism for C is implemented by saving a snap-shot
|
---|
| 414 | of a function's state with @setjmp@ and restoring that snap-shot with
|
---|
| 415 | @longjmp@. This approach bypasses the need to know stack details by simply
|
---|
| 416 | reseting to a snap-shot of an arbitrary but existing function frame on the
|
---|
| 417 | stack. It is up to the programmer to ensure the snap-shot is valid when it is
|
---|
[5a4f1a8] | 418 | reset and that all required clean-up from the unwound stacks is performed.
|
---|
| 419 | This approach is fragile and requires extra work in the surrounding code.
|
---|
[9d7e5cb] | 420 |
|
---|
[ba2e8f0] | 421 | With respect to the extra work in the surrounding code,
|
---|
[9d7e5cb] | 422 | many languages define clean-up actions that must be taken when certain
|
---|
| 423 | sections of the stack are removed. Such as when the storage for a variable
|
---|
[ba2e8f0] | 424 | is removed from the stack, possibly requiring a destructor call,
|
---|
| 425 | or when a try statement with a finally clause is
|
---|
[9d7e5cb] | 426 | (conceptually) popped from the stack.
|
---|
[ba2e8f0] | 427 | None of these cases should be handled by the user --- that would contradict the
|
---|
[5a4f1a8] | 428 | intention of these features --- so they need to be handled automatically.
|
---|
[9d7e5cb] | 429 |
|
---|
[5a4f1a8] | 430 | To safely remove sections of the stack, the language must be able to find and
|
---|
[9d7e5cb] | 431 | run these clean-up actions even when removing multiple functions unknown at
|
---|
| 432 | the beginning of the unwinding.
|
---|
[7eb6eb5] | 433 |
|
---|
| 434 | One of the most popular tools for stack management is libunwind, a low-level
|
---|
| 435 | library that provides tools for stack walking, handler execution, and
|
---|
| 436 | unwinding. What follows is an overview of all the relevant features of
|
---|
| 437 | libunwind needed for this work, and how \CFA uses them to implement exception
|
---|
| 438 | handling.
|
---|
| 439 |
|
---|
| 440 | \subsection{libunwind Usage}
|
---|
| 441 | Libunwind, accessed through @unwind.h@ on most platforms, is a C library that
|
---|
[df24d37] | 442 | provides \Cpp-style stack-unwinding. Its operation is divided into two phases:
|
---|
[7eb6eb5] | 443 | search and cleanup. The dynamic target search -- phase 1 -- is used to scan the
|
---|
| 444 | stack and decide where unwinding should stop (but no unwinding occurs). The
|
---|
| 445 | cleanup -- phase 2 -- does the unwinding and also runs any cleanup code.
|
---|
| 446 |
|
---|
| 447 | To use libunwind, each function must have a personality function and a Language
|
---|
[830299f] | 448 | Specific Data Area (LSDA). The LSDA has the unique information for each
|
---|
[7eb6eb5] | 449 | function to tell the personality function where a function is executing, its
|
---|
[830299f] | 450 | current stack frame, and what handlers should be checked. Theoretically, the
|
---|
[7eb6eb5] | 451 | LSDA can contain any information but conventionally it is a table with entries
|
---|
[5a4f1a8] | 452 | representing regions of a function and what has to be done there during
|
---|
[9d7e5cb] | 453 | unwinding. These regions are bracketed by instruction addresses. If the
|
---|
[7eb6eb5] | 454 | instruction pointer is within a region's start/end, then execution is currently
|
---|
| 455 | executing in that region. Regions are used to mark out the scopes of objects
|
---|
[b51e389c] | 456 | with destructors and try blocks.
|
---|
[7eb6eb5] | 457 |
|
---|
| 458 | % Libunwind actually does very little, it simply moves down the stack from
|
---|
| 459 | % function to function. Most of the actions are implemented by the personality
|
---|
| 460 | % function which libunwind calls on every function. Since this is shared across
|
---|
| 461 | % many functions or even every function in a language it will need a bit more
|
---|
| 462 | % information.
|
---|
| 463 |
|
---|
| 464 | The GCC compilation flag @-fexceptions@ causes the generation of an LSDA and
|
---|
[9d7e5cb] | 465 | attaches a personality function to each function.
|
---|
| 466 | In plain C (which \CFA currently compiles down to) this
|
---|
[830299f] | 467 | flag only handles the cleanup attribute:
|
---|
[ba2e8f0] | 468 | %\label{code:cleanup}
|
---|
[7eb6eb5] | 469 | \begin{cfa}
|
---|
| 470 | void clean_up( int * var ) { ... }
|
---|
[830299f] | 471 | int avar __attribute__(( cleanup(clean_up) ));
|
---|
[7eb6eb5] | 472 | \end{cfa}
|
---|
[5a4f1a8] | 473 | The attribute is used on a variable and specifies a function,
|
---|
[9d7e5cb] | 474 | in this case @clean_up@, run when the variable goes out of scope.
|
---|
[5a4f1a8] | 475 | This feature is enough to mimic destructors,
|
---|
[ba2e8f0] | 476 | but not try statements that affect
|
---|
[9d7e5cb] | 477 | the unwinding.
|
---|
| 478 |
|
---|
[5a4f1a8] | 479 | To get full unwinding support, all of these features must be handled directly
|
---|
[0a55a53] | 480 | in assembly and assembler directives; particularly the cfi directives
|
---|
[b51e389c] | 481 | \snake{.cfi_lsda} and \snake{.cfi_personality}.
|
---|
[7eb6eb5] | 482 |
|
---|
| 483 | \subsection{Personality Functions}
|
---|
[830299f] | 484 | Personality functions have a complex interface specified by libunwind. This
|
---|
[7eb6eb5] | 485 | section covers some of the important parts of the interface.
|
---|
| 486 |
|
---|
[5a4f1a8] | 487 | A personality function can perform different actions depending on how it is
|
---|
[830299f] | 488 | called.
|
---|
[9b0bb79] | 489 | \begin{lstlisting}
|
---|
| 490 | typedef _Unwind_Reason_Code (*_Unwind_Personality_Fn) (
|
---|
| 491 | _Unwind_Action action,
|
---|
| 492 | _Unwind_Exception_Class exception_class,
|
---|
| 493 | _Unwind_Exception * exception,
|
---|
| 494 | struct _Unwind_Context * context);
|
---|
[26ca815] | 495 | \end{lstlisting}
|
---|
[7eb6eb5] | 496 | The @action@ argument is a bitmask of possible actions:
|
---|
[9d7e5cb] | 497 | \begin{enumerate}[topsep=5pt]
|
---|
[7eb6eb5] | 498 | \item
|
---|
| 499 | @_UA_SEARCH_PHASE@ specifies a search phase and tells the personality function
|
---|
[830299f] | 500 | to check for handlers. If there is a handler in a stack frame, as defined by
|
---|
[7eb6eb5] | 501 | the language, the personality function returns @_URC_HANDLER_FOUND@; otherwise
|
---|
| 502 | it return @_URC_CONTINUE_UNWIND@.
|
---|
| 503 |
|
---|
| 504 | \item
|
---|
| 505 | @_UA_CLEANUP_PHASE@ specifies a cleanup phase, where the entire frame is
|
---|
| 506 | unwound and all cleanup code is run. The personality function does whatever
|
---|
| 507 | cleanup the language defines (such as running destructors/finalizers) and then
|
---|
| 508 | generally returns @_URC_CONTINUE_UNWIND@.
|
---|
| 509 |
|
---|
| 510 | \item
|
---|
| 511 | \begin{sloppypar}
|
---|
| 512 | @_UA_HANDLER_FRAME@ specifies a cleanup phase on a function frame that found a
|
---|
| 513 | handler. The personality function must prepare to return to normal code
|
---|
| 514 | execution and return @_URC_INSTALL_CONTEXT@.
|
---|
| 515 | \end{sloppypar}
|
---|
| 516 |
|
---|
| 517 | \item
|
---|
| 518 | @_UA_FORCE_UNWIND@ specifies a forced unwind call. Forced unwind only performs
|
---|
| 519 | the cleanup phase and uses a different means to decide when to stop
|
---|
[ba2e8f0] | 520 | (see \autoref{s:ForcedUnwind}).
|
---|
[7eb6eb5] | 521 | \end{enumerate}
|
---|
| 522 |
|
---|
| 523 | The @exception_class@ argument is a copy of the
|
---|
[5a4f1a8] | 524 | \code{C}{exception}'s @exception_class@ field,
|
---|
[ba2e8f0] | 525 | which is a number that identifies the EHM
|
---|
[5a4f1a8] | 526 | that created the exception.
|
---|
[7eb6eb5] | 527 |
|
---|
[5a4f1a8] | 528 | The \code{C}{exception} argument is a pointer to a user
|
---|
[9d7e5cb] | 529 | provided storage object. It has two public fields: the @exception_class@,
|
---|
| 530 | which is described above, and the @exception_cleanup@ function.
|
---|
[5a4f1a8] | 531 | The clean-up function is used by the EHM to clean-up the exception, if it
|
---|
[9d7e5cb] | 532 | should need to be freed at an unusual time, it takes an argument that says
|
---|
| 533 | why it had to be cleaned up.
|
---|
[7eb6eb5] | 534 |
|
---|
| 535 | The @context@ argument is a pointer to an opaque type passed to helper
|
---|
| 536 | functions called inside the personality function.
|
---|
| 537 |
|
---|
| 538 | The return value, @_Unwind_Reason_Code@, is an enumeration of possible messages
|
---|
[26ca815] | 539 | that can be passed several places in libunwind. It includes a number of
|
---|
| 540 | messages for special cases (some of which should never be used by the
|
---|
[9d7e5cb] | 541 | personality function) and error codes. However, unless otherwise noted, the
|
---|
[5a4f1a8] | 542 | personality function always returns @_URC_CONTINUE_UNWIND@.
|
---|
[26ca815] | 543 |
|
---|
| 544 | \subsection{Raise Exception}
|
---|
[5a4f1a8] | 545 | Raising an exception is the central function of libunwind and it performs
|
---|
[7eb6eb5] | 546 | two-staged unwinding.
|
---|
| 547 | \begin{cfa}
|
---|
[26ca815] | 548 | _Unwind_Reason_Code _Unwind_RaiseException(_Unwind_Exception *);
|
---|
[7eb6eb5] | 549 | \end{cfa}
|
---|
| 550 | First, the function begins the search phase, calling the personality function
|
---|
| 551 | of the most recent stack frame. It continues to call personality functions
|
---|
| 552 | traversing the stack from newest to oldest until a function finds a handler or
|
---|
| 553 | the end of the stack is reached. In the latter case, raise exception returns
|
---|
| 554 | @_URC_END_OF_STACK@.
|
---|
| 555 |
|
---|
[9d7e5cb] | 556 | Second, when a handler is matched, raise exception moves to the clean-up
|
---|
| 557 | phase and walks the stack a second time.
|
---|
[7eb6eb5] | 558 | Once again, it calls the personality functions of each stack frame from newest
|
---|
| 559 | to oldest. This pass stops at the stack frame containing the matching handler.
|
---|
| 560 | If that personality function has not install a handler, it is an error.
|
---|
| 561 |
|
---|
| 562 | If an error is encountered, raise exception returns either
|
---|
| 563 | @_URC_FATAL_PHASE1_ERROR@ or @_URC_FATAL_PHASE2_ERROR@ depending on when the
|
---|
| 564 | error occurred.
|
---|
[26ca815] | 565 |
|
---|
| 566 | \subsection{Forced Unwind}
|
---|
[7eb6eb5] | 567 | \label{s:ForcedUnwind}
|
---|
| 568 | Forced Unwind is the other central function in libunwind.
|
---|
| 569 | \begin{cfa}
|
---|
[9d7e5cb] | 570 | _Unwind_Reason_Code _Unwind_ForcedUnwind(_Unwind_Exception *,
|
---|
[7eb6eb5] | 571 | _Unwind_Stop_Fn, void *);
|
---|
| 572 | \end{cfa}
|
---|
| 573 | It also unwinds the stack but it does not use the search phase. Instead another
|
---|
[830299f] | 574 | function, the stop function, is used to stop searching. The exception is the
|
---|
[7eb6eb5] | 575 | same as the one passed to raise exception. The extra arguments are the stop
|
---|
| 576 | function and the stop parameter. The stop function has a similar interface as a
|
---|
| 577 | personality function, except it is also passed the stop parameter.
|
---|
[9b0bb79] | 578 | \begin{lstlisting}
|
---|
| 579 | typedef _Unwind_Reason_Code (*_Unwind_Stop_Fn)(
|
---|
| 580 | _Unwind_Action action,
|
---|
| 581 | _Unwind_Exception_Class exception_class,
|
---|
| 582 | _Unwind_Exception * exception,
|
---|
| 583 | struct _Unwind_Context * context,
|
---|
| 584 | void * stop_parameter);
|
---|
[26ca815] | 585 | \end{lstlisting}
|
---|
| 586 |
|
---|
| 587 | The stop function is called at every stack frame before the personality
|
---|
[7eb6eb5] | 588 | function is called and then once more after all frames of the stack are
|
---|
| 589 | unwound.
|
---|
[26ca815] | 590 |
|
---|
[7eb6eb5] | 591 | Each time it is called, the stop function should return @_URC_NO_REASON@ or
|
---|
| 592 | transfer control directly to other code outside of libunwind. The framework
|
---|
| 593 | does not provide any assistance here.
|
---|
[26ca815] | 594 |
|
---|
[7eb6eb5] | 595 | \begin{sloppypar}
|
---|
[830299f] | 596 | Its arguments are the same as the paired personality function. The actions
|
---|
[887fc79] | 597 | \snake{_UA_CLEANUP_PHASE} and \snake{_UA_FORCE_UNWIND} are always set when it is
|
---|
[7eb6eb5] | 598 | called. Beyond the libunwind standard, both GCC and Clang add an extra action
|
---|
[887fc79] | 599 | on the last call at the end of the stack: \snake{_UA_END_OF_STACK}.
|
---|
[7eb6eb5] | 600 | \end{sloppypar}
|
---|
[26ca815] | 601 |
|
---|
| 602 | \section{Exception Context}
|
---|
| 603 | % Should I have another independent section?
|
---|
| 604 | % There are only two things in it, top_resume and current_exception. How it is
|
---|
[7eb6eb5] | 605 | % stored changes depending on whether or not the thread-library is linked.
|
---|
| 606 |
|
---|
| 607 | The exception context is global storage used to maintain data across different
|
---|
| 608 | exception operations and to communicate among different components.
|
---|
| 609 |
|
---|
| 610 | Each stack must have its own exception context. In a sequential \CFA program,
|
---|
| 611 | there is only one stack with a single global exception-context. However, when
|
---|
[9d7e5cb] | 612 | the library @libcfathread@ is linked, there are multiple stacks and each
|
---|
[7eb6eb5] | 613 | needs its own exception context.
|
---|
| 614 |
|
---|
[ba2e8f0] | 615 | The current exception context should be retrieved by calling the function
|
---|
[887fc79] | 616 | \snake{this_exception_context}.
|
---|
| 617 | For sequential execution, this function is defined as
|
---|
[7eb6eb5] | 618 | a weak symbol in the \CFA system-library, @libcfa@. When a \CFA program is
|
---|
| 619 | concurrent, it links with @libcfathread@, where this function is defined with a
|
---|
| 620 | strong symbol replacing the sequential version.
|
---|
| 621 |
|
---|
[830299f] | 622 | The sequential @this_exception_context@ returns a hard-coded pointer to the
|
---|
[9d7e5cb] | 623 | global exception context.
|
---|
[830299f] | 624 | The concurrent version adds the exception context to the data stored at the
|
---|
[9d7e5cb] | 625 | base of each stack. When @this_exception_context@ is called, it retrieves the
|
---|
[830299f] | 626 | active stack and returns the address of the context saved there.
|
---|
[26ca815] | 627 |
|
---|
| 628 | \section{Termination}
|
---|
| 629 | % Memory management & extra information, the custom function used to implement
|
---|
| 630 | % catches. Talk about GCC nested functions.
|
---|
| 631 |
|
---|
[5a4f1a8] | 632 | \CFA termination exceptions use libunwind heavily because they match
|
---|
[9d7e5cb] | 633 | \Cpp exceptions closely. The main complication for \CFA is that the
|
---|
[7eb6eb5] | 634 | compiler generates C code, making it very difficult to generate the assembly to
|
---|
[b51e389c] | 635 | form the LSDA for try blocks or destructors.
|
---|
[26ca815] | 636 |
|
---|
| 637 | \subsection{Memory Management}
|
---|
[7eb6eb5] | 638 | The first step of a termination raise is to copy the exception into memory
|
---|
| 639 | managed by the exception system. Currently, the system uses @malloc@, rather
|
---|
[ba2e8f0] | 640 | than reserved memory or the stack top. The EHM manages
|
---|
[7eb6eb5] | 641 | memory for the exception as well as memory for libunwind and the system's own
|
---|
| 642 | per-exception storage.
|
---|
| 643 |
|
---|
[9d7e5cb] | 644 | \begin{figure}
|
---|
[5a4f1a8] | 645 | \centering
|
---|
[9b0bb79] | 646 | \input{exception-layout}
|
---|
[9d7e5cb] | 647 | \caption{Exception Layout}
|
---|
| 648 | \label{f:ExceptionLayout}
|
---|
| 649 | \end{figure}
|
---|
[830299f] | 650 |
|
---|
[5a4f1a8] | 651 | Exceptions are stored in variable-sized blocks
|
---|
| 652 | (see \autoref{f:ExceptionLayout}).
|
---|
[9d7e5cb] | 653 | The first component is a fixed-sized data structure that contains the
|
---|
[7eb6eb5] | 654 | information for libunwind and the exception system. The second component is an
|
---|
| 655 | area of memory big enough to store the exception. Macros with pointer arthritic
|
---|
| 656 | and type cast are used to move between the components or go from the embedded
|
---|
[f28fdee] | 657 | @_Unwind_Exception@ to the entire node.
|
---|
[26ca815] | 658 |
|
---|
[5a4f1a8] | 659 | Multiple exceptions can exist at the same time because exceptions can be
|
---|
[9d7e5cb] | 660 | raised inside handlers, destructors and finally blocks.
|
---|
| 661 | Figure~\vref{f:MultipleExceptions} shows a program that has multiple
|
---|
| 662 | exceptions active at one time.
|
---|
| 663 | Each time an exception is thrown and caught the stack unwinds and the finally
|
---|
[5a4f1a8] | 664 | clause runs. This handler throws another exception (until @num_exceptions@ gets
|
---|
| 665 | high enough), which must be allocated. The previous exceptions may not be
|
---|
[9d7e5cb] | 666 | freed because the handler/catch clause has not been run.
|
---|
[5a4f1a8] | 667 | Therefore, the EHM must keep all unhandled exceptions alive
|
---|
| 668 | while it allocates exceptions for new throws.
|
---|
[9d7e5cb] | 669 |
|
---|
| 670 | \begin{figure}
|
---|
| 671 | \centering
|
---|
[9b0bb79] | 672 | \newsavebox{\codeBox}
|
---|
| 673 | \newsavebox{\stackBox}
|
---|
| 674 | \begin{lrbox}{\codeBox}
|
---|
[25d4e15] | 675 | \begin{cfa}
|
---|
[9d7e5cb] | 676 | unsigned num_exceptions = 0;
|
---|
| 677 | void throws() {
|
---|
| 678 | try {
|
---|
| 679 | try {
|
---|
| 680 | ++num_exceptions;
|
---|
| 681 | throw (Example){table};
|
---|
| 682 | } finally {
|
---|
| 683 | if (num_exceptions < 3) {
|
---|
| 684 | throws();
|
---|
| 685 | }
|
---|
| 686 | }
|
---|
| 687 | } catch (exception_t *) {
|
---|
| 688 | --num_exceptions;
|
---|
| 689 | }
|
---|
| 690 | }
|
---|
| 691 | int main() {
|
---|
| 692 | throws();
|
---|
| 693 | }
|
---|
[25d4e15] | 694 | \end{cfa}
|
---|
[9d7e5cb] | 695 | \end{lrbox}
|
---|
| 696 |
|
---|
[9b0bb79] | 697 | \begin{lrbox}{\stackBox}
|
---|
[9d7e5cb] | 698 | \begin{lstlisting}
|
---|
[25d4e15] | 699 | | finally block (Example)
|
---|
| 700 | | try block
|
---|
[9b0bb79] | 701 | throws()
|
---|
[25d4e15] | 702 | | finally block (Example)
|
---|
| 703 | | try block
|
---|
[9b0bb79] | 704 | throws()
|
---|
[25d4e15] | 705 | | finally block (Example)
|
---|
| 706 | | try block
|
---|
[9b0bb79] | 707 | throws()
|
---|
| 708 | main()
|
---|
[9d7e5cb] | 709 | \end{lstlisting}
|
---|
| 710 | \end{lrbox}
|
---|
| 711 |
|
---|
[9b0bb79] | 712 | {\usebox\codeBox}
|
---|
[9d7e5cb] | 713 | \hspace{25pt}
|
---|
[9b0bb79] | 714 | {\usebox\stackBox}
|
---|
[9d7e5cb] | 715 |
|
---|
| 716 | \caption{Multiple Exceptions}
|
---|
| 717 | \label{f:MultipleExceptions}
|
---|
| 718 | \end{figure}
|
---|
| 719 |
|
---|
[5a4f1a8] | 720 | All exceptions are stored in nodes, which are then linked together in lists
|
---|
[9d7e5cb] | 721 | one list per stack, with the
|
---|
[7eb6eb5] | 722 | list head stored in the exception context. Within each linked list, the most
|
---|
| 723 | recently thrown exception is at the head followed by older thrown
|
---|
| 724 | exceptions. This format allows exceptions to be thrown, while a different
|
---|
| 725 | exception is being handled. The exception at the head of the list is currently
|
---|
| 726 | being handled, while other exceptions wait for the exceptions before them to be
|
---|
[5a4f1a8] | 727 | handled and removed.
|
---|
[7eb6eb5] | 728 |
|
---|
| 729 | The virtual members in the exception's virtual table provide the size of the
|
---|
| 730 | exception, the copy function, and the free function, so they are specific to an
|
---|
| 731 | exception type. The size and copy function are used immediately to copy an
|
---|
[9d7e5cb] | 732 | exception into managed memory. After the exception is handled, the free
|
---|
| 733 | function is used to clean up the exception and then the entire node is
|
---|
[5a4f1a8] | 734 | passed to free, returning the memory back to the heap.
|
---|
[7eb6eb5] | 735 |
|
---|
| 736 | \subsection{Try Statements and Catch Clauses}
|
---|
[b51e389c] | 737 | The try statement with termination handlers is complex because it must
|
---|
[ba2e8f0] | 738 | compensate for the C code-generation versus proper
|
---|
[5a4f1a8] | 739 | assembly-code generated from \CFA. Libunwind
|
---|
[7eb6eb5] | 740 | requires an LSDA and personality function for control to unwind across a
|
---|
| 741 | function. The LSDA in particular is hard to mimic in generated C code.
|
---|
| 742 |
|
---|
[ba2e8f0] | 743 | The workaround is a function called \snake{__cfaehm_try_terminate} in the
|
---|
| 744 | standard \CFA library. The contents of a try block and the termination
|
---|
| 745 | handlers are converted into nested functions. These are then passed to the
|
---|
| 746 | try terminate function and it calls them, appropriately.
|
---|
[830299f] | 747 | Because this function is known and fixed (and not an arbitrary function that
|
---|
[ba2e8f0] | 748 | happens to contain a try statement), its LSDA can be generated ahead
|
---|
[830299f] | 749 | of time.
|
---|
| 750 |
|
---|
[ba2e8f0] | 751 | Both the LSDA and the personality function for \snake{__cfaehm_try_terminate}
|
---|
| 752 | are set ahead of time using
|
---|
[9d7e5cb] | 753 | embedded assembly. This assembly code is handcrafted using C @asm@ statements
|
---|
| 754 | and contains
|
---|
[ba2e8f0] | 755 | enough information for the single try statement the function represents.
|
---|
[26ca815] | 756 |
|
---|
| 757 | The three functions passed to try terminate are:
|
---|
[7eb6eb5] | 758 | \begin{description}
|
---|
[5a4f1a8] | 759 | \item[try function:] This function is the try block, it is where all the code
|
---|
| 760 | from inside the try block is placed. It takes no parameters and has no
|
---|
[7eb6eb5] | 761 | return value. This function is called during regular execution to run the try
|
---|
| 762 | block.
|
---|
| 763 |
|
---|
| 764 | \item[match function:] This function is called during the search phase and
|
---|
[830299f] | 765 | decides if a catch clause matches the termination exception. It is constructed
|
---|
[7eb6eb5] | 766 | from the conditional part of each handler and runs each check, top to bottom,
|
---|
[ba2e8f0] | 767 | in turn, to see if the exception matches this handler.
|
---|
| 768 | The match is performed in two steps, first a virtual cast is used to check
|
---|
| 769 | if the raised exception is an instance of the declared exception type or
|
---|
| 770 | one of its descendant types, and then the condition is evaluated, if
|
---|
| 771 | present.
|
---|
| 772 | The match function takes a pointer to the exception and returns 0 if the
|
---|
[7eb6eb5] | 773 | exception is not handled here. Otherwise the return value is the id of the
|
---|
| 774 | handler that matches the exception.
|
---|
| 775 |
|
---|
[5a4f1a8] | 776 | \item[handler function:] This function handles the exception, and contains
|
---|
| 777 | all the code from the handlers in the try statement, joined with a switch
|
---|
| 778 | statement on the handler's id.
|
---|
| 779 | It takes a
|
---|
[7eb6eb5] | 780 | pointer to the exception and the handler's id and returns nothing. It is called
|
---|
[5a4f1a8] | 781 | after the cleanup phase.
|
---|
[7eb6eb5] | 782 | \end{description}
|
---|
| 783 | All three functions are created with GCC nested functions. GCC nested functions
|
---|
[5a4f1a8] | 784 | can be used to create closures,
|
---|
[ba2e8f0] | 785 | in other words,
|
---|
| 786 | functions that can refer to variables in their lexical scope even
|
---|
| 787 | those variables are part of a different function.
|
---|
| 788 | This approach allows the functions to refer to all the
|
---|
[830299f] | 789 | variables in scope for the function containing the @try@ statement. These
|
---|
[7eb6eb5] | 790 | nested functions and all other functions besides @__cfaehm_try_terminate@ in
|
---|
| 791 | \CFA use the GCC personality function and the @-fexceptions@ flag to generate
|
---|
[9d7e5cb] | 792 | the LSDA.
|
---|
| 793 | Using this pattern, \CFA implements destructors with the cleanup attribute.
|
---|
[c21f5a9] | 794 |
|
---|
[5a4f1a8] | 795 | \autoref{f:TerminationTransformation} shows the pattern used to transform
|
---|
[ba2e8f0] | 796 | a \CFA try statement with catch clauses into the appropriate C functions.
|
---|
[5a4f1a8] | 797 |
|
---|
[c21f5a9] | 798 | \begin{figure}
|
---|
| 799 | \begin{cfa}
|
---|
| 800 | try {
|
---|
| 801 | // TRY BLOCK
|
---|
| 802 | } catch (Exception1 * name1 ; check(name1)) {
|
---|
| 803 | // CATCH BLOCK 1
|
---|
| 804 | } catch (Exception2 * name2) {
|
---|
| 805 | // CATCH BLOCK 2
|
---|
| 806 | }
|
---|
| 807 | \end{cfa}
|
---|
| 808 |
|
---|
[d02e547] | 809 | \transformline
|
---|
[5a4f1a8] | 810 |
|
---|
[c21f5a9] | 811 | \begin{cfa}
|
---|
| 812 | void try(void) {
|
---|
| 813 | // TRY BLOCK
|
---|
| 814 | }
|
---|
| 815 | int match(exception_t * __exception_inst) {
|
---|
| 816 | {
|
---|
| 817 | Exception1 * name1;
|
---|
[887fc79] | 818 | if (name1 = (virtual Exception1 *)__exception_inst
|
---|
| 819 | && check(name1)) {
|
---|
[c21f5a9] | 820 | return 1;
|
---|
| 821 | }
|
---|
| 822 | }
|
---|
| 823 | {
|
---|
| 824 | Exception2 * name2;
|
---|
| 825 | if (name2 = (virtual Exception2 *)__exception_inst) {
|
---|
| 826 | return 2;
|
---|
| 827 | }
|
---|
| 828 | }
|
---|
| 829 | return 0;
|
---|
| 830 | }
|
---|
| 831 | void catch(exception_t * __exception_inst, int __handler_index) {
|
---|
| 832 | switch (__handler_index) {
|
---|
| 833 | case 1:
|
---|
| 834 | {
|
---|
| 835 | Exception1 * name1 = (virtual Exception1 *)__exception_inst;
|
---|
| 836 | // CATCH BLOCK 1
|
---|
| 837 | }
|
---|
| 838 | return;
|
---|
| 839 | case 2:
|
---|
| 840 | {
|
---|
| 841 | Exception2 * name2 = (virtual Exception2 *)__exception_inst;
|
---|
| 842 | // CATCH BLOCK 2
|
---|
| 843 | }
|
---|
| 844 | return;
|
---|
| 845 | }
|
---|
| 846 | }
|
---|
| 847 | {
|
---|
| 848 | __cfaehm_try_terminate(try, catch, match);
|
---|
| 849 | }
|
---|
| 850 | \end{cfa}
|
---|
| 851 |
|
---|
| 852 | \caption{Termination Transformation}
|
---|
| 853 | \label{f:TerminationTransformation}
|
---|
| 854 | \end{figure}
|
---|
[26ca815] | 855 |
|
---|
| 856 | \section{Resumption}
|
---|
| 857 | % The stack-local data, the linked list of nodes.
|
---|
| 858 |
|
---|
[5a4f1a8] | 859 | Resumption is simpler to implement than termination
|
---|
[9d7e5cb] | 860 | because there is no stack unwinding.
|
---|
| 861 | Instead of storing the data in a special area using assembly,
|
---|
| 862 | there is just a linked list of possible handlers for each stack,
|
---|
[ba2e8f0] | 863 | with each node on the list representing a try statement on the stack.
|
---|
[9d7e5cb] | 864 |
|
---|
| 865 | The head of the list is stored in the exception context.
|
---|
[b51e389c] | 866 | The nodes are stored in order, with the more recent try statements closer
|
---|
[9d7e5cb] | 867 | to the head of the list.
|
---|
[5a4f1a8] | 868 | Instead of traversing the stack, resumption handling traverses the list.
|
---|
[ba2e8f0] | 869 | At each node, the EHM checks to see if the try statement the node represents
|
---|
[9d7e5cb] | 870 | can handle the exception. If it can, then the exception is handled and
|
---|
| 871 | the operation finishes, otherwise the search continues to the next node.
|
---|
[b51e389c] | 872 | If the search reaches the end of the list without finding a try statement
|
---|
[ba2e8f0] | 873 | with a handler clause
|
---|
| 874 | that can handle the exception, the default handler is executed.
|
---|
| 875 | If the default handler returns, control continues after the raise statement.
|
---|
[9d7e5cb] | 876 |
|
---|
[5a4f1a8] | 877 | Each node has a handler function that does most of the work.
|
---|
| 878 | The handler function is passed the raised exception and returns true
|
---|
| 879 | if the exception is handled and false otherwise.
|
---|
| 880 | The handler function checks each of its internal handlers in order,
|
---|
| 881 | top-to-bottom, until it funds a match. If a match is found that handler is
|
---|
| 882 | run, after which the function returns true, ignoring all remaining handlers.
|
---|
| 883 | If no match is found the function returns false.
|
---|
| 884 | The match is performed in two steps, first a virtual cast is used to see
|
---|
[ba2e8f0] | 885 | if the raised exception is an instance of the declared exception type or one
|
---|
| 886 | of its descendant types, if so then it is passed to the custom predicate
|
---|
| 887 | if one is defined.
|
---|
| 888 | % You need to make sure the type is correct before running the predicate
|
---|
| 889 | % because the predicate can depend on that.
|
---|
[5a4f1a8] | 890 |
|
---|
| 891 | \autoref{f:ResumptionTransformation} shows the pattern used to transform
|
---|
[cd03b76d] | 892 | a \CFA try statement with catchResume clauses into the appropriate
|
---|
| 893 | C functions.
|
---|
[9d7e5cb] | 894 |
|
---|
[c21f5a9] | 895 | \begin{figure}
|
---|
| 896 | \begin{cfa}
|
---|
| 897 | try {
|
---|
| 898 | // TRY BLOCK
|
---|
| 899 | } catchResume (Exception1 * name1 ; check(name1)) {
|
---|
| 900 | // CATCH BLOCK 1
|
---|
| 901 | } catchResume (Exception2 * name2) {
|
---|
| 902 | // CATCH BLOCK 2
|
---|
| 903 | }
|
---|
| 904 | \end{cfa}
|
---|
| 905 |
|
---|
[d02e547] | 906 | \transformline
|
---|
[5a4f1a8] | 907 |
|
---|
[c21f5a9] | 908 | \begin{cfa}
|
---|
| 909 | bool handle(exception_t * __exception_inst) {
|
---|
| 910 | {
|
---|
| 911 | Exception1 * name1;
|
---|
[887fc79] | 912 | if (name1 = (virtual Exception1 *)__exception_inst
|
---|
| 913 | && check(name1)) {
|
---|
[c21f5a9] | 914 | // CATCH BLOCK 1
|
---|
| 915 | return 1;
|
---|
| 916 | }
|
---|
| 917 | }
|
---|
| 918 | {
|
---|
| 919 | Exception2 * name2;
|
---|
| 920 | if (name2 = (virtual Exception2 *)__exception_inst) {
|
---|
| 921 | // CATCH BLOCK 2
|
---|
| 922 | return 2;
|
---|
| 923 | }
|
---|
| 924 | }
|
---|
| 925 | return false;
|
---|
| 926 | }
|
---|
| 927 | struct __try_resume_node __resume_node
|
---|
| 928 | __attribute__((cleanup( __cfaehm_try_resume_cleanup )));
|
---|
| 929 | __cfaehm_try_resume_setup( &__resume_node, handler );
|
---|
| 930 | \end{cfa}
|
---|
| 931 |
|
---|
| 932 | \caption{Resumption Transformation}
|
---|
| 933 | \label{f:ResumptionTransformation}
|
---|
| 934 | \end{figure}
|
---|
[26ca815] | 935 |
|
---|
[12b4ab4] | 936 | % Recursive Resumption Stuff:
|
---|
[5a4f1a8] | 937 | \autoref{f:ResumptionMarking} shows search skipping
|
---|
| 938 | (see \vpageref{s:ResumptionMarking}), which ignores parts of
|
---|
[df24d37] | 939 | the stack
|
---|
[ba2e8f0] | 940 | already examined, and is accomplished by updating the front of the list as
|
---|
| 941 | the search continues.
|
---|
| 942 | Before the handler is called at a matching node, the head of the list
|
---|
[7eb6eb5] | 943 | is updated to the next node of the current node. After the search is complete,
|
---|
| 944 | successful or not, the head of the list is reset.
|
---|
[5a4f1a8] | 945 | % No paragraph?
|
---|
[7eb6eb5] | 946 | This mechanism means the current handler and every handler that has already
|
---|
| 947 | been checked are not on the list while a handler is run. If a resumption is
|
---|
[5a4f1a8] | 948 | thrown during the handling of another resumption, the active handlers and all
|
---|
[ba2e8f0] | 949 | the other handlers checked up to this point are not checked again.
|
---|
[5a4f1a8] | 950 | % No paragraph?
|
---|
| 951 | This structure also supports new handlers added while the resumption is being
|
---|
[12b4ab4] | 952 | handled. These are added to the front of the list, pointing back along the
|
---|
[5a4f1a8] | 953 | stack --- the first one points over all the checked handlers ---
|
---|
| 954 | and the ordering is maintained.
|
---|
[c21f5a9] | 955 |
|
---|
| 956 | \begin{figure}
|
---|
[ba2e8f0] | 957 | \centering
|
---|
[9b0bb79] | 958 | \input{resumption-marking}
|
---|
[c21f5a9] | 959 | \caption{Resumption Marking}
|
---|
| 960 | \label{f:ResumptionMarking}
|
---|
| 961 | \end{figure}
|
---|
[7eb6eb5] | 962 |
|
---|
| 963 | \label{p:zero-cost}
|
---|
[5a4f1a8] | 964 | Finally, the resumption implementation has a cost for entering/exiting a try
|
---|
| 965 | statement with @catchResume@ clauses, whereas a try statement with @catch@
|
---|
[7eb6eb5] | 966 | clauses has zero-cost entry/exit. While resumption does not need the stack
|
---|
| 967 | unwinding and cleanup provided by libunwind, it could use the search phase to
|
---|
| 968 | providing zero-cost enter/exit using the LSDA. Unfortunately, there is no way
|
---|
| 969 | to return from a libunwind search without installing a handler or raising an
|
---|
[830299f] | 970 | error. Although workarounds might be possible, they are beyond the scope of
|
---|
[7eb6eb5] | 971 | this thesis. The current resumption implementation has simplicity in its
|
---|
| 972 | favour.
|
---|
[26ca815] | 973 | % Seriously, just compare the size of the two chapters and then consider
|
---|
| 974 | % that unwind is required knowledge for that chapter.
|
---|
| 975 |
|
---|
| 976 | \section{Finally}
|
---|
| 977 | % Uses destructors and GCC nested functions.
|
---|
[ba2e8f0] | 978 |
|
---|
| 979 | %\autoref{code:cleanup}
|
---|
| 980 | A finally clause is handled by converting it into a once-off destructor.
|
---|
| 981 | The code inside the clause is placed into GCC nested-function
|
---|
| 982 | with a unique name, and no arguments or return values.
|
---|
| 983 | This nested function is
|
---|
| 984 | then set as the cleanup function of an empty object that is declared at the
|
---|
| 985 | beginning of a block placed around the context of the associated try
|
---|
| 986 | statement (see \autoref{f:FinallyTransformation}).
|
---|
| 987 |
|
---|
| 988 | \begin{figure}
|
---|
| 989 | \begin{cfa}
|
---|
| 990 | try {
|
---|
| 991 | // TRY BLOCK
|
---|
| 992 | } finally {
|
---|
| 993 | // FINALLY BLOCK
|
---|
| 994 | }
|
---|
| 995 | \end{cfa}
|
---|
| 996 |
|
---|
| 997 | \transformline
|
---|
| 998 |
|
---|
| 999 | \begin{cfa}
|
---|
| 1000 | {
|
---|
| 1001 | void finally(void *__hook){
|
---|
| 1002 | // FINALLY BLOCK
|
---|
| 1003 | }
|
---|
| 1004 | __attribute__ ((cleanup(finally)))
|
---|
| 1005 | struct __cfaehm_cleanup_hook __finally_hook;
|
---|
| 1006 | {
|
---|
| 1007 | // TRY BLOCK
|
---|
| 1008 | }
|
---|
| 1009 | }
|
---|
| 1010 | \end{cfa}
|
---|
| 1011 |
|
---|
| 1012 | \caption{Finally Transformation}
|
---|
| 1013 | \label{f:FinallyTransformation}
|
---|
| 1014 | \end{figure}
|
---|
| 1015 |
|
---|
| 1016 | The rest is handled by GCC.
|
---|
| 1017 | The TRY BLOCK
|
---|
| 1018 | contains the try block itself as well as all code generated for handlers.
|
---|
| 1019 | Once that code has completed,
|
---|
| 1020 | control exits the block and the empty object is cleaned
|
---|
[7eb6eb5] | 1021 | up, which runs the function that contains the finally code.
|
---|
[26ca815] | 1022 |
|
---|
| 1023 | \section{Cancellation}
|
---|
| 1024 | % Stack selections, the three internal unwind functions.
|
---|
| 1025 |
|
---|
| 1026 | Cancellation also uses libunwind to do its stack traversal and unwinding,
|
---|
[9d7e5cb] | 1027 | however it uses a different primary function: @_Unwind_ForcedUnwind@. Details
|
---|
| 1028 | of its interface can be found in the Section~\vref{s:ForcedUnwind}.
|
---|
[26ca815] | 1029 |
|
---|
[7eb6eb5] | 1030 | The first step of cancellation is to find the cancelled stack and its type:
|
---|
[7372065] | 1031 | coroutine, thread or main thread.
|
---|
[5a4f1a8] | 1032 | In \CFA, a thread (the construct the user works with) is a user-level thread
|
---|
| 1033 | (point of execution) paired with a coroutine, the thread's main coroutine.
|
---|
| 1034 | The thread library also stores pointers to the main thread and the current
|
---|
[7372065] | 1035 | thread.
|
---|
[5a4f1a8] | 1036 | If the current thread's main and current coroutines are the same then the
|
---|
| 1037 | current stack is a thread stack, otherwise it is a coroutine stack.
|
---|
| 1038 | If the current stack is a thread stack, it is also the main thread stack
|
---|
| 1039 | if and only if the main and current threads are the same.
|
---|
[0c4df43] | 1040 |
|
---|
[7eb6eb5] | 1041 | However, if the threading library is not linked, the sequential execution is on
|
---|
| 1042 | the main stack. Hence, the entire check is skipped because the weak-symbol
|
---|
[5a4f1a8] | 1043 | function is loaded. Therefore, main thread cancellation is unconditionally
|
---|
[7eb6eb5] | 1044 | performed.
|
---|
| 1045 |
|
---|
| 1046 | Regardless of how the stack is chosen, the stop function and parameter are
|
---|
| 1047 | passed to the forced-unwind function. The general pattern of all three stop
|
---|
[5a4f1a8] | 1048 | functions is the same: continue unwinding until the end of stack and
|
---|
[ba2e8f0] | 1049 | then perform the appropriate transfer.
|
---|
[0c4df43] | 1050 |
|
---|
[7eb6eb5] | 1051 | For main stack cancellation, the transfer is just a program abort.
|
---|
| 1052 |
|
---|
[0c4df43] | 1053 | For coroutine cancellation, the exception is stored on the coroutine's stack,
|
---|
[7eb6eb5] | 1054 | and the coroutine context switches to its last resumer. The rest is handled on
|
---|
[5a4f1a8] | 1055 | the backside of the resume, which checks if the resumed coroutine is
|
---|
[7eb6eb5] | 1056 | cancelled. If cancelled, the exception is retrieved from the resumed coroutine,
|
---|
| 1057 | and a @CoroutineCancelled@ exception is constructed and loaded with the
|
---|
| 1058 | cancelled exception. It is then resumed as a regular exception with the default
|
---|
| 1059 | handler coming from the context of the resumption call.
|
---|
| 1060 |
|
---|
| 1061 | For thread cancellation, the exception is stored on the thread's main stack and
|
---|
| 1062 | then context switched to the scheduler. The rest is handled by the thread
|
---|
| 1063 | joiner. When the join is complete, the joiner checks if the joined thread is
|
---|
| 1064 | cancelled. If cancelled, the exception is retrieved and the joined thread, and
|
---|
| 1065 | a @ThreadCancelled@ exception is constructed and loaded with the cancelled
|
---|
| 1066 | exception. The default handler is passed in as a function pointer. If it is
|
---|
| 1067 | null (as it is for the auto-generated joins on destructor call), the default is
|
---|
| 1068 | used, which is a program abort.
|
---|
| 1069 | %; which gives the required handling on implicate join.
|
---|