1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: t -*-
3 * Copyright (c) 2005-2008, The Android Open Source Project
4 * Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
30 #include <dynamic_config.h>
32 #include <logcommon.h>
33 #include "logconfig.h"
34 #include "loglimiter.h"
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
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
51 int (*write_to_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg) = NULL;
52 void (*destroy_backend)();
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;
58 extern void __dlog_init_pipe(const struct log_config *conf);
59 extern void __dlog_init_android(const struct log_config *conf);
63 bool plog[LOG_ID_MAX];
64 bool plog_default_values[LOG_ID_MAX];
67 static int fatal_assert;
68 static int limiter_apply_to_all_buffers;
70 static void __configure_limiter(struct log_config *config)
77 limiter = __log_limiter_create(config);
80 static int __configure_backend(struct log_config *config)
84 const char *const backend = log_config_get(config, "backend");
88 if (!strcmp(backend, "pipe"))
89 __dlog_init_pipe(config);
90 else if (!strcmp(backend, "logger"))
91 __dlog_init_android(config);
98 static void __set_plog_default_values()
100 for (int i = 0; i < NELEMS(plog); ++i)
101 plog_default_values[i] = plog[i];
104 static void __initialize_plog(const struct log_config *config)
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();
115 static void __configure_parameters(struct log_config *config)
119 __initialize_plog(config);
120 __update_plog(config);
121 __set_plog_default_values();
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);
131 void __update_plog(const struct log_config *conf)
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));
140 plog[i] = log_config_get_boolean(conf, key, plog_default_values[i]);
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):
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.
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.
167 bool __configure(void)
169 __attribute__((cleanup(log_config_free))) struct log_config config;
171 if (log_config_read(&config) < 0)
174 dynamic_config = __dynamic_config_create(&config);
176 __configure_parameters(&config);
178 if (!__configure_backend(&config)) {
179 __dynamic_config_destroy();
180 dynamic_config = false;
184 __configure_limiter(&config);
188 static bool first = true;
189 static bool initialize()
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
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. */
216 pthread_mutex_lock(&log_construction_lock);
218 first = !__configure();
220 is_initialized = true;
222 pthread_mutex_unlock(&log_construction_lock);
227 * @brief Fatal assertion
228 * @details Conditionally crash the sucka who sent the log
229 * @param[in] prio Priority of the log
231 static void __dlog_fatal_assert(int prio)
233 assert(!fatal_assert || (prio != DLOG_FATAL));
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
245 static int dlog_check_validity(log_id_t log_id, int prio, const char *tag)
248 return DLOG_ERROR_INVALID_PARAMETER;
250 if (log_id <= LOG_ID_INVALID || LOG_ID_MAX <= log_id)
251 return DLOG_ERROR_INVALID_PARAMETER;
253 return DLOG_ERROR_NONE;
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
265 static int dlog_check_limiter(log_id_t log_id, int prio, const char *tag)
267 if (!debugmode && prio <= DLOG_DEBUG)
268 return DLOG_ERROR_NOT_PERMITTED;
271 __dynamic_config_update();
275 if (!pthread_rwlock_rdlock(&log_limiter_lock)) {
276 should_log = __log_limiter_pass_log(tag, prio);
277 pthread_rwlock_unlock(&log_limiter_lock);
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;
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. */
292 return DLOG_ERROR_NOT_PERMITTED;
294 return DLOG_ERROR_NONE;
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)
299 if ((check_should_log || limiter_apply_to_all_buffers) && (dlog_check_limiter(log_id, prio, tag) < 0))
300 return DLOG_ERROR_NONE;
302 char buf[LOG_MAX_PAYLOAD_SIZE];
303 vsnprintf(buf, sizeof buf, fmt, ap);
304 return write_to_log(log_id, prio, tag, buf);
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)
309 int ret = dlog_check_validity(log_id, prio, tag);
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);
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)
335 pthread_setcancelstate(old_cancel_state, NULL);
342 * @details Print a log line
343 * @param[in] log_id The target buffer ID
344 * @param[in] prio Priority
346 * @param[in] fmt Format (same as printf)
347 * @param[in] ap Argument list
348 * @return Bytes written, or negative error
350 int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
352 int ret = __write_to_log(log_id, prio, tag, fmt, ap, true);
353 __dlog_fatal_assert(prio);
360 * @details Print a log line
361 * @param[in] log_id The target buffer ID
362 * @param[in] prio Priority
364 * @param[in] fmt Format (same as printf)
365 * @return Bytes written, or negative error
367 int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
372 int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
380 * @details Print a log line
381 * @param[in] log_id The target buffer ID
382 * @param[in] prio Priority
384 * @param[in] fmt Format (same as printf)
385 * @return Bytes written, or negative error
387 int __dlog_sec_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
392 int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
398 int dlog_vprint(log_priority prio, const char *tag, const char *fmt, va_list ap)
400 return __write_to_log(LOG_ID_APPS, prio, tag, fmt, ap, false);
403 int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
408 int ret = dlog_vprint(prio, tag, fmt, ap);
415 * @brief Finalize DLog
416 * @details Finalizes and deallocates the library
417 * @notes Used directly in tests; brings back the pre-init state
419 void __dlog_fini(void)
421 if (destroy_backend) {
423 destroy_backend = NULL;
426 is_initialized = false;
429 __log_limiter_destroy();
430 __dynamic_config_destroy();