Add __dlog_sec_print() to keep backward compatibility with existing MCD in-house...
[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_mutex_t log_construction_lock = PTHREAD_MUTEX_INITIALIZER;
56 static bool is_initialized = false;
57
58 extern void __dlog_init_pipe(const struct log_config *conf);
59 extern void __dlog_init_android(const struct log_config *conf);
60
61 bool limiter;
62 bool dynamic_config;
63 bool plog[LOG_ID_MAX];
64 bool plog_default_values[LOG_ID_MAX];
65
66 static int debugmode;
67 static int fatal_assert;
68 static int limiter_apply_to_all_buffers;
69
70 static void __configure_limiter(struct log_config *config)
71 {
72         assert(config);
73
74         if (!limiter)
75                 return;
76
77         limiter = __log_limiter_create(config);
78 }
79
80 static int __configure_backend(struct log_config *config)
81 {
82         assert(config);
83
84         const char *const backend = log_config_get(config, "backend");
85         if (!backend)
86                 return 0;
87
88         if (!strcmp(backend, "pipe"))
89                 __dlog_init_pipe(config);
90         else if (!strcmp(backend, "logger"))
91                 __dlog_init_android(config);
92         else
93                 return 0;
94
95         return 1;
96 }
97
98 static void __set_plog_default_values()
99 {
100         for (int i = 0; i < NELEMS(plog); ++i)
101                 plog_default_values[i] = plog[i];
102 }
103
104 static void __initialize_plog(const struct log_config *config)
105 {
106         assert(config);
107
108         const bool plog_default = log_config_get_boolean(config, "plog", DEFAULT_CONFIG_PLOG);
109         for (int i = 0; i < NELEMS(plog); ++i)
110                 plog[i] = plog_default;
111         plog[LOG_ID_APPS] = true; // the default does not apply here for backward compatibility reasons.
112         __set_plog_default_values();
113 }
114
115 static void __configure_parameters(struct log_config *config)
116 {
117         assert(config);
118
119         __initialize_plog(config);
120         __update_plog(config);
121         __set_plog_default_values();
122
123         debugmode = log_config_get_int(config, "debugmode", DEFAULT_CONFIG_DEBUGMODE);
124         fatal_assert = access(DEBUGMODE_FILE, F_OK) != -1;
125         limiter = log_config_get_boolean(config, "limiter", DEFAULT_CONFIG_LIMITER);
126         limiter_apply_to_all_buffers = log_config_get_int(config,
127                                                                         "limiter_apply_to_all_buffers",
128                                                                         DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS);
129 }
130
131 void __update_plog(const struct log_config *conf)
132 {
133         assert(conf);
134
135         for (int i = 0; i < NELEMS(plog); ++i) {
136                 char key[MAX_CONF_KEY_LEN];
137                 const int r = snprintf(key, sizeof key, "enable_%s", log_name_by_id((log_id_t)i));
138                 if (r < 0)
139                         continue;
140                 plog[i] = log_config_get_boolean(conf, key, plog_default_values[i]);
141         }
142 }
143
144 /**
145  * @brief Configure the library
146  * @details Reads relevant config values
147  * @remarks This is more or less a constructor, but there are some obstacles
148  *          to using it as such (i.e. with attribute constructor):
149  *
150  *  - some important pieces of the system link to dlog, they start very early
151  *    such that dlog can't properly initialize (which lasts for program lifetime)
152  *    but don't actually log anything until later on and would be fine under lazy
153  *    initialisation. The way to do it "properly" would be to expose this function
154  *    into the API so that people can manually call it when they're ready, but
155  *    one of the design goals of the current API is that it requires absolutely no
156  *    other calls than `dlog_print`. Changing it would require somebody with a
157  *    bird's eye view of the system to produce a design so I wouldn't count on it.
158  *
159  *  - the constructor would need to have as high of a priority as possible (so as
160  *    to minimize the risk of another library's constructor using uninitialized data)
161  *    but at the same time others might want some room to wrap functions before
162  *    dlog uses them (think mprobe/mcheck). This would also require a design pass.
163  */
164 #ifndef UNIT_TEST
165 static
166 #endif
167 bool __configure(void)
168 {
169         __attribute__((cleanup(log_config_free))) struct log_config config;
170
171         if (log_config_read(&config) < 0)
172                 return false;
173
174         dynamic_config = __dynamic_config_create(&config);
175
176         __configure_parameters(&config);
177
178         if (!__configure_backend(&config)) {
179                 __dynamic_config_destroy();
180                 dynamic_config = false;
181                 return false;
182         }
183
184         __configure_limiter(&config);
185         return true;
186 }
187
188 static bool first = true;
189 static bool initialize()
190 {
191         if (is_initialized)
192                 return true;
193
194         /* The mutex acts as a barrier, but otherwise the C language's
195          * machine abstraction is single-threaded. This means that the
196          * compiler is free to rearrange calls inside the mutex according
197          * to the as-if rule because it doesn't care if another thread can
198          * access it in parallel. In particular, `is_initialized = true`
199          * directly after `__configure()` could be rearranged to go in
200          * front of it because it is not touched inside that function
201          * if the compiler thinks it helps somehow (not unlikely: since
202          * it is checked before the mutex, it is very probable for it to
203          * still be in the CPU register or something like that). On top
204          * of that, some architectures (in particular, armv7l) don't have
205          * strict memory guarantees and can reorder actual memory stores
206          * on their own, even if the compiler didn't do anything fancy
207          * when creating machine code. For more info about the issue,
208          * see https://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
209          *
210          * Ultimately this means that there needs to be some sort of
211          * barrier between `__configure` and `is_initialized = true`,
212          * and the simplest way to achieve that is to just wait until
213          * the second entry into the mutex. */
214
215         bool ret;
216         pthread_mutex_lock(&log_construction_lock);
217                 if (first)
218                         first = !__configure();
219                 else
220                         is_initialized = true;
221                 ret = !first;
222         pthread_mutex_unlock(&log_construction_lock);
223         return ret;
224 }
225
226 /**
227  * @brief Fatal assertion
228  * @details Conditionally crash the sucka who sent the log
229  * @param[in] prio Priority of the log
230  */
231 static void __dlog_fatal_assert(int prio)
232 {
233         assert(!fatal_assert || (prio != DLOG_FATAL));
234 }
235
236 /**
237  * @brief Check log validity
238  * @details Checks whether the log is valid and eligible for printing
239  * @param[in] log_id The target buffer ID
240  * @param[in] prio The log's priority
241  * @param[in] tag The log's tag
242  * @return DLOG_ERROR_NONE on success, else an error code.
243  * @retval DLOG_ERROR_INVALID_PARAMETER Invalid parameter
244  */
245 static int dlog_check_validity(log_id_t log_id, int prio, const char *tag)
246 {
247         if (!tag)
248                 return DLOG_ERROR_INVALID_PARAMETER;
249
250         if (log_id <= LOG_ID_INVALID || LOG_ID_MAX <= log_id)
251                 return DLOG_ERROR_INVALID_PARAMETER;
252
253         return DLOG_ERROR_NONE;
254 }
255
256 /**
257  * @brief Check log against limiter rules
258  * @details Checks whether the log passes current limiter rules
259  * @param[in] log_id The target buffer ID
260  * @param[in] prio The log's priority
261  * @param[in] tag The log's tag
262  * @return DLOG_ERROR_NONE on success, else an error code.
263  * @retval DLOG_ERROR_NOT_PERMITTED Not permitted
264  */
265 static int dlog_check_limiter(log_id_t log_id, int prio, const char *tag)
266 {
267         if (!debugmode && prio <= DLOG_DEBUG)
268                 return DLOG_ERROR_NOT_PERMITTED;
269
270         if (dynamic_config)
271                 __dynamic_config_update();
272
273         if (limiter) {
274                 int should_log = 0;
275                 if (!pthread_rwlock_rdlock(&log_limiter_lock)) {
276                         should_log = __log_limiter_pass_log(tag, prio);
277                         pthread_rwlock_unlock(&log_limiter_lock);
278                 }
279
280                 if (!should_log) {
281                         return DLOG_ERROR_NOT_PERMITTED;
282                 } else if (should_log < 0) {
283                         write_to_log(log_id, prio, tag,
284                                         "Your log has been blocked due to limit of log lines per minute.");
285                         return DLOG_ERROR_NOT_PERMITTED;
286                 }
287         }
288
289         /* This can change due to __dynamic_config_update(), but is atomic and its
290          * value implies nothing else so does not need to be under a lock. */
291         if (!plog[log_id])
292                 return DLOG_ERROR_NOT_PERMITTED;
293
294         return DLOG_ERROR_NONE;
295 }
296
297 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)
298 {
299         if ((check_should_log || limiter_apply_to_all_buffers) && (dlog_check_limiter(log_id, prio, tag) < 0))
300                 return DLOG_ERROR_NONE;
301
302         char buf[LOG_MAX_PAYLOAD_SIZE];
303         vsnprintf(buf, sizeof buf, fmt, ap);
304         return write_to_log(log_id, prio, tag, buf);
305 }
306
307 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)
308 {
309         int ret = dlog_check_validity(log_id, prio, tag);
310         if (ret < 0)
311                 return ret;
312
313         /* Threads can be cancelled before they give up a lock.
314          * Therefore cancellation is temporarily disabled.
315          * This solution is comparatively simple and cheap.
316          * The other solutions (cleanup handlers, robust mutexes)
317          * would be much more complicated and also inflict larger
318          * runtime costs. The downside of disabling cancellation
319          * is not a problem in our case because it is temporary
320          * and very brief so we don't keep an obsolete thread
321          * for much longer than we otherwise would. */
322         int old_cancel_state;
323         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancel_state);
324
325         /* The only thing that needs to be protected here is `write_to_log` since
326          * all other resources already have their own specific locks (and even the
327          * pointer could be made to point at a null handler instead of a true NULL)
328          * but giving this guarantee makes everything a lot simpler as it removes
329          * the risk of something suddenly becoming NULL during processing. */
330         ret = !initialize() || !write_to_log
331                 ? DLOG_ERROR_NOT_PERMITTED
332                 : __write_to_log_critical_section(log_id, prio, tag, fmt, ap, check_should_log)
333                 ;
334
335         pthread_setcancelstate(old_cancel_state, NULL);
336
337         return ret;
338 }
339
340 /**
341  * @brief Print log
342  * @details Print a log line
343  * @param[in] log_id The target buffer ID
344  * @param[in] prio Priority
345  * @param[in] tag tag
346  * @param[in] fmt Format (same as printf)
347  * @param[in] ap Argument list
348  * @return Bytes written, or negative error
349  */
350 int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
351 {
352         int ret = __write_to_log(log_id, prio, tag, fmt, ap, true);
353         __dlog_fatal_assert(prio);
354
355         return ret;
356 }
357
358 /**
359  * @brief Print log
360  * @details Print a log line
361  * @param[in] log_id The target buffer ID
362  * @param[in] prio Priority
363  * @param[in] tag tag
364  * @param[in] fmt Format (same as printf)
365  * @return Bytes written, or negative error
366  */
367 int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
368 {
369         va_list ap;
370
371         va_start(ap, fmt);
372         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
373         va_end(ap);
374
375         return ret;
376 }
377
378 /**
379  * @brief Print log
380  * @details Print a log line
381  * @param[in] log_id The target buffer ID
382  * @param[in] prio Priority
383  * @param[in] tag tag
384  * @param[in] fmt Format (same as printf)
385  * @return Bytes written, or negative error
386  */
387 int __dlog_sec_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
388 {
389         va_list ap;
390
391         va_start(ap, fmt);
392         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
393         va_end(ap);
394
395         return ret;
396 }
397
398 int dlog_vprint(log_priority prio, const char *tag, const char *fmt, va_list ap)
399 {
400         return __write_to_log(LOG_ID_APPS, prio, tag, fmt, ap, false);
401 }
402
403 int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
404 {
405         va_list ap;
406
407         va_start(ap, fmt);
408         int ret = dlog_vprint(prio, tag, fmt, ap);
409         va_end(ap);
410
411         return ret;
412 }
413
414 /**
415  * @brief Finalize DLog
416  * @details Finalizes and deallocates the library
417  * @notes Used directly in tests; brings back the pre-init state
418  */
419 void __dlog_fini(void)
420 {
421         if (destroy_backend) {
422                 destroy_backend();
423                 destroy_backend = NULL;
424         }
425         write_to_log = NULL;
426         is_initialized = false;
427         first = true;
428
429         __log_limiter_destroy();
430         __dynamic_config_destroy();
431 }