Coverage Report

Created: 2026-05-16 06:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/crosvm/third_party/minijail/util.h
Line
Count
Source
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
0
#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
0
#define attribute_cleanup_fp attribute_cleanup(_cleanup_fp)
93
static inline void _cleanup_fp(FILE **fp)
94
0
{
95
0
  if (*fp)
96
0
    fclose(*fp);
97
0
}
Unexecuted instantiation: libminijail.c:_cleanup_fp
Unexecuted instantiation: syscall_filter.c:_cleanup_fp
Unexecuted instantiation: signal_handler.c:_cleanup_fp
Unexecuted instantiation: bpf.c:_cleanup_fp
Unexecuted instantiation: landlock_util.c:_cleanup_fp
Unexecuted instantiation: util.c:_cleanup_fp
Unexecuted instantiation: system.c:_cleanup_fp
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
0
#define attribute_cleanup_fd attribute_cleanup(_cleanup_fd)
111
static inline void _cleanup_fd(int *fd)
112
0
{
113
0
  if (*fd >= 0)
114
0
    close(*fd);
115
0
}
Unexecuted instantiation: libminijail.c:_cleanup_fd
Unexecuted instantiation: syscall_filter.c:_cleanup_fd
Unexecuted instantiation: signal_handler.c:_cleanup_fd
Unexecuted instantiation: bpf.c:_cleanup_fd
Unexecuted instantiation: landlock_util.c:_cleanup_fd
Unexecuted instantiation: util.c:_cleanup_fd
Unexecuted instantiation: system.c:_cleanup_fd
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
0
#define attribute_cleanup_str attribute_cleanup(_cleanup_str)
127
static inline void _cleanup_str(char **ptr)
128
0
{
129
0
  free(*ptr);
130
0
}
Unexecuted instantiation: libminijail.c:_cleanup_str
Unexecuted instantiation: syscall_filter.c:_cleanup_str
Unexecuted instantiation: signal_handler.c:_cleanup_str
Unexecuted instantiation: bpf.c:_cleanup_str
Unexecuted instantiation: landlock_util.c:_cleanup_str
Unexecuted instantiation: util.c:_cleanup_str
Unexecuted instantiation: system.c:_cleanup_str
131
132
#endif /* __cplusplus */
133
134
/* clang-format off */
135
#define die(_msg, ...) \
136
0
  do_fatal_log(LOG_ERR, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
137
138
#define pdie(_msg, ...) \
139
0
  die(_msg ": %m", ## __VA_ARGS__)
140
141
#define warn(_msg, ...) \
142
0
  do_log(LOG_WARNING, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
143
144
#define pwarn(_msg, ...) \
145
0
  warn(_msg ": %m", ## __VA_ARGS__)
146
147
#define info(_msg, ...) \
148
0
  do_log(LOG_INFO, "libminijail[%d]: " _msg, getpid(), ## __VA_ARGS__)
149
150
0
#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
181
static inline int is_android(void)
182
0
{
183
#if defined(__ANDROID__)
184
  return 1;
185
#else
186
0
  return 0;
187
0
#endif
188
0
}
Unexecuted instantiation: libminijail.c:is_android
Unexecuted instantiation: syscall_filter.c:is_android
Unexecuted instantiation: signal_handler.c:is_android
Unexecuted instantiation: bpf.c:is_android
Unexecuted instantiation: landlock_util.c:is_android
Unexecuted instantiation: util.c:is_android
Unexecuted instantiation: system.c:is_android
189
190
static inline bool compiled_with_asan(void)
191
0
{
192
0
#if defined(__SANITIZE_ADDRESS__)
193
0
  /* For gcc. */
194
0
  return true;
195
0
#elif defined(__has_feature)
196
0
  /* For clang. */
197
0
  return __has_feature(address_sanitizer) ||
198
0
         __has_feature(hwaddress_sanitizer);
199
0
#else
200
0
  return false;
201
0
#endif
202
0
}
Unexecuted instantiation: syscall_filter.c:compiled_with_asan
Unexecuted instantiation: signal_handler.c:compiled_with_asan
Unexecuted instantiation: bpf.c:compiled_with_asan
Unexecuted instantiation: landlock_util.c:compiled_with_asan
Unexecuted instantiation: util.c:compiled_with_asan
Unexecuted instantiation: system.c:compiled_with_asan
203
204
void __asan_init(void) attribute_weak;
205
void __hwasan_init(void) attribute_weak;
206
207
static inline bool running_with_asan(void)
208
0
{
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
0
  return compiled_with_asan() || &__asan_init != 0 || &__hwasan_init != 0;
216
0
}
Unexecuted instantiation: libminijail.c:running_with_asan
Unexecuted instantiation: syscall_filter.c:running_with_asan
Unexecuted instantiation: signal_handler.c:running_with_asan
Unexecuted instantiation: bpf.c:running_with_asan
Unexecuted instantiation: landlock_util.c:running_with_asan
Unexecuted instantiation: util.c:running_with_asan
Unexecuted instantiation: system.c:running_with_asan
217
218
static inline bool debug_logging_allowed(void)
219
0
{
220
0
#if defined(ALLOW_DEBUG_LOGGING)
221
0
  return true;
222
#else
223
  return false;
224
#endif
225
0
}
Unexecuted instantiation: libminijail.c:debug_logging_allowed
Unexecuted instantiation: syscall_filter.c:debug_logging_allowed
Unexecuted instantiation: signal_handler.c:debug_logging_allowed
Unexecuted instantiation: bpf.c:debug_logging_allowed
Unexecuted instantiation: landlock_util.c:debug_logging_allowed
Unexecuted instantiation: util.c:debug_logging_allowed
Unexecuted instantiation: system.c:debug_logging_allowed
226
227
static inline bool seccomp_default_ret_log(void)
228
0
{
229
#if defined(SECCOMP_DEFAULT_RET_LOG)
230
  return true;
231
#else
232
0
  return false;
233
0
#endif
234
0
}
Unexecuted instantiation: libminijail.c:seccomp_default_ret_log
Unexecuted instantiation: syscall_filter.c:seccomp_default_ret_log
Unexecuted instantiation: signal_handler.c:seccomp_default_ret_log
Unexecuted instantiation: bpf.c:seccomp_default_ret_log
Unexecuted instantiation: landlock_util.c:seccomp_default_ret_log
Unexecuted instantiation: util.c:seccomp_default_ret_log
Unexecuted instantiation: system.c:seccomp_default_ret_log
235
236
static inline bool block_symlinks_in_bindmount_paths(void)
237
0
{
238
#if defined(BLOCK_SYMLINKS_IN_BINDMOUNT_PATHS)
239
  return true;
240
#else
241
0
  return false;
242
0
#endif
243
0
}
Unexecuted instantiation: libminijail.c:block_symlinks_in_bindmount_paths
Unexecuted instantiation: syscall_filter.c:block_symlinks_in_bindmount_paths
Unexecuted instantiation: signal_handler.c:block_symlinks_in_bindmount_paths
Unexecuted instantiation: bpf.c:block_symlinks_in_bindmount_paths
Unexecuted instantiation: landlock_util.c:block_symlinks_in_bindmount_paths
Unexecuted instantiation: util.c:block_symlinks_in_bindmount_paths
Unexecuted instantiation: system.c:block_symlinks_in_bindmount_paths
244
245
static inline bool block_symlinks_in_noninit_mountns_tmp(void)
246
0
{
247
#if defined(BLOCK_SYMLINKS_IN_NONINIT_MOUNTNS_TMP)
248
  return true;
249
#else
250
0
  return false;
251
0
#endif
252
0
}
Unexecuted instantiation: libminijail.c:block_symlinks_in_noninit_mountns_tmp
Unexecuted instantiation: syscall_filter.c:block_symlinks_in_noninit_mountns_tmp
Unexecuted instantiation: signal_handler.c:block_symlinks_in_noninit_mountns_tmp
Unexecuted instantiation: bpf.c:block_symlinks_in_noninit_mountns_tmp
Unexecuted instantiation: landlock_util.c:block_symlinks_in_noninit_mountns_tmp
Unexecuted instantiation: util.c:block_symlinks_in_noninit_mountns_tmp
Unexecuted instantiation: system.c:block_symlinks_in_noninit_mountns_tmp
253
254
static inline size_t get_num_syscalls(void)
255
0
{
256
0
  return syscall_table_size;
257
0
}
Unexecuted instantiation: libminijail.c:get_num_syscalls
Unexecuted instantiation: syscall_filter.c:get_num_syscalls
Unexecuted instantiation: signal_handler.c:get_num_syscalls
Unexecuted instantiation: bpf.c:get_num_syscalls
Unexecuted instantiation: landlock_util.c:get_num_syscalls
Unexecuted instantiation: util.c:get_num_syscalls
Unexecuted instantiation: system.c:get_num_syscalls
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
 */
285
attribute_nonnull() static inline bool streq(const char *s1, const char *s2)
286
0
{
287
0
  return strcmp(s1, s2) == 0;
288
0
}
Unexecuted instantiation: libminijail.c:streq
Unexecuted instantiation: syscall_filter.c:streq
Unexecuted instantiation: signal_handler.c:streq
Unexecuted instantiation: bpf.c:streq
Unexecuted instantiation: landlock_util.c:streq
Unexecuted instantiation: util.c:streq
Unexecuted instantiation: system.c:streq
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
 * logging_to_syslog: report whether the active logging backend is syslog.
345
 *
346
 * Returns true when logging is handled by syslog, false otherwise.
347
 */
348
bool logging_to_syslog(void);
349
350
/*
351
 * minjail_free_env: Frees an environment array plus the environment strings it
352
 * points to. The environment and its constituent strings must have been
353
 * allocated (as opposed to pointing to static data), e.g. by using
354
 * minijail_copy_env() and minijail_setenv().
355
 *
356
 * @env The environment to free.
357
 */
358
void minijail_free_env(char **env);
359
360
/*
361
 * minjail_copy_env: Copy an environment array (such as passed to execve),
362
 * duplicating the environment strings and the array pointing at them.
363
 *
364
 * @env The environment to copy.
365
 *
366
 * Returns a pointer to the copied environment or NULL on memory allocation
367
 * failure.
368
 */
369
char **minijail_copy_env(char *const *env);
370
371
/*
372
 * minjail_setenv: Set an environment variable in @env. Semantics match the
373
 * standard setenv() function, but this operates on @env, not the global
374
 * environment. @env must be dynamically allocated (as opposed to pointing to
375
 * static data), e.g. via minijail_copy_env(). @name and @value get copied into
376
 * newly-allocated memory.
377
 *
378
 * @env       Address of the environment to modify. Might be re-allocated to
379
 *            make room for the new entry.
380
 * @name      Name of the key to set.
381
 * @value     The value to set.
382
 * @overwrite Whether to replace the existing value for @name. If non-zero and
383
 *            the entry is already present, no changes will be made.
384
 *
385
 * Returns 0 and modifies *@env on success, returns an error code otherwise.
386
 */
387
int minijail_setenv(char ***env, const char *name, const char *value,
388
        int overwrite);
389
390
/*
391
 * getmultiline: This is like getline() but supports line wrapping with \.
392
 *
393
 * @lineptr    Address of a buffer that a mutli-line is stored.
394
 * @n          Number of bytes stored in *lineptr.
395
 * @stream     Input stream to read from.
396
 *
397
 * Returns number of bytes read or -1 on failure to read (including EOF).
398
 */
399
ssize_t getmultiline(char **lineptr, size_t *n, FILE *stream)
400
    attribute_nonnull();
401
402
/*
403
 * minjail_getenv: Get an environment variable from @envp. Semantics match the
404
 * standard getenv() function, but this operates on @envp, not the global
405
 * environment (usually referred to as `extern char **environ`).
406
 *
407
 * @env       Address of the environment to read from.
408
 * @name      Name of the key to get.
409
 *
410
 * Returns a pointer to the corresponding environment value. The caller must
411
 * take care not to modify the pointed value, as this points directly to memory
412
 * pointed to by @envp.
413
 * If the environment variable name is not found, returns NULL.
414
 */
415
char *minijail_getenv(char **env, const char *name);
416
417
/*
418
 * minjail_unsetenv: Clear the environment variable @name from the @envp array
419
 * of pointers to strings that have the KEY=VALUE format. If the operation is
420
 * successful, the array will contain one item less than before the call.
421
 * Only the first occurence is removed.
422
 *
423
 * @envp      Address of the environment to clear the variable from.
424
 * @name      Name of the variable to clear.
425
 *
426
 * Returns false and modifies *@envp on success, returns true otherwise.
427
 */
428
bool minijail_unsetenv(char **envp, const char *name);
429
430
#ifdef __cplusplus
431
}; /* extern "C" */
432
#endif
433
434
#endif /* _UTIL_H_ */