Debian Codegraph @

vendor/c_exception/docs/CException.md

raw
1
2 CException
3 ==========
4
5 CException is a basic exception framework for C, suitable for use in
6 embedded applications. It provides an exception framework similar in
7 use to C++, but with much less overhead.
8
9
10 CException uses C standard library functions `setjmp` and `longjmp` to
11 operate. As long as the target system has these two functions defined,
12 this library should be useable with very little configuration. It
13 even supports environments where multiple program flows are in use,
14 such as real-time operating systems.
15
16
17 There are about a gabillion exception frameworks using a similar
18 setjmp/longjmp method out there... and there will probably be more
19 in the future. Unfortunately, when we started our last embedded
20 project, all those that existed either (a) did not support multiple
21 tasks (therefore multiple stacks) or (b) were way more complex than
22 we really wanted. CException was born.
23
24
25 *Why use CException?*
26
27
28 0. It's ANSI C, and it beats passing error codes around.
29 1. You want something simple... CException throws a single id. You can
30 define those ID's to be whatever you like. You might even choose which
31 type that number is for your project. But that's as far as it goes.
32 We weren't interested in passing objects or structs or strings...
33 just simple error codes.
34 2. Performance... CException can be configured for single tasking or
35 multitasking. In single tasking, there is very little overhead past
36 the setjmp/longjmp calls (which are already fast). In multitasking,
37 your only additional overhead is the time it takes you to determine
38 a unique task id 0 - num_tasks.
39
40
41 For the latest version, go to [ThrowTheSwitch.org](http://throwtheswitch.org)
42
43
44 CONTENTS OF THIS DOCUMENT
45 =========================
46
47 * Usage
48 * Limitations
49 * API
50 * Configuration
51 * Testing
52 * License
53
54
55 Usage
56 -----
57
58 Code that is to be protected are wrapped in `Try { } Catch { }` blocks.
59 The code directly following the Try call is "protected", meaning that
60 if any Throws occur, program control is directly transferred to the
61 start of the Catch block.
62
63
64 A numerical exception ID is included with Throw, and is made accessible
65 from the Catch block.
66
67
68 Throws can occur from within function calls (nested as deeply as you
69 like) or directly from within the function itself.
70
71
72
73 Limitations
74 -----------
75
76
77 This library was made to be as fast as possible, and provide basic
78 exception handling. It is not a full-blown exception library. Because
79 of this, there are a few limitations that should be observed in order
80 to successfully utilize this library:
81
82 1. Do not directly "return" from within a `Try` block, nor `goto`
83 into or out of a `Try` block.
84
85 *Why?*
86
87 The `Try` macro allocates some local memory and alters a global
88 pointer. These are cleaned up at the top of the `Catch` macro.
89 Gotos and returns would bypass some of these steps, resulting in
90 memory leaks or unpredictable behavior.
91
92
93 2. If (a) you change local (stack) variables within your `Try` block,
94 AND (b) wish to make use of the updated values after an exception
95 is thrown, those variables should be made `volatile`. Note that this
96 is ONLY for locals and ONLY when you need access to them after a
97 `Throw`.
98
99 *Why?*
100
101 Compilers optimize. There is no way to guarantee that the actual
102 memory location was updated and not just a register unless the
103 variable is marked volatile.
104
105 As an example, if we had the following code, the value `b` is
106 very likely at risk. It is assigned to the value `3` inside the
107 `Try` block, but the compiler may or may not have written that
108 variable to an actual memory location when the Throw happens. If
109 it did, the `printf` will have a `3` for the second value. If not,
110 it will still have a `0`. Changing `b` to `volatile` would
111 guarantee it is the correct value.
112
113 ```
114 void func(int *a)
115 {
116 // ...
117 int b = 0;
118 Try {
119 *a += 2;
120 b = *a;
121 Throw(MY_EX);
122 } Catch(e) {
123 // ...
124 }
125 printf("%d ?= %d", a, b);
126 }
127 void main()
128 {
129 int x = 1;
130 func(&x);
131 printf("%d", x);
132 }
133 ```
134
135 With most compilers, the `*a` and `x` values are NOT at risk.
136 We're dereferencing the pointer, which usually will force
137 memory interaction. Optimizing compilers DO optimize, though,
138 and it IS possible that even these values may have been cached
139 and not written to the final memory location. In those instances,
140 they would both report `1`.
141
142 If you have a lot of situations like this and a strong optimizing
143 compiler, it is best to reduce the optimization level when using
144 CException.
145
146 3. Memory which is `malloc`'d or `new`'d is not automatically released
147 when an error is thrown. This will sometimes be desirable, and
148 othertimes may not. It will be the responsibility of the `Catch`
149 block to perform this kind of cleanup.
150
151 *Why?*
152
153 There's just no easy way to track `malloc`'d memory, etc., without
154 replacing or wrapping malloc calls or something like that. This
155 is a light framework, so these options were not desirable.
156
157
158
159 API
160 ---
161
162 ###Try
163
164 `Try` is a macro which starts a protected block. It MUST be followed by
165 a pair of braces or a single protected line (similar to an 'if'),
166 enclosing the data that is to be protected. It **must** be followed by a
167 `Catch` block (don't worry, you'll get compiler errors to let you know if
168 you mess any of that up).
169
170
171 ###Catch(e)
172
173 `Catch` is a macro which ends the `Try` block and starts the error handling
174 block. The `Catch` block is called if and only if an exception was thrown
175 while within the `Try` block. This error was thrown by a `Throw` call
176 somewhere within `Try` (or within a function called within `Try`, or a function
177 called by a function called within `Try`, etc).
178
179 The single parameter `e` is filled with the error code which was thrown.
180 This can be used for reporting, conditional cleanup, etc. (or you can just
181 ignore it if you really want... people ignore return codes all the time,
182 right?). `e` should be of type `EXCEPTION_T`
183
184
185 ###Throw(e)
186
187 This is the method of throwing an error. A `Throw` should only occur from within a
188 protected (`Try` ... `Catch`) block, though it may easily be nested many function
189 calls deep without an impact on performance or functionality. `Throw` takes
190 a single argument, which is an exception id which will be passed to `Catch`
191 as the reason for the error.
192
193 If you wish to rethrow an error, this can be done by calling `Throw(e)` with
194 the error code you just caught. It **is** valid to throw from a catch block.
195
196
197 ###ExitTry()
198
199 On rare occasion, you might want to immediately exit your current `Try` block
200 but **not** treat this as an error. Don't run the `Catch`. Just start executing
201 from after the `Catch` as if nothing had happened... That's what `ExitTry` is
202 for.
203
204
205 CONFIGURATION
206 -------------
207
208 CException is a mostly portable library. It has one universal
209 dependency, and some macros which are required if working in a
210 multi-tasking environment.
211
212 1. The standard C library setjmp must be available. Since this is part
213 of the standard library, chances are good that you'll be fine.
214
215 2. If working in a multitasking environment, methods for obtaining an
216 index into an array of frames and to get the overall number of
217 id's are required. If the OS supports a method to retrieve Task
218 ID's, and those Tasks are number 0, 1, 2... you are in an ideal
219 situation. Otherwise, a more creative mapping function may be
220 required. Note that this function is likely to be called twice
221 for each protected block and once during a throw. This is the
222 only overhead in the system.
223
224
225 Exception.h
226 -----------
227
228 By convention, most projects include `Exception.h` which defines any
229 further requirements, then calls `CException.h` to do the gruntwork. All
230 of these are optional. You could directly include `CException.h` if
231 you wanted and just use the defaults provided.
232
233 * `EXCEPTION_T`
234 * Set this to the type you want your exception id's to be. Defaults to 'unsigned int'.
235
236 * `EXCEPTION_NONE`
237 * Set this to a number which will never be an exception id in your system. Defaults to `0x5a5a5a5a`.
238
239 * `EXCEPTION_GET_ID`
240 * If in a multi-tasking environment, this should be
241 set to be a call to the function described in #2 above.
242 Defaults to just return `0` all the time (good for
243 single tasking environments)
244
245 * `EXCEPTION_NUM_ID`
246 * If in a multi-tasking environment, this should be set
247 to the number of ID's required (usually the number of
248 tasks in the system). Defaults to `1` (for single
249 tasking environments).
250
251 * `CEXCEPTION_NO_CATCH_HANDLER(id)`
252 * This macro can be optionally specified.
253 It allows you to specify code to be called when a Throw
254 is made outside of `Try` ... `Catch` protection. Consider
255 this the emergency fallback plan for when something has
256 gone terribly wrong.
257
258
259 You may also want to include any header files which will commonly be
260 needed by the rest of your application where it uses exception handling
261 here. For example, OS header files or exception codes would be useful.
262
263
264 Finally, there are some hook macros which you can implement to inject
265 your own target-specific code in particular places. It is a rare instance
266 where you will need these, but they are here if you need them:
267
268
269 * `CEXCEPTION_HOOK_START_TRY`
270 * called immediately before the Try block
271
272 * `CEXCEPTION_HOOK_HAPPY_TRY`
273 * called immediately after the Try block if no exception was thrown
274
275 * `CEXCEPTION_HOOK_AFTER_TRY`
276 * called immediately after the Try block OR before an exception is caught
277
278 * `CEXCEPTION_HOOK_START_CATCH`
279 * called immediately before the catch
280
281
282
283 TESTING
284 -------
285
286
287 If you want to validate that CException works with your tools or that
288 it works with your custom configuration, you may want to run the test
289 suite.
290
291
292 The test suite included makes use of the `Unity` Test Framework. It will
293 require a native C compiler. The example makefile uses MinGW's gcc.
294 Modify the makefile to include the proper paths to tools, then run `make`
295 to compile and run the test application.
296
297 * `C_COMPILER`
298 * The C compiler to use to perform the tests
299
300 * `C_LIBS`
301 * The path to the C libraries (including setjmp)
302
303 * `UNITY_DIR`
304 * The path to the Unity framework (required to run tests)
305 (get it at [ThrowTheSwitch.org](http://throwtheswitch.org))
306
307
308
309 LICENSE
310 -------
311
312 This software is licensed under the MIT License
313
314 Copyright (c) 2007-2020 Mark VanderVoord
315
316 Permission is hereby granted, free of charge, to any person obtaining a copy
317 of this software and associated documentation files (the "Software"), to deal
318 in the Software without restriction, including without limitation the rights
319 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
320 copies of the Software, and to permit persons to whom the Software is
321 furnished to do so, subject to the following conditions:
322
323 The above copyright notice and this permission notice shall be included in
324 all copies or substantial portions of the Software.
325
326 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
327 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
328 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
329 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
330 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
331 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
332 THE SOFTWARE.