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 /* clang-format off */
59 #define die(_msg, ...) \
60 	do_fatal_log(LOG_ERR, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
61 
62 #define pdie(_msg, ...) \
63 	die(_msg ": %m", ## __VA_ARGS__)
64 
65 #define warn(_msg, ...) \
66 	do_log(LOG_WARNING, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
67 
68 #define pwarn(_msg, ...) \
69 	warn(_msg ": %m", ## __VA_ARGS__)
70 
71 #define info(_msg, ...) \
72 	do_log(LOG_INFO, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
73 
74 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
75 /* clang-format on */
76 
77 extern const char *log_syscalls[];
78 extern const size_t log_syscalls_len;
79 
80 enum logging_system_t {
81 	/* Log to syslog. This is the default. */
82 	LOG_TO_SYSLOG = 0,
83 
84 	/* Log to a file descriptor. */
85 	LOG_TO_FD,
86 };
87 
88 /*
89  * Even though this function internally calls abort(2)/exit(2), it is
90  * intentionally not marked with the noreturn attribute. When marked as
91  * noreturn, clang coalesces several of the do_fatal_log() calls in methods that
92  * have a large number of such calls (like minijail_enter()), making it
93  * impossible for breakpad to correctly identify the line where it was called,
94  * making the backtrace somewhat useless.
95  */
96 extern void do_fatal_log(int priority, const char *format, ...)
97     attribute_printf(2, 3);
98 
99 extern void do_log(int priority, const char *format, ...)
100     attribute_printf(2, 3);
101 
is_android(void)102 static inline int is_android(void)
103 {
104 #if defined(__ANDROID__)
105 	return 1;
106 #else
107 	return 0;
108 #endif
109 }
110 
compiled_with_asan(void)111 static inline bool compiled_with_asan(void)
112 {
113 #if defined(__SANITIZE_ADDRESS__)
114 	/* For gcc. */
115 	return true;
116 #elif defined(__has_feature)
117 	/* For clang. */
118 	return __has_feature(address_sanitizer) ||
119 	       __has_feature(hwaddress_sanitizer);
120 #else
121 	return false;
122 #endif
123 }
124 
125 void __asan_init(void) attribute_weak;
126 void __hwasan_init(void) attribute_weak;
127 
running_with_asan(void)128 static inline bool running_with_asan(void)
129 {
130 	/*
131 	 * There are some configurations under which ASan needs a dynamic (as
132 	 * opposed to compile-time) test. Some Android processes that start
133 	 * before /data is mounted run with non-instrumented libminijail.so, so
134 	 * the symbol-sniffing code must be present to make the right decision.
135 	 */
136 	return compiled_with_asan() || &__asan_init != 0 || &__hwasan_init != 0;
137 }
138 
debug_logging_allowed(void)139 static inline bool debug_logging_allowed(void) {
140 #if defined(ALLOW_DEBUG_LOGGING)
141 	return true;
142 #else
143 	return false;
144 #endif
145 }
146 
get_num_syscalls(void)147 static inline size_t get_num_syscalls(void)
148 {
149 	return syscall_table_size;
150 }
151 
152 int lookup_syscall(const char *name, size_t *ind);
153 const char *lookup_syscall_name(int nr);
154 
155 long int parse_single_constant(char *constant_str, char **endptr);
156 long int parse_constant(char *constant_str, char **endptr);
157 int parse_size(size_t *size, const char *sizespec);
158 
159 char *strip(char *s);
160 
161 /*
162  * tokenize: locate the next token in @stringp using the @delim
163  * @stringp A pointer to the string to scan for tokens
164  * @delim   The delimiter to split by
165  *
166  * Note that, unlike strtok, @delim is not a set of characters, but the full
167  * delimiter.  e.g. "a,;b,;c" with a delim of ",;" will yield ["a","b","c"].
168  *
169  * Note that, unlike strtok, this may return an empty token.  e.g. "a,,b" with
170  * strtok will yield ["a","b"], but this will yield ["a","","b"].
171  */
172 char *tokenize(char **stringp, const char *delim);
173 
174 char *path_join(const char *external_path, const char *internal_path);
175 
176 /*
177  * consumebytes: consumes @length bytes from a buffer @buf of length @buflength
178  * @length    Number of bytes to consume
179  * @buf       Buffer to consume from
180  * @buflength Size of @buf
181  *
182  * Returns a pointer to the base of the bytes, or NULL for errors.
183  */
184 void *consumebytes(size_t length, char **buf, size_t *buflength);
185 
186 /*
187  * consumestr: consumes a C string from a buffer @buf of length @length
188  * @buf    Buffer to consume
189  * @length Length of buffer
190  *
191  * Returns a pointer to the base of the string, or NULL for errors.
192  */
193 char *consumestr(char **buf, size_t *buflength);
194 
195 /*
196  * init_logging: initializes the module-wide logging.
197  * @logger       The logging system to use.
198  * @fd           The file descriptor to log into. Ignored unless
199  *               @logger = LOG_TO_FD.
200  * @min_priority The minimum priority to display. Corresponds to syslog's
201                  priority parameter. Ignored unless @logger = LOG_TO_FD.
202  */
203 void init_logging(enum logging_system_t logger, int fd, int min_priority);
204 
205 /*
206  * minjail_free_env: Frees an environment array plus the environment strings it
207  * points to. The environment and its constituent strings must have been
208  * allocated (as opposed to pointing to static data), e.g. by using
209  * minijail_copy_env() and minijail_setenv().
210  *
211  * @env The environment to free.
212  */
213 void minijail_free_env(char **env);
214 
215 /*
216  * minjail_copy_env: Copy an environment array (such as passed to execve),
217  * duplicating the environment strings and the array pointing at them.
218  *
219  * @env The environment to copy.
220  *
221  * Returns a pointer to the copied environment or NULL on memory allocation
222  * failure.
223  */
224 char **minijail_copy_env(char *const *env);
225 
226 /*
227  * minjail_setenv: Set an environment variable in @env. Semantics match the
228  * standard setenv() function, but this operates on @env, not the global
229  * environment. @env must be dynamically allocated (as opposed to pointing to
230  * static data), e.g. via minijail_copy_env(). @name and @value get copied into
231  * newly-allocated memory.
232  *
233  * @env       Address of the environment to modify. Might be re-allocated to
234  *            make room for the new entry.
235  * @name      Name of the key to set.
236  * @value     The value to set.
237  * @overwrite Whether to replace the existing value for @name. If non-zero and
238  *            the entry is already present, no changes will be made.
239  *
240  * Returns 0 and modifies *@env on success, returns an error code otherwise.
241  */
242 int minijail_setenv(char ***env, const char *name, const char *value,
243 		    int overwrite);
244 
245 #ifdef __cplusplus
246 }; /* extern "C" */
247 #endif
248 
249 #endif /* _UTIL_H_ */
250