blob: b2815fbc141eb5ebaeb13bdb7296d9b1fc923741 [file] [log] [blame]
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -07001/* util.h
2 * Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
5 *
6 * Logging and other utility functions.
7 */
8
9#ifndef _UTIL_H_
10#define _UTIL_H_
11
Luis Hector Chavezeb42bb72018-10-15 09:46:29 -070012#include <stdbool.h>
Luis Hector Chavez114a9302017-09-05 20:36:58 -070013#include <stdio.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070014#include <stdlib.h>
Jorge Lucangeli Obesf205fff2016-08-06 09:06:21 -040015#include <sys/types.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070016#include <syslog.h>
Jorge Lucangeli Obesf205fff2016-08-06 09:06:21 -040017#include <unistd.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070018
Nicole Anderson-Au461d8fb2020-11-09 22:53:40 +000019#include "libsyscalls.h"
20
Jorge Lucangeli Obesa67bd6a2016-08-19 15:33:48 -040021#ifdef __cplusplus
22extern "C" {
23#endif
24
Mike Frysingerd9ef07c2018-05-30 16:51:36 -040025/*
26 * Silence compiler warnings for unused variables/functions.
27 *
28 * If the definition is actually used, the attribute should be removed, but if
29 * it's forgotten or left in place, it doesn't cause a problem.
30 *
31 * If the definition is actually unused, the compiler is free to remove it from
32 * the output so as to save size. If you want to make sure the definition is
33 * kept (e.g. for ABI compatibility), look at the "used" attribute instead.
34 */
35#define attribute_unused __attribute__((__unused__))
36
37/*
38 * Mark the symbol as "weak" in the ELF output. This provides a fallback symbol
39 * that may be overriden at link time. See this page for more details:
40 * https://en.wikipedia.org/wiki/Weak_symbol
41 */
42#define attribute_weak __attribute__((__weak__))
43
44/*
45 * Mark the function as a printf-style function.
46 * @format_idx The index in the function argument list where the format string
47 * is passed (where the first argument is "1").
48 * @check_idx The index in the function argument list where the first argument
49 * used in the format string is passed.
50 * Some examples:
51 * foo([1] const char *format, [2] ...): format=1 check=2
52 * foo([1] int, [2] const char *format, [3] ...): format=2 check=3
53 * foo([1] const char *format, [2] const char *, [3] ...): format=1 check=3
54 */
55#define attribute_printf(format_idx, check_idx) \
56 __attribute__((__format__(__printf__, format_idx, check_idx)))
57
Mike Frysingerdebdf5d2021-06-21 09:52:06 -040058/*
59 * Mark a local variable for automatic cleanup when exiting its scope.
60 * See attribute_cleanup_fp as an example below.
61 * Make sure any variable using this is always initialized to something.
62 * @func The function to call on (a pointer to) the variable.
63 */
64#define attribute_cleanup(func) \
65 __attribute__((__cleanup__(func)))
66
67/*
68 * Automatically close a FILE* when exiting its scope.
69 * Make sure the pointer is always initialized.
70 * Some examples:
71 * attribute_cleanup_fp FILE *fp = fopen(...);
72 * attribute_cleanup_fp FILE *fp = NULL;
73 * ...
74 * fp = fopen(...);
75 */
76#define attribute_cleanup_fp attribute_cleanup(_cleanup_fp)
77static inline void _cleanup_fp(FILE **fp)
78{
79 if (*fp)
80 fclose(*fp);
81}
82
Jorge Lucangeli Obes0b208772017-04-19 14:15:46 -040083/* clang-format off */
Luis Hector Chavezcc559e82018-07-09 13:26:31 -070084#define die(_msg, ...) \
85 do_fatal_log(LOG_ERR, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070086
87#define pdie(_msg, ...) \
Mike Frysingerb5d7b9f2015-01-09 03:50:15 -050088 die(_msg ": %m", ## __VA_ARGS__)
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070089
90#define warn(_msg, ...) \
Luis Hector Chavez114a9302017-09-05 20:36:58 -070091 do_log(LOG_WARNING, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070092
Jorge Lucangeli Obesa2053902016-08-02 12:08:15 -040093#define pwarn(_msg, ...) \
94 warn(_msg ": %m", ## __VA_ARGS__)
95
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070096#define info(_msg, ...) \
Luis Hector Chavez114a9302017-09-05 20:36:58 -070097 do_log(LOG_INFO, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070098
Mike Frysinger404d2bb2017-01-17 19:29:00 -050099#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
Jorge Lucangeli Obes0b208772017-04-19 14:15:46 -0400100/* clang-format on */
Mike Frysinger404d2bb2017-01-17 19:29:00 -0500101
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -0700102extern const char *log_syscalls[];
103extern const size_t log_syscalls_len;
104
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700105enum logging_system_t {
106 /* Log to syslog. This is the default. */
107 LOG_TO_SYSLOG = 0,
108
109 /* Log to a file descriptor. */
110 LOG_TO_FD,
111};
112
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700113/*
114 * Even though this function internally calls abort(2)/exit(2), it is
115 * intentionally not marked with the noreturn attribute. When marked as
116 * noreturn, clang coalesces several of the do_fatal_log() calls in methods that
117 * have a large number of such calls (like minijail_enter()), making it
118 * impossible for breakpad to correctly identify the line where it was called,
119 * making the backtrace somewhat useless.
120 */
121extern void do_fatal_log(int priority, const char *format, ...)
122 attribute_printf(2, 3);
123
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700124extern void do_log(int priority, const char *format, ...)
Mike Frysingerd9ef07c2018-05-30 16:51:36 -0400125 attribute_printf(2, 3);
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700126
Mike Frysinger8c013272017-09-06 19:26:46 -0400127static inline int is_android(void)
Jorge Lucangeli Obes0b208772017-04-19 14:15:46 -0400128{
Jorge Lucangeli Obes4b276a62016-01-07 14:31:33 -0800129#if defined(__ANDROID__)
130 return 1;
131#else
132 return 0;
133#endif
134}
135
Luis Hector Chavezfc814552019-04-22 09:44:18 -0700136static inline bool compiled_with_asan(void)
Jorge Lucangeli Obes0b208772017-04-19 14:15:46 -0400137{
Luis Hector Chavezeb42bb72018-10-15 09:46:29 -0700138#if defined(__SANITIZE_ADDRESS__)
139 /* For gcc. */
140 return true;
141#elif defined(__has_feature)
142 /* For clang. */
Luis Hector Chavezfc814552019-04-22 09:44:18 -0700143 return __has_feature(address_sanitizer) ||
144 __has_feature(hwaddress_sanitizer);
Luis Hector Chavezeb42bb72018-10-15 09:46:29 -0700145#else
146 return false;
147#endif
Jorge Lucangeli Obes2413f372016-04-06 18:43:10 -0700148}
149
Luis Hector Chavezfc814552019-04-22 09:44:18 -0700150void __asan_init(void) attribute_weak;
151void __hwasan_init(void) attribute_weak;
152
153static inline bool running_with_asan(void)
154{
155 /*
156 * There are some configurations under which ASan needs a dynamic (as
157 * opposed to compile-time) test. Some Android processes that start
158 * before /data is mounted run with non-instrumented libminijail.so, so
159 * the symbol-sniffing code must be present to make the right decision.
160 */
161 return compiled_with_asan() || &__asan_init != 0 || &__hwasan_init != 0;
162}
163
Jorge Lucangeli Obes32201f82019-06-12 14:45:06 -0400164static inline bool debug_logging_allowed(void) {
165#if defined(ALLOW_DEBUG_LOGGING)
166 return true;
167#else
168 return false;
169#endif
170}
171
Adrian Ratiu8ef61252021-06-08 03:46:24 +0300172static inline bool seccomp_default_ret_log(void) {
173#if defined(SECCOMP_DEFAULT_RET_LOG)
174 return true;
175#else
176 return false;
177#endif
178}
179
Nicole Anderson-Au461d8fb2020-11-09 22:53:40 +0000180static inline size_t get_num_syscalls(void)
181{
182 return syscall_table_size;
183}
184
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000185int lookup_syscall(const char *name, size_t *ind);
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700186const char *lookup_syscall_name(int nr);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400187
Mike Frysingere34d7fe2018-05-23 04:18:30 -0400188long int parse_single_constant(char *constant_str, char **endptr);
Luis Hector Chavez40b25742013-09-22 19:44:06 -0700189long int parse_constant(char *constant_str, char **endptr);
Martin Pelikánab9eb442017-01-25 11:53:58 +1100190int parse_size(size_t *size, const char *sizespec);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400191
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700192char *strip(char *s);
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500193
194/*
195 * tokenize: locate the next token in @stringp using the @delim
196 * @stringp A pointer to the string to scan for tokens
197 * @delim The delimiter to split by
198 *
199 * Note that, unlike strtok, @delim is not a set of characters, but the full
200 * delimiter. e.g. "a,;b,;c" with a delim of ",;" will yield ["a","b","c"].
201 *
202 * Note that, unlike strtok, this may return an empty token. e.g. "a,,b" with
203 * strtok will yield ["a","b"], but this will yield ["a","","b"].
204 */
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800205char *tokenize(char **stringp, const char *delim);
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700206
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400207char *path_join(const char *external_path, const char *internal_path);
208
209/*
210 * consumebytes: consumes @length bytes from a buffer @buf of length @buflength
211 * @length Number of bytes to consume
212 * @buf Buffer to consume from
213 * @buflength Size of @buf
214 *
215 * Returns a pointer to the base of the bytes, or NULL for errors.
216 */
217void *consumebytes(size_t length, char **buf, size_t *buflength);
218
219/*
220 * consumestr: consumes a C string from a buffer @buf of length @length
221 * @buf Buffer to consume
222 * @length Length of buffer
223 *
224 * Returns a pointer to the base of the string, or NULL for errors.
225 */
226char *consumestr(char **buf, size_t *buflength);
227
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700228/*
229 * init_logging: initializes the module-wide logging.
230 * @logger The logging system to use.
231 * @fd The file descriptor to log into. Ignored unless
232 * @logger = LOG_TO_FD.
233 * @min_priority The minimum priority to display. Corresponds to syslog's
234 priority parameter. Ignored unless @logger = LOG_TO_FD.
235 */
236void init_logging(enum logging_system_t logger, int fd, int min_priority);
237
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100238/*
239 * minjail_free_env: Frees an environment array plus the environment strings it
240 * points to. The environment and its constituent strings must have been
241 * allocated (as opposed to pointing to static data), e.g. by using
242 * minijail_copy_env() and minijail_setenv().
243 *
244 * @env The environment to free.
245 */
246void minijail_free_env(char **env);
247
248/*
249 * minjail_copy_env: Copy an environment array (such as passed to execve),
250 * duplicating the environment strings and the array pointing at them.
251 *
252 * @env The environment to copy.
253 *
254 * Returns a pointer to the copied environment or NULL on memory allocation
255 * failure.
256 */
257char **minijail_copy_env(char *const *env);
258
259/*
260 * minjail_setenv: Set an environment variable in @env. Semantics match the
261 * standard setenv() function, but this operates on @env, not the global
262 * environment. @env must be dynamically allocated (as opposed to pointing to
263 * static data), e.g. via minijail_copy_env(). @name and @value get copied into
264 * newly-allocated memory.
265 *
266 * @env Address of the environment to modify. Might be re-allocated to
267 * make room for the new entry.
268 * @name Name of the key to set.
269 * @value The value to set.
270 * @overwrite Whether to replace the existing value for @name. If non-zero and
271 * the entry is already present, no changes will be made.
272 *
273 * Returns 0 and modifies *@env on success, returns an error code otherwise.
274 */
275int minijail_setenv(char ***env, const char *name, const char *value,
276 int overwrite);
277
Jorge Lucangeli Obesa67bd6a2016-08-19 15:33:48 -0400278#ifdef __cplusplus
279}; /* extern "C" */
280#endif
281
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700282#endif /* _UTIL_H_ */