ISO14443: Fix Dead Store (Dead assignement/Dead increment) Warning found by Clang
[metze/wireshark/wip.git] / epan / except.c
1 /*
2  * Portable Exception Handling for ANSI C.
3  * Copyright (C) 1999 Kaz Kylheku <kaz@ashi.footprints.net>
4  *
5  * Free Software License:
6  *
7  * All rights are reserved by the author, with the following exceptions:
8  * Permission is granted to freely reproduce and distribute this software,
9  * possibly in exchange for a fee, provided that this copyright notice appears
10  * intact. Permission is also granted to adapt this software to produce
11  * derivative works, as long as the modified versions carry this copyright
12  * notice and additional notices stating that the work has been modified.
13  * This source code may be translated into executable form and incorporated
14  * into proprietary software; there is no requirement for such software to
15  * contain a copyright notice related to this source.
16  */
17
18 /*
19  * Modified to support throwing an exception with a null message pointer,
20  * and to have the message not be const (as we generate messages with
21  * "g_strdup_sprintf()", which means they need to be freed; using
22  * a null message means that we don't have to use a special string
23  * for exceptions with no message, and don't have to worry about
24  * not freeing that).
25  */
26
27 #include "config.h"
28
29 #include <assert.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <stdarg.h>
33 #include <limits.h>
34
35 #include <glib.h>
36
37 #include "except.h"
38
39 #ifdef _WIN32
40 #include <windows.h>
41 #include "exceptions.h"
42 #endif
43
44 #define XCEPT_BUFFER_SIZE 1024
45
46 #ifdef KAZLIB_POSIX_THREADS
47
48 #include <pthread.h>
49
50 static pthread_mutex_t init_mtx = PTHREAD_MUTEX_INITIALIZER;
51 static int init_counter;
52 static pthread_key_t top_key;
53 static pthread_key_t uh_key;
54 static pthread_key_t alloc_key;
55 static pthread_key_t dealloc_key;
56 static void unhandled_catcher(except_t *);
57
58 #define get_top() ((struct except_stacknode *) pthread_getspecific(top_key))
59 #define set_top(T) (pthread_setspecific(top_key, (T)), (void)((T) == (struct except_stacknode *) 0))
60 #define set_catcher(C) (pthread_setspecific(uh_key, (void *) (C)), (void)((C) == (void (*)(except_t *)) 0))
61 #define set_alloc(A) (pthread_setspecific(alloc_key, (void *) (A)), (void)((A) == (void *(*)(size_t)) 0))
62 #define set_dealloc(D) (pthread_setspecific(dealloc_key, (void *) (D)), (void)((D) == (void (*)(void *)) 0))
63
64 static void (*get_catcher(void))(except_t *)
65 {
66     void (*catcher)(except_t *) = (void (*)(except_t *)) pthread_getspecific(uh_key);
67     return (catcher == 0) ? unhandled_catcher : catcher;
68 }
69
70 static void *(*get_alloc(void))(size_t)
71 {
72     void *(*alloc)(size_t) = (void *(*)(size_t)) pthread_getspecific(alloc_key);
73     return (alloc == 0) ? malloc : alloc;
74 }
75
76 static void (*get_dealloc(void))(void *)
77 {
78     void (*dealloc)(void *) = (void (*)(void *)) pthread_getspecific(dealloc_key);
79     return (dealloc == 0) ? free : dealloc;
80 }
81
82 int except_init(void)
83 {
84     int retval = 1;
85
86     pthread_mutex_lock(&init_mtx);
87
88     assert (init_counter < INT_MAX);
89
90     if (init_counter++ == 0) {
91         int top_ok = (pthread_key_create(&top_key, 0) == 0);
92         int uh_ok = (pthread_key_create(&uh_key, 0) == 0);
93         int alloc_ok = (pthread_key_create(&alloc_key, 0) == 0);
94         int dealloc_ok = (pthread_key_create(&dealloc_key, 0) == 0);
95
96         if (!top_ok || !uh_ok || !alloc_ok || !dealloc_ok) {
97             retval = 0;
98             init_counter = 0;
99             if (top_ok)
100                 pthread_key_delete(top_key);
101             if (uh_ok)
102                 pthread_key_delete(uh_key);
103             if (alloc_ok)
104                 pthread_key_delete(alloc_key);
105             if (dealloc_ok)
106                 pthread_key_delete(dealloc_key);
107         }
108     }
109
110     pthread_mutex_unlock(&init_mtx);
111
112     return retval;
113 }
114
115 void except_deinit(void)
116 {
117     pthread_mutex_lock(&init_mtx);
118
119     assert (init_counter > 0);
120
121     if (--init_counter == 0) {
122         pthread_key_delete(top_key);
123         pthread_key_delete(uh_key);
124         pthread_key_delete(alloc_key);
125         pthread_key_delete(dealloc_key);
126     }
127
128     pthread_mutex_unlock(&init_mtx);
129 }
130
131 #else /* no thread support */
132
133 static int init_counter;
134 static void unhandled_catcher(except_t *);
135 static void (*uh_catcher_ptr)(except_t *) = unhandled_catcher;
136 /* We need this 'size_t' cast due to a glitch in GLib where g_malloc was prototyped
137  * as 'gpointer g_malloc (gulong n_bytes)'. This was later fixed to the correct prototype
138  * 'gpointer g_malloc (gsize n_bytes)'. In Wireshark we use the latter prototype
139  * throughout the code. We can get away with this even with older versions of GLib by
140  * adding a '(void *(*)(size_t))' cast whenever we refer to g_malloc. The only platform
141  * supported by Wireshark where this isn't safe (sizeof size_t != sizeof gulong) is Win64.
142  * However, we _always_ bundle the newest version of GLib on this platform so
143  * the size_t issue doesn't exists here. Pheew.. */
144 static void *(*allocator)(size_t) = (void *(*)(size_t)) g_malloc;
145 static void (*deallocator)(void *) = g_free;
146 static struct except_stacknode *stack_top;
147
148 #define get_top() (stack_top)
149 #define set_top(T) (stack_top = (T))
150 #define get_catcher() (uh_catcher_ptr)
151 #define set_catcher(C) (uh_catcher_ptr = (C))
152 #define get_alloc() (allocator)
153 #define set_alloc(A) (allocator = (A))
154 #define get_dealloc() (deallocator)
155 #define set_dealloc(D) (deallocator = (D))
156
157 int except_init(void)
158 {
159     assert (init_counter < INT_MAX);
160     init_counter++;
161     return 1;
162 }
163
164 void except_deinit(void)
165 {
166     assert (init_counter > 0);
167     init_counter--;
168 }
169
170 #endif
171
172
173 static int match(const volatile except_id_t *thrown, const except_id_t *caught)
174 {
175     int group_match = (caught->except_group == XCEPT_GROUP_ANY ||
176         caught->except_group == thrown->except_group);
177     int code_match = (caught->except_code == XCEPT_CODE_ANY ||
178         caught->except_code == thrown->except_code);
179
180     return group_match && code_match;
181 }
182
183 G_GNUC_NORETURN WS_MSVC_NORETURN static void do_throw(except_t *except)
184 {
185     struct except_stacknode *top;
186
187     assert (except->except_id.except_group != 0 &&
188         except->except_id.except_code != 0);
189
190     for (top = get_top(); top != 0; top = top->except_down) {
191         if (top->except_type == XCEPT_CLEANUP) {
192             top->except_info.except_cleanup->except_func(top->except_info.except_cleanup->except_context);
193         } else {
194             struct except_catch *catcher = top->except_info.except_catcher;
195             const except_id_t *pi = catcher->except_id;
196             size_t i;
197
198             assert (top->except_type == XCEPT_CATCHER);
199             except_free(catcher->except_obj.except_dyndata);
200
201             for (i = 0; i < catcher->except_size; pi++, i++) {
202                 if (match(&except->except_id, pi)) {
203                     catcher->except_obj = *except;
204                     set_top(top);
205                     longjmp(catcher->except_jmp, 1);
206                 }
207             }
208         }
209     }
210
211     set_top(top);
212     get_catcher()(except); /* unhandled exception */
213     abort();
214 }
215
216 static void unhandled_catcher(except_t *except)
217 {
218     if (except->except_message == NULL) {
219         fprintf(stderr, "Unhandled exception (group=%lu, code=%lu)\n",
220                 except->except_id.except_group,
221                 except->except_id.except_code);
222     } else {
223         fprintf(stderr, "Unhandled exception (\"%s\", group=%lu, code=%lu)\n",
224                 except->except_message, except->except_id.except_group,
225                 except->except_id.except_code);
226     }
227     abort();
228 }
229
230 static void stack_push(struct except_stacknode *node)
231 {
232     node->except_down = get_top();
233     set_top(node);
234 }
235
236 void except_setup_clean(struct except_stacknode *esn,
237         struct except_cleanup *ecl, void (*cleanf)(void *), void *context)
238 {
239     esn->except_type = XCEPT_CLEANUP;
240     ecl->except_func = cleanf;
241     ecl->except_context = context;
242     esn->except_info.except_cleanup = ecl;
243     stack_push(esn);
244 }
245
246 void except_setup_try(struct except_stacknode *esn,
247         struct except_catch *ech, const except_id_t id[], size_t size)
248 {
249    ech->except_id = id;
250    ech->except_size = size;
251    ech->except_obj.except_dyndata = 0;
252    esn->except_type = XCEPT_CATCHER;
253    esn->except_info.except_catcher = ech;
254    stack_push(esn);
255 }
256
257 struct except_stacknode *except_pop(void)
258 {
259     struct except_stacknode *top = get_top();
260     set_top(top->except_down);
261     return top;
262 }
263
264 G_GNUC_NORETURN WS_MSVC_NORETURN void except_rethrow(except_t *except)
265 {
266     struct except_stacknode *top = get_top();
267     assert (top != 0);
268     assert (top->except_type == XCEPT_CATCHER);
269     assert (&top->except_info.except_catcher->except_obj == except);
270     set_top(top->except_down);
271     do_throw(except);
272 }
273
274 G_GNUC_NORETURN WS_MSVC_NORETURN void except_throw(long group, long code, const char *msg)
275 {
276     except_t except;
277
278     except.except_id.except_group = group;
279     except.except_id.except_code = code;
280     except.except_message = msg;
281     except.except_dyndata = 0;
282
283 #ifdef _WIN32
284     if (code == DissectorError && IsDebuggerPresent()) {
285         DebugBreak();
286     }
287 #endif
288
289     do_throw(&except);
290 }
291
292 G_GNUC_NORETURN WS_MSVC_NORETURN void except_throwd(long group, long code, const char *msg, void *data)
293 {
294     except_t except;
295
296     except.except_id.except_group = group;
297     except.except_id.except_code = code;
298     except.except_message = msg;
299     except.except_dyndata = data;
300
301     do_throw(&except);
302 }
303
304 /*
305  * XXX - should we use g_strdup_sprintf() here, so we're not limited by
306  * XCEPT_BUFFER_SIZE?  We could then just use this to generate formatted
307  * messages.
308  */
309 G_GNUC_NORETURN WS_MSVC_NORETURN void except_throwf(long group, long code, const char *fmt, ...)
310 {
311     char *buf = (char *)except_alloc(XCEPT_BUFFER_SIZE);
312     va_list vl;
313
314     va_start (vl, fmt);
315     g_vsnprintf(buf, XCEPT_BUFFER_SIZE, fmt, vl);
316     va_end (vl);
317     except_throwd(group, code, buf, buf);
318 }
319
320 void (*except_unhandled_catcher(void (*new_catcher)(except_t *)))(except_t *)
321 {
322     void (*old_catcher)(except_t *) = get_catcher();
323     set_catcher(new_catcher);
324     return old_catcher;
325 }
326
327 #undef except_code
328 #undef except_group
329 #undef except_message
330 #undef except_data
331
332 unsigned long except_code(except_t *ex)
333 {
334     return ex->except_id.except_code;
335 }
336
337 unsigned long except_group(except_t *ex)
338 {
339     return ex->except_id.except_group;
340 }
341
342 const char *except_message(except_t *ex)
343 {
344     return ex->except_message;
345 }
346
347 void *except_data(except_t *ex)
348 {
349     return ex->except_dyndata;
350 }
351
352 void *except_take_data(except_t *ex)
353 {
354     void *data = ex->except_dyndata;
355     ex->except_dyndata = 0;
356     return data;
357 }
358
359 void except_set_allocator(void *(*alloc)(size_t), void (*dealloc)(void *))
360 {
361     set_alloc(alloc);
362     set_dealloc(dealloc);
363 }
364
365 void *except_alloc(size_t size)
366 {
367     void *ptr = get_alloc()(size);
368
369     if (ptr == 0)
370         except_throw(XCEPT_BAD_ALLOC, 0, "out of memory");
371     return ptr;
372 }
373
374 void except_free(void *ptr)
375 {
376     get_dealloc()(ptr);
377 }
378
379 #ifdef KAZLIB_TEST_MAIN
380
381
382 static void cleanup(void *arg)
383 {
384     printf("cleanup(\"%s\") called\n", (char *) arg);
385 }
386
387 static void bottom_level(void)
388 {
389     char buf[256];
390     printf("throw exception? "); fflush(stdout);
391     fgets(buf, sizeof buf, stdin);
392
393     if (buf[0] >= 0 && (buf[0] == 'Y' || buf[0] == 'y'))
394         except_throw(1, 1, "nasty exception");
395 }
396
397 static void top_level(void)
398 {
399     except_cleanup_push(cleanup, "argument");
400     bottom_level();
401     except_cleanup_pop(0);
402 }
403
404 int main(int argc, char **argv)
405 {
406     static const except_id_t catch[] = { { 1, 1 }, { 1, 2 } };
407     except_t *ex;
408     char *msg;
409
410     /*
411      * Nested exception ``try blocks''
412      */
413
414     /* outer */
415     except_try_push(catch, 2, &ex);
416     if (!ex) {
417         /* inner */
418         except_try_push(catch, 2, &ex);
419         if (!ex) {
420             top_level();
421         } else {
422             /* inner catch */
423             msg = except_message(ex);
424             if (msg == NULL) {
425                 printf("caught exception (inner): s=%lu, c=%lu\n",
426                        except_group(ex), except_code(ex));
427             } else {
428                 printf("caught exception (inner): \"%s\", s=%lu, c=%lu\n",
429                        msg, except_group(ex), except_code(ex));
430             }
431             except_rethrow(ex);
432         }
433         except_try_pop();
434     } else {
435         /* outer catch */
436         msg = except_message(ex);
437         if (msg == NULL) {
438             printf("caught exception (outer): s=%lu, c=%lu\n",
439                    except_group(ex), except_code(ex));
440         } else {
441             printf("caught exception (outer): \"%s\", s=%lu, c=%lu\n",
442                    except_message(ex), except_group(ex), except_code(ex));
443         }
444     }
445     except_try_pop();
446     except_throw(99, 99, "exception in main");
447     return 0;
448 }
449
450
451 #endif
452
453 /*
454  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
455  *
456  * Local variables:
457  * c-basic-offset: 4
458  * tab-width: 8
459  * indent-tabs-mode: nil
460  * End:
461  *
462  * vi: set shiftwidth=4 tabstop=8 expandtab:
463  * :indentSize=4:tabSize=8:noTabs=true:
464  */