1 /* util.h
2 * Copyright 2012 The ChromiumOS Authors
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 <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <sys/types.h>
18 #include <syslog.h>
19 #include <unistd.h>
20
21 #include "libsyscalls.h"
22
23 #ifdef __cplusplus
24 extern "C" {
25 #endif
26
27 /*
28 * Silence compiler warnings for unused variables/functions.
29 *
30 * If the definition is actually used, the attribute should be removed, but if
31 * it's forgotten or left in place, it doesn't cause a problem.
32 *
33 * If the definition is actually unused, the compiler is free to remove it from
34 * the output so as to save size. If you want to make sure the definition is
35 * kept (e.g. for ABI compatibility), look at the "used" attribute instead.
36 */
37 #define attribute_unused __attribute__((__unused__))
38
39 /*
40 * Mark the symbol as "weak" in the ELF output. This provides a fallback symbol
41 * that may be overriden at link time. See this page for more details:
42 * https://en.wikipedia.org/wiki/Weak_symbol
43 */
44 #define attribute_weak __attribute__((__weak__))
45
46 /*
47 * Mark the function as a printf-style function.
48 * @format_idx The index in the function argument list where the format string
49 * is passed (where the first argument is "1").
50 * @check_idx The index in the function argument list where the first argument
51 * used in the format string is passed.
52 * Some examples:
53 * foo([1] const char *format, [2] ...): format=1 check=2
54 * foo([1] int, [2] const char *format, [3] ...): format=2 check=3
55 * foo([1] const char *format, [2] const char *, [3] ...): format=1 check=3
56 */
57 #define attribute_printf(format_idx, check_idx) \
58 __attribute__((__format__(__printf__, format_idx, check_idx)))
59
60 /*
61 * The specified function arguments may not be NULL. Params starts counting
62 * from 1, not 0. If no params are specified, then all function arguments are
63 * marked as non-NULL. Thus, params should only be specified if a function
64 * accepts NULL pointers for any of the arguments.
65 * NB: Keep in sync with libminijail.h style.
66 */
67 #define attribute_nonnull(params) __attribute__((__nonnull__ params))
68
69 #ifndef __cplusplus
70 /* If writing C++, use std::unique_ptr with a destructor instead. */
71
72 /*
73 * Mark a local variable for automatic cleanup when exiting its scope.
74 * See attribute_cleanup_fp as an example below.
75 * Make sure any variable using this is always initialized to something.
76 * @func The function to call on (a pointer to) the variable.
77 */
78 #define attribute_cleanup(func) __attribute__((__cleanup__(func)))
79
80 /*
81 * Automatically close a FILE* when exiting its scope.
82 * Make sure the pointer is always initialized.
83 * Some examples:
84 * attribute_cleanup_fp FILE *fp = fopen(...);
85 * attribute_cleanup_fp FILE *fp = NULL;
86 * ...
87 * fp = fopen(...);
88 *
89 * NB: This will automatically close the underlying fd, so do not use this
90 * with fdopen calls if the fd should be left open.
91 */
92 #define attribute_cleanup_fp attribute_cleanup(_cleanup_fp)
_cleanup_fp(FILE ** fp)93 static inline void _cleanup_fp(FILE **fp)
94 {
95 if (*fp)
96 fclose(*fp);
97 }
98
99 /*
100 * Automatically close a fd when exiting its scope.
101 * Make sure the fd is always initialized.
102 * Some examples:
103 * attribute_cleanup_fd int fd = open(...);
104 * attribute_cleanup_fd int fd = -1;
105 * ...
106 * fd = open(...);
107 *
108 * NB: Be careful when using this with attribute_cleanup_fp and fdopen.
109 */
110 #define attribute_cleanup_fd attribute_cleanup(_cleanup_fd)
_cleanup_fd(int * fd)111 static inline void _cleanup_fd(int *fd)
112 {
113 if (*fd >= 0)
114 close(*fd);
115 }
116
117 /*
118 * Automatically free a heap allocation when exiting its scope.
119 * Make sure the pointer is always initialized.
120 * Some examples:
121 * attribute_cleanup_str char *s = strdup(...);
122 * attribute_cleanup_str char *s = NULL;
123 * ...
124 * s = strdup(...);
125 */
126 #define attribute_cleanup_str attribute_cleanup(_cleanup_str)
_cleanup_str(char ** ptr)127 static inline void _cleanup_str(char **ptr)
128 {
129 free(*ptr);
130 }
131
132 #endif /* __cplusplus */
133
134 /* clang-format off */
135 #define die(_msg, ...) \
136 do_fatal_log(LOG_ERR, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
137
138 #define pdie(_msg, ...) \
139 die(_msg ": %m", ## __VA_ARGS__)
140
141 #define warn(_msg, ...) \
142 do_log(LOG_WARNING, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
143
144 #define pwarn(_msg, ...) \
145 warn(_msg ": %m", ## __VA_ARGS__)
146
147 #define info(_msg, ...) \
148 do_log(LOG_INFO, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
149
150 #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
151 /* clang-format on */
152
153 extern const char *const log_syscalls[];
154 extern const size_t log_syscalls_len;
155
156 extern const char *const libc_compatibility_syscalls[];
157 extern const size_t libc_compatibility_syscalls_len;
158
159 enum logging_system_t {
160 /* Log to syslog. This is the default. */
161 LOG_TO_SYSLOG = 0,
162
163 /* Log to a file descriptor. */
164 LOG_TO_FD,
165 };
166
167 /*
168 * Even though this function internally calls abort(2)/exit(2), it is
169 * intentionally not marked with the noreturn attribute. When marked as
170 * noreturn, clang coalesces several of the do_fatal_log() calls in methods that
171 * have a large number of such calls (like minijail_enter()), making it
172 * impossible for breakpad to correctly identify the line where it was called,
173 * making the backtrace somewhat useless.
174 */
175 extern void do_fatal_log(int priority, const char *format, ...)
176 attribute_printf(2, 3);
177
178 extern void do_log(int priority, const char *format, ...)
179 attribute_printf(2, 3);
180
is_android(void)181 static inline int is_android(void)
182 {
183 #if defined(__ANDROID__)
184 return 1;
185 #else
186 return 0;
187 #endif
188 }
189
compiled_with_asan(void)190 static inline bool compiled_with_asan(void)
191 {
192 #if defined(__SANITIZE_ADDRESS__)
193 /* For gcc. */
194 return true;
195 #elif defined(__has_feature)
196 /* For clang. */
197 return __has_feature(address_sanitizer) ||
198 __has_feature(hwaddress_sanitizer);
199 #else
200 return false;
201 #endif
202 }
203
204 void __asan_init(void) attribute_weak;
205 void __hwasan_init(void) attribute_weak;
206
running_with_asan(void)207 static inline bool running_with_asan(void)
208 {
209 /*
210 * There are some configurations under which ASan needs a dynamic (as
211 * opposed to compile-time) test. Some Android processes that start
212 * before /data is mounted run with non-instrumented libminijail.so, so
213 * the symbol-sniffing code must be present to make the right decision.
214 */
215 return compiled_with_asan() || &__asan_init != 0 || &__hwasan_init != 0;
216 }
217
debug_logging_allowed(void)218 static inline bool debug_logging_allowed(void)
219 {
220 #if defined(ALLOW_DEBUG_LOGGING)
221 return true;
222 #else
223 return false;
224 #endif
225 }
226
seccomp_default_ret_log(void)227 static inline bool seccomp_default_ret_log(void)
228 {
229 #if defined(SECCOMP_DEFAULT_RET_LOG)
230 return true;
231 #else
232 return false;
233 #endif
234 }
235
block_symlinks_in_bindmount_paths(void)236 static inline bool block_symlinks_in_bindmount_paths(void)
237 {
238 #if defined(BLOCK_SYMLINKS_IN_BINDMOUNT_PATHS)
239 return true;
240 #else
241 return false;
242 #endif
243 }
244
block_symlinks_in_noninit_mountns_tmp(void)245 static inline bool block_symlinks_in_noninit_mountns_tmp(void)
246 {
247 #if defined(BLOCK_SYMLINKS_IN_NONINIT_MOUNTNS_TMP)
248 return true;
249 #else
250 return false;
251 #endif
252 }
253
get_num_syscalls(void)254 static inline size_t get_num_syscalls(void)
255 {
256 return syscall_table_size;
257 }
258
259 int lookup_syscall(const char *name, size_t *ind) attribute_nonnull((1));
260 const char *lookup_syscall_name(long nr);
261
262 long int parse_single_constant(char *constant_str, char **endptr)
263 attribute_nonnull();
264 long int parse_constant(char *constant_str, char **endptr)
265 attribute_nonnull((1));
266
267 /*
268 * parse_size: parse a string to a positive integer bytes with optional suffix.
269 * @size The output parsed size, in bytes
270 * @sizespec The input string to parse
271 *
272 * A single 1-char suffix is supported like "10K" or "6G". These use base 1024,
273 * not base 1000. i.e. "1K" is "1024". It is case-sensitive.
274 *
275 * Returns 0 on success, negative errno on failure.
276 * Only writes to |size| on success.
277 */
278 int parse_size(uint64_t *size, const char *sizespec) attribute_nonnull();
279
280 char *strip(char *s) attribute_nonnull();
281
282 /*
283 * streq: determine whether two strings are equal.
284 */
attribute_nonnull()285 attribute_nonnull() static inline bool streq(const char *s1, const char *s2)
286 {
287 return strcmp(s1, s2) == 0;
288 }
289
290 /*
291 * tokenize: locate the next token in @stringp using the @delim
292 * @stringp A pointer to the string to scan for tokens
293 * @delim The delimiter to split by
294 *
295 * Note that, unlike strtok, @delim is not a set of characters, but the full
296 * delimiter. e.g. "a,;b,;c" with a delim of ",;" will yield ["a","b","c"].
297 *
298 * Note that, unlike strtok, this may return an empty token. e.g. "a,,b" with
299 * strtok will yield ["a","b"], but this will yield ["a","","b"].
300 */
301 char *tokenize(char **stringp, const char *delim);
302
303 char *path_join(const char *external_path, const char *internal_path)
304 attribute_nonnull();
305
306 /*
307 * path_is_parent: checks whether @parent is a parent of @child.
308 * Note: this function does not evaluate '.' or '..' nor does it resolve
309 * symlinks.
310 */
311 bool path_is_parent(const char *parent, const char *child) attribute_nonnull();
312
313 /*
314 * consumebytes: consumes @length bytes from a buffer @buf of length @buflength
315 * @length Number of bytes to consume
316 * @buf Buffer to consume from
317 * @buflength Size of @buf
318 *
319 * Returns a pointer to the base of the bytes, or NULL for errors.
320 */
321 void *consumebytes(size_t length, char **buf, size_t *buflength)
322 attribute_nonnull();
323
324 /*
325 * consumestr: consumes a C string from a buffer @buf of length @length
326 * @buf Buffer to consume
327 * @length Length of buffer
328 *
329 * Returns a pointer to the base of the string, or NULL for errors.
330 */
331 char *consumestr(char **buf, size_t *buflength) attribute_nonnull();
332
333 /*
334 * init_logging: initializes the module-wide logging.
335 * @logger The logging system to use.
336 * @fd The file descriptor to log into. Ignored unless
337 * @logger = LOG_TO_FD.
338 * @min_priority The minimum priority to display. Corresponds to syslog's
339 * priority parameter. Ignored unless @logger = LOG_TO_FD.
340 */
341 void init_logging(enum logging_system_t logger, int fd, int min_priority);
342
343 /*
344 * minjail_free_env: Frees an environment array plus the environment strings it
345 * points to. The environment and its constituent strings must have been
346 * allocated (as opposed to pointing to static data), e.g. by using
347 * minijail_copy_env() and minijail_setenv().
348 *
349 * @env The environment to free.
350 */
351 void minijail_free_env(char **env);
352
353 /*
354 * minjail_copy_env: Copy an environment array (such as passed to execve),
355 * duplicating the environment strings and the array pointing at them.
356 *
357 * @env The environment to copy.
358 *
359 * Returns a pointer to the copied environment or NULL on memory allocation
360 * failure.
361 */
362 char **minijail_copy_env(char *const *env);
363
364 /*
365 * minjail_setenv: Set an environment variable in @env. Semantics match the
366 * standard setenv() function, but this operates on @env, not the global
367 * environment. @env must be dynamically allocated (as opposed to pointing to
368 * static data), e.g. via minijail_copy_env(). @name and @value get copied into
369 * newly-allocated memory.
370 *
371 * @env Address of the environment to modify. Might be re-allocated to
372 * make room for the new entry.
373 * @name Name of the key to set.
374 * @value The value to set.
375 * @overwrite Whether to replace the existing value for @name. If non-zero and
376 * the entry is already present, no changes will be made.
377 *
378 * Returns 0 and modifies *@env on success, returns an error code otherwise.
379 */
380 int minijail_setenv(char ***env, const char *name, const char *value,
381 int overwrite);
382
383 /*
384 * getmultiline: This is like getline() but supports line wrapping with \.
385 *
386 * @lineptr Address of a buffer that a mutli-line is stored.
387 * @n Number of bytes stored in *lineptr.
388 * @stream Input stream to read from.
389 *
390 * Returns number of bytes read or -1 on failure to read (including EOF).
391 */
392 ssize_t getmultiline(char **lineptr, size_t *n, FILE *stream)
393 attribute_nonnull();
394
395 /*
396 * minjail_getenv: Get an environment variable from @envp. Semantics match the
397 * standard getenv() function, but this operates on @envp, not the global
398 * environment (usually referred to as `extern char **environ`).
399 *
400 * @env Address of the environment to read from.
401 * @name Name of the key to get.
402 *
403 * Returns a pointer to the corresponding environment value. The caller must
404 * take care not to modify the pointed value, as this points directly to memory
405 * pointed to by @envp.
406 * If the environment variable name is not found, returns NULL.
407 */
408 char *minijail_getenv(char **env, const char *name);
409
410 /*
411 * minjail_unsetenv: Clear the environment variable @name from the @envp array
412 * of pointers to strings that have the KEY=VALUE format. If the operation is
413 * successful, the array will contain one item less than before the call.
414 * Only the first occurence is removed.
415 *
416 * @envp Address of the environment to clear the variable from.
417 * @name Name of the variable to clear.
418 *
419 * Returns false and modifies *@envp on success, returns true otherwise.
420 */
421 bool minijail_unsetenv(char **envp, const char *name);
422
423 #ifdef __cplusplus
424 }; /* extern "C" */
425 #endif
426
427 #endif /* _UTIL_H_ */
428