libdlog: readd the destructor
[platform/core/system/dlog.git] / src / libdlog / log.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: t -*-
2  * DLOG
3  * Copyright (c) 2005-2008, The Android Open Source Project
4  * Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
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 // C
20 #include <assert.h>
21 #include <stdbool.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 // POSIX
26 #include <pthread.h>
27 #include <unistd.h>
28
29 // DLog
30 #include <dynamic_config.h>
31 #include <libdlog.h>
32 #include <logcommon.h>
33 #include "logconfig.h"
34 #include "loglimiter.h"
35
36 #define DEFAULT_CONFIG_LIMITER false
37 #define DEFAULT_CONFIG_PLOG true
38 #define DEFAULT_CONFIG_DEBUGMODE 0
39 #define DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS 0
40
41 /**
42  * @brief Points to a function which writes a log message
43  * @details The function pointed to depends on the backend used
44  * @param[in] log_id ID of the buffer to log to. Belongs to (LOG_ID_INVALID, LOG_ID_MAX) non-inclusive
45  * @param[in] prio Priority of the message.
46  * @param[in] tag The message tag, identifies the sender.
47  * @param[in] msg The contents of the message.
48  * @return Returns the number of bytes written on success and a negative error value on error.
49  * @see __dlog_init_backend
50  */
51 int (*write_to_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg) = NULL;
52 void (*destroy_backend)();
53
54 pthread_rwlock_t log_limiter_lock = PTHREAD_RWLOCK_INITIALIZER;
55 static pthread_rwlock_t log_destruction_lock = PTHREAD_RWLOCK_INITIALIZER;
56
57 extern void __dlog_init_pipe(const struct log_config *conf);
58 extern void __dlog_init_android(const struct log_config *conf);
59
60 bool limiter;
61 bool dynamic_config;
62 bool plog[LOG_ID_MAX];
63 bool plog_default_values[LOG_ID_MAX];
64
65 static int debugmode;
66 static int fatal_assert;
67 static int limiter_apply_to_all_buffers;
68
69 static void __configure_limiter(struct log_config *config)
70 {
71         assert(config);
72
73         if (!limiter)
74                 return;
75
76         limiter = __log_limiter_create(config);
77 }
78
79 static int __configure_backend(struct log_config *config)
80 {
81         assert(config);
82
83         const char *const backend = log_config_get(config, "backend");
84         if (!backend)
85                 return 0;
86
87         if (!strcmp(backend, "pipe"))
88                 __dlog_init_pipe(config);
89         else if (!strcmp(backend, "logger"))
90                 __dlog_init_android(config);
91         else
92                 return 0;
93
94         return 1;
95 }
96
97 static void __set_plog_default_values()
98 {
99         for (int i = 0; i < NELEMS(plog); ++i)
100                 plog_default_values[i] = plog[i];
101 }
102
103 static void __initialize_plog(const struct log_config *config)
104 {
105         assert(config);
106
107         const bool plog_default = log_config_get_boolean(config, "plog", DEFAULT_CONFIG_PLOG);
108         for (int i = 0; i < NELEMS(plog); ++i)
109                 plog[i] = plog_default;
110         plog[LOG_ID_APPS] = true; // the default does not apply here for backward compatibility reasons.
111         __set_plog_default_values();
112 }
113
114 static void __configure_parameters(struct log_config *config)
115 {
116         assert(config);
117
118         __initialize_plog(config);
119         __update_plog(config);
120         __set_plog_default_values();
121
122         debugmode = log_config_get_int(config, "debugmode", DEFAULT_CONFIG_DEBUGMODE);
123         fatal_assert = access(DEBUGMODE_FILE, F_OK) != -1;
124         limiter = log_config_get_boolean(config, "limiter", DEFAULT_CONFIG_LIMITER);
125         limiter_apply_to_all_buffers = log_config_get_int(config,
126                                                                         "limiter_apply_to_all_buffers",
127                                                                         DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS);
128 }
129
130 void __update_plog(const struct log_config *conf)
131 {
132         assert(conf);
133
134         for (int i = 0; i < NELEMS(plog); ++i) {
135                 char key[MAX_CONF_KEY_LEN];
136                 const int r = snprintf(key, sizeof key, "enable_%s", log_name_by_id((log_id_t)i));
137                 if (r < 0)
138                         continue;
139                 plog[i] = log_config_get_boolean(conf, key, plog_default_values[i]);
140         }
141 }
142
143 /**
144  * @brief Configure the library
145  * @details Reads relevant config values
146  * @remarks The constructor has the highest possible priority (100 and below are reserved).
147  *          This is because other libraries are likely to use libdlog and might want to
148  *          use it as early as in their own constructor. This means that libdlog must be
149  *          constructed as soon as possible.
150  */
151 #ifdef UNIT_TEST
152 void __configure(void)
153 #else
154 static void __attribute__((constructor(101))) __configure(void)
155 #endif
156 {
157         struct log_config config;
158
159         if (log_config_read(&config) < 0)
160                 goto out;
161
162         dynamic_config = __dynamic_config_create(&config);
163
164         __configure_parameters(&config);
165
166         if (!__configure_backend(&config))
167                 goto out;
168
169         __configure_limiter(&config);
170
171 out:
172         log_config_free(&config);
173         return;
174 }
175
176 /**
177  * @brief Fatal assertion
178  * @details Conditionally crash the sucka who sent the log
179  * @param[in] prio Priority of the log
180  */
181 static void __dlog_fatal_assert(int prio)
182 {
183         assert(!fatal_assert || (prio != DLOG_FATAL));
184 }
185
186 /**
187  * @brief Check log validity
188  * @details Checks whether the log is valid and eligible for printing
189  * @param[in] log_id The target buffer ID
190  * @param[in] prio The log's priority
191  * @param[in] tag The log's tag
192  * @return DLOG_ERROR_NONE on success, else an error code.
193  * @retval DLOG_ERROR_INVALID_PARAMETER Invalid parameter
194  */
195 static int dlog_check_validity(log_id_t log_id, int prio, const char *tag)
196 {
197         if (!tag)
198                 return DLOG_ERROR_INVALID_PARAMETER;
199
200         if (log_id <= LOG_ID_INVALID || LOG_ID_MAX <= log_id)
201                 return DLOG_ERROR_INVALID_PARAMETER;
202
203         return DLOG_ERROR_NONE;
204 }
205
206 /**
207  * @brief Check log against limiter rules
208  * @details Checks whether the log passes current limiter rules
209  * @param[in] log_id The target buffer ID
210  * @param[in] prio The log's priority
211  * @param[in] tag The log's tag
212  * @return DLOG_ERROR_NONE on success, else an error code.
213  * @retval DLOG_ERROR_NOT_PERMITTED Not permitted
214  */
215 static int dlog_check_limiter(log_id_t log_id, int prio, const char *tag)
216 {
217         if (!debugmode && prio <= DLOG_DEBUG)
218                 return DLOG_ERROR_NOT_PERMITTED;
219
220         if (dynamic_config)
221                 __dynamic_config_update();
222
223         if (limiter) {
224                 pthread_rwlock_rdlock(&log_limiter_lock);
225                 int should_log = __log_limiter_pass_log(tag, prio);
226                 pthread_rwlock_unlock(&log_limiter_lock);
227
228                 if (!should_log) {
229                         return DLOG_ERROR_NOT_PERMITTED;
230                 } else if (should_log < 0) {
231                         write_to_log(log_id, prio, tag,
232                                         "Your log has been blocked due to limit of log lines per minute.");
233                         return DLOG_ERROR_NOT_PERMITTED;
234                 }
235         }
236
237         /* This can change due to __dynamic_config_update(), but is atomic and its
238          * value implies nothing else so does not need to be under a lock. */
239         if (!plog[log_id])
240                 return DLOG_ERROR_NOT_PERMITTED;
241
242         return DLOG_ERROR_NONE;
243 }
244
245 static int __write_to_log_critical_section(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap, bool check_should_log)
246 {
247         if ((check_should_log || limiter_apply_to_all_buffers) && (dlog_check_limiter(log_id, prio, tag) < 0))
248                 return DLOG_ERROR_NONE;
249
250         char buf[LOG_MAX_PAYLOAD_SIZE];
251         vsnprintf(buf, sizeof buf, fmt, ap);
252         return write_to_log(log_id, prio, tag, buf);
253 }
254
255 static int __write_to_log(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap, bool check_should_log)
256 {
257         int ret = dlog_check_validity(log_id, prio, tag);
258         if (ret < 0)
259                 return ret;
260
261         /* The only thing that needs to be protected here is `write_to_log` since
262          * all other resources already have their own specific locks (and even the
263          * pointer could be made to point at a null handler instead of a true NULL)
264          * but giving this guarantee makes everything a lot simpler as it removes
265          * the risk of something suddenly becoming NULL during processing. */
266         pthread_rwlock_rdlock(&log_destruction_lock);
267         ret = write_to_log ? __write_to_log_critical_section(log_id, prio, tag, fmt, ap, check_should_log) : DLOG_ERROR_NOT_PERMITTED;
268         pthread_rwlock_unlock(&log_destruction_lock);
269
270         return ret;
271 }
272
273 /**
274  * @brief Print log
275  * @details Print a log line
276  * @param[in] log_id The target buffer ID
277  * @param[in] prio Priority
278  * @param[in] tag tag
279  * @param[in] fmt Format (same as printf)
280  * @param[in] ap Argument list
281  * @return Bytes written, or negative error
282  */
283 int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
284 {
285         int ret = __write_to_log(log_id, prio, tag, fmt, ap, true);
286         __dlog_fatal_assert(prio);
287
288         return ret;
289 }
290
291 /**
292  * @brief Print log
293  * @details Print a log line
294  * @param[in] log_id The target buffer ID
295  * @param[in] prio Priority
296  * @param[in] tag tag
297  * @param[in] fmt Format (same as printf)
298  * @return Bytes written, or negative error
299  */
300 int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
301 {
302         va_list ap;
303
304         va_start(ap, fmt);
305         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
306         va_end(ap);
307
308         return ret;
309 }
310
311 int dlog_vprint(log_priority prio, const char *tag, const char *fmt, va_list ap)
312 {
313         return __write_to_log(LOG_ID_APPS, prio, tag, fmt, ap, false);
314 }
315
316 int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
317 {
318         va_list ap;
319
320         va_start(ap, fmt);
321         int ret = dlog_vprint(prio, tag, fmt, ap);
322         va_end(ap);
323
324         return ret;
325 }
326
327 /**
328  * @brief Finalize DLog
329  * @details Finalizes and deallocates the library
330  * @notes Used directly in tests; brings back the pre-init state
331  */
332 #ifndef UNIT_TEST
333 static
334 #endif
335 void __dlog_fini(void)
336 {
337         if (destroy_backend) {
338                 destroy_backend();
339                 destroy_backend = NULL;
340         }
341         write_to_log = NULL;
342
343         __log_limiter_destroy();
344         __dynamic_config_destroy();
345 }
346
347 #ifdef UNIT_TEST
348 void
349 #else
350 static void __attribute__((destructor))
351 #endif
352 __dlog_destroy(void)
353 {
354         pthread_rwlock_wrlock(&log_destruction_lock);
355         __dlog_fini();
356
357         /* IMPORTANT! The lock is NEVER RELEASED. This is done ON PURPOSE.
358          * The critical section can still be reached in some ways, NONE LEGAL.
359          *
360          * The first is that the program links the library dynamically and keeps
361          * pointers to API functions past dlclose(). This is UNDEFINED BEHAVIOUR
362          * and the implementation is NOT REQUIRED to keep the functions in memory
363          * AT ALL and doing this COULD HAVE ALREADY CRASHED the program under a
364          * different implementation.
365          *
366          * The second is when linking statically and FAILING TO JOIN threads before
367          * exit(). These threads then typically keep running and can access the
368          * library interface. However, they WILL DIE ANY MOMENT NOW ANYWAY so
369          * getting deadlocked is of no consequence.
370          *
371          * In theory it would be possible to detect that destruction has already
372          * taken place and reinitialize the library to salvage a logging attempt.
373          * This is a HORRIBLE IDEA since without a destructor to rely on, either
374          * those RESOURCES WOULD LEAK or we would have to MASSIVELY CONVOLUTE our
375          * logic for manual destruction in such cases. */
376 }
377