1 /* 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 
12 #include <stdbool.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <sys/types.h>
16 #include <syslog.h>
17 #include <unistd.h>
18 
19 #include "libsyscalls.h"
20 
21 #ifdef __cplusplus
22 extern "C" {
23 #endif
24 
25 /*
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 
58 #ifndef __cplusplus
59 /* If writing C++, use std::unique_ptr with a destructor instead. */
60 
61 /*
62  * Mark a local variable for automatic cleanup when exiting its scope.
63  * See attribute_cleanup_fp as an example below.
64  * Make sure any variable using this is always initialized to something.
65  * @func The function to call on (a pointer to) the variable.
66  */
67 #define attribute_cleanup(func) \
68 	__attribute__((__cleanup__(func)))
69 
70 /*
71  * Automatically close a FILE* when exiting its scope.
72  * Make sure the pointer is always initialized.
73  * Some examples:
74  *   attribute_cleanup_fp FILE *fp = fopen(...);
75  *   attribute_cleanup_fp FILE *fp = NULL;
76  *   ...
77  *   fp = fopen(...);
78  *
79  * NB: This will automatically close the underlying fd, so do not use this
80  * with fdopen calls if the fd should be left open.
81  */
82 #define attribute_cleanup_fp attribute_cleanup(_cleanup_fp)
_cleanup_fp(FILE ** fp)83 static inline void _cleanup_fp(FILE **fp)
84 {
85 	if (*fp)
86 		fclose(*fp);
87 }
88 
89 /*
90  * Automatically close a fd when exiting its scope.
91  * Make sure the fd is always initialized.
92  * Some examples:
93  *   attribute_cleanup_fd int fd = open(...);
94  *   attribute_cleanup_fd int fd = -1;
95  *   ...
96  *   fd = open(...);
97  *
98  * NB: Be careful when using this with attribute_cleanup_fp and fdopen.
99  */
100 #define attribute_cleanup_fd attribute_cleanup(_cleanup_fd)
_cleanup_fd(int * fd)101 static inline void _cleanup_fd(int *fd)
102 {
103 	if (*fd >= 0)
104 		close(*fd);
105 }
106 
107 /*
108  * Automatically free a heap allocation when exiting its scope.
109  * Make sure the pointer is always initialized.
110  * Some examples:
111  *   attribute_cleanup_str char *s = strdup(...);
112  *   attribute_cleanup_str char *s = NULL;
113  *   ...
114  *   s = strdup(...);
115  */
116 #define attribute_cleanup_str attribute_cleanup(_cleanup_str)
_cleanup_str(char ** ptr)117 static inline void _cleanup_str(char **ptr)
118 {
119 	free(*ptr);
120 }
121 
122 #endif /* __cplusplus */
123 
124 /* clang-format off */
125 #define die(_msg, ...) \
126 	do_fatal_log(LOG_ERR, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
127 
128 #define pdie(_msg, ...) \
129 	die(_msg ": %m", ## __VA_ARGS__)
130 
131 #define warn(_msg, ...) \
132 	do_log(LOG_WARNING, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
133 
134 #define pwarn(_msg, ...) \
135 	warn(_msg ": %m", ## __VA_ARGS__)
136 
137 #define info(_msg, ...) \
138 	do_log(LOG_INFO, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
139 
140 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
141 /* clang-format on */
142 
143 extern const char *const log_syscalls[];
144 extern const size_t log_syscalls_len;
145 
146 enum logging_system_t {
147 	/* Log to syslog. This is the default. */
148 	LOG_TO_SYSLOG = 0,
149 
150 	/* Log to a file descriptor. */
151 	LOG_TO_FD,
152 };
153 
154 /*
155  * Even though this function internally calls abort(2)/exit(2), it is
156  * intentionally not marked with the noreturn attribute. When marked as
157  * noreturn, clang coalesces several of the do_fatal_log() calls in methods that
158  * have a large number of such calls (like minijail_enter()), making it
159  * impossible for breakpad to correctly identify the line where it was called,
160  * making the backtrace somewhat useless.
161  */
162 extern void do_fatal_log(int priority, const char *format, ...)
163     attribute_printf(2, 3);
164 
165 extern void do_log(int priority, const char *format, ...)
166     attribute_printf(2, 3);
167 
is_android(void)168 static inline int is_android(void)
169 {
170 #if defined(__ANDROID__)
171 	return 1;
172 #else
173 	return 0;
174 #endif
175 }
176 
compiled_with_asan(void)177 static inline bool compiled_with_asan(void)
178 {
179 #if defined(__SANITIZE_ADDRESS__)
180 	/* For gcc. */
181 	return true;
182 #elif defined(__has_feature)
183 	/* For clang. */
184 	return __has_feature(address_sanitizer) ||
185 	       __has_feature(hwaddress_sanitizer);
186 #else
187 	return false;
188 #endif
189 }
190 
191 void __asan_init(void) attribute_weak;
192 void __hwasan_init(void) attribute_weak;
193 
running_with_asan(void)194 static inline bool running_with_asan(void)
195 {
196 	/*
197 	 * There are some configurations under which ASan needs a dynamic (as
198 	 * opposed to compile-time) test. Some Android processes that start
199 	 * before /data is mounted run with non-instrumented libminijail.so, so
200 	 * the symbol-sniffing code must be present to make the right decision.
201 	 */
202 	return compiled_with_asan() || &__asan_init != 0 || &__hwasan_init != 0;
203 }
204 
debug_logging_allowed(void)205 static inline bool debug_logging_allowed(void)
206 {
207 #if defined(ALLOW_DEBUG_LOGGING)
208 	return true;
209 #else
210 	return false;
211 #endif
212 }
213 
seccomp_default_ret_log(void)214 static inline bool seccomp_default_ret_log(void)
215 {
216 #if defined(SECCOMP_DEFAULT_RET_LOG)
217 	return true;
218 #else
219 	return false;
220 #endif
221 }
222 
get_num_syscalls(void)223 static inline size_t get_num_syscalls(void)
224 {
225 	return syscall_table_size;
226 }
227 
228 int lookup_syscall(const char *name, size_t *ind);
229 const char *lookup_syscall_name(int nr);
230 
231 long int parse_single_constant(char *constant_str, char **endptr);
232 long int parse_constant(char *constant_str, char **endptr);
233 int parse_size(size_t *size, const char *sizespec);
234 
235 char *strip(char *s);
236 
237 /*
238  * tokenize: locate the next token in @stringp using the @delim
239  * @stringp A pointer to the string to scan for tokens
240  * @delim   The delimiter to split by
241  *
242  * Note that, unlike strtok, @delim is not a set of characters, but the full
243  * delimiter.  e.g. "a,;b,;c" with a delim of ",;" will yield ["a","b","c"].
244  *
245  * Note that, unlike strtok, this may return an empty token.  e.g. "a,,b" with
246  * strtok will yield ["a","b"], but this will yield ["a","","b"].
247  */
248 char *tokenize(char **stringp, const char *delim);
249 
250 char *path_join(const char *external_path, const char *internal_path);
251 
252 /*
253  * consumebytes: consumes @length bytes from a buffer @buf of length @buflength
254  * @length    Number of bytes to consume
255  * @buf       Buffer to consume from
256  * @buflength Size of @buf
257  *
258  * Returns a pointer to the base of the bytes, or NULL for errors.
259  */
260 void *consumebytes(size_t length, char **buf, size_t *buflength);
261 
262 /*
263  * consumestr: consumes a C string from a buffer @buf of length @length
264  * @buf    Buffer to consume
265  * @length Length of buffer
266  *
267  * Returns a pointer to the base of the string, or NULL for errors.
268  */
269 char *consumestr(char **buf, size_t *buflength);
270 
271 /*
272  * init_logging: initializes the module-wide logging.
273  * @logger       The logging system to use.
274  * @fd           The file descriptor to log into. Ignored unless
275  *               @logger = LOG_TO_FD.
276  * @min_priority The minimum priority to display. Corresponds to syslog's
277  *               priority parameter. Ignored unless @logger = LOG_TO_FD.
278  */
279 void init_logging(enum logging_system_t logger, int fd, int min_priority);
280 
281 /*
282  * minjail_free_env: Frees an environment array plus the environment strings it
283  * points to. The environment and its constituent strings must have been
284  * allocated (as opposed to pointing to static data), e.g. by using
285  * minijail_copy_env() and minijail_setenv().
286  *
287  * @env The environment to free.
288  */
289 void minijail_free_env(char **env);
290 
291 /*
292  * minjail_copy_env: Copy an environment array (such as passed to execve),
293  * duplicating the environment strings and the array pointing at them.
294  *
295  * @env The environment to copy.
296  *
297  * Returns a pointer to the copied environment or NULL on memory allocation
298  * failure.
299  */
300 char **minijail_copy_env(char *const *env);
301 
302 /*
303  * minjail_setenv: Set an environment variable in @env. Semantics match the
304  * standard setenv() function, but this operates on @env, not the global
305  * environment. @env must be dynamically allocated (as opposed to pointing to
306  * static data), e.g. via minijail_copy_env(). @name and @value get copied into
307  * newly-allocated memory.
308  *
309  * @env       Address of the environment to modify. Might be re-allocated to
310  *            make room for the new entry.
311  * @name      Name of the key to set.
312  * @value     The value to set.
313  * @overwrite Whether to replace the existing value for @name. If non-zero and
314  *            the entry is already present, no changes will be made.
315  *
316  * Returns 0 and modifies *@env on success, returns an error code otherwise.
317  */
318 int minijail_setenv(char ***env, const char *name, const char *value,
319 		    int overwrite);
320 
321 /*
322  * getmultiline: This is like getline() but supports line wrapping with \.
323  *
324  * @lineptr    Address of a buffer that a mutli-line is stored.
325  * @n          Number of bytes stored in *lineptr.
326  * @stream     Input stream to read from.
327  *
328  * Returns number of bytes read or -1 on failure to read (including EOF).
329  */
330 ssize_t getmultiline(char **lineptr, size_t *n, FILE *stream);
331 
332 /*
333  * minjail_getenv: Get an environment variable from @envp. Semantics match the
334  * standard getenv() function, but this operates on @envp, not the global
335  * environment (usually referred to as `extern char **environ`).
336  *
337  * @env       Address of the environment to read from.
338  * @name      Name of the key to get.
339  *
340  * Returns a pointer to the corresponding environment value. The caller must
341  * take care not to modify the pointed value, as this points directly to memory
342  * pointed to by @envp.
343  * If the environment variable name is not found, returns NULL.
344  */
345 char *minijail_getenv(char **env, const char *name);
346 
347 /*
348  * minjail_unsetenv: Clear the environment variable @name from the @envp array
349  * of pointers to strings that have the KEY=VALUE format. If the operation is
350  * successful, the array will contain one item less than before the call.
351  * Only the first occurence is removed.
352  *
353  * @envp      Address of the environment to clear the variable from.
354  * @name      Name of the variable to clear.
355  *
356  * Returns false and modifies *@envp on success, returns true otherwise.
357  */
358 bool minijail_unsetenv(char **envp, const char *name);
359 
360 #ifdef __cplusplus
361 }; /* extern "C" */
362 #endif
363 
364 #endif /* _UTIL_H_ */
365