afb-debug: add features for debugging
[src/app-framework-binder.git] / src / afb-debug.c
1 /*
2  Copyright 2017 IoT.bzh
3
4  author: José Bollo <jose.bollo@iot.bzh>
5
6  Licensed under the Apache License, Version 2.0 (the "License");
7  you may not use this file except in compliance with the License.
8  You may obtain a copy of the License at
9
10      http://www.apache.org/licenses/LICENSE-2.0
11
12  Unless required by applicable law or agreed to in writing, software
13  distributed under the License is distributed on an "AS IS" BASIS,
14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  See the License for the specific language governing permissions and
16  limitations under the License.
17 */
18
19 #include "afb-debug.h"
20
21 #if defined(AFB_INSERT_DEBUG_FEATURES)
22
23 #define _GNU_SOURCE
24 #include <stdlib.h>
25 #include <string.h>
26 #include <signal.h>
27
28 #include "verbose.h"
29
30 static char key_env_break[] = "AFB_DEBUG_BREAK";
31 static char key_env_wait[] = "AFB_DEBUG_WAIT";
32 static char separs[] = ", \t\n";
33
34 static int has_key(const char *key, const char *list)
35 {
36         if (list && key) {
37                 list += strspn(list, separs);
38                 while (*list) {
39                         size_t s = strcspn(list, separs);
40                         if (!strncasecmp(list, key, s) && !key[s])
41                                 return 1;
42                         list += s;
43                         list += strspn(list, separs);
44                 }
45         }
46         return 0;
47 }
48
49 static void handler(int signum)
50 {
51 }
52
53 void afb_debug(const char *key)
54 {
55         enum { None, Break, Wait } action;
56
57         if (has_key(key, secure_getenv(key_env_break)))
58                 action = Break;
59         else if (has_key(key, secure_getenv(key_env_wait)))
60                 action = Wait;
61         else
62                 action = None;
63
64         if (action != None) {
65                 const char *a = action == Break ? "BREAK" : "WAIT";
66                 struct sigaction sa, psa;
67                 sigset_t ss;
68
69                 NOTICE("DEBUG %s before %s", a, key);
70                 memset(&sa, 0, sizeof sa);
71                 sa.sa_handler = handler;
72                 sigaction(SIGINT, &sa, &psa);
73                 if (action == Break) {
74                         raise(SIGINT);
75                 } else {
76                         sigemptyset(&ss);
77                         sigaddset(&ss, SIGINT);
78                         sigwaitinfo(&ss, NULL);
79                 }
80                 sigaction(SIGINT, &psa, NULL);
81                 NOTICE("DEBUG %s after %s", a, key);
82         }
83 }
84
85 #endif
86