blob: 1770d5d7de08b8eddde365bce3919f3d072310b9 [file] [log] [blame]
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -07001/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 */
5
Mattias Nisslerb35f2c12020-02-07 13:37:36 +01006#define _GNU_SOURCE
7
Jorge Lucangeli Obes0b208772017-04-19 14:15:46 -04008#include "util.h"
9
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070010#include <ctype.h>
Jorge Lucangeli Obesf205fff2016-08-06 09:06:21 -040011#include <errno.h>
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -040012#include <limits.h>
Luis Hector Chavez114a9302017-09-05 20:36:58 -070013#include <stdarg.h>
Luis Hector Chavez466f2312018-10-31 10:44:43 -070014#include <stdbool.h>
Martin Pelikánab9eb442017-01-25 11:53:58 +110015#include <stdint.h>
Luis Hector Chavez40b25742013-09-22 19:44:06 -070016#include <stdio.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070017#include <string.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070018
Luis Hector Chavez40b25742013-09-22 19:44:06 -070019#include "libconstants.h"
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070020#include "libsyscalls.h"
21
Mike Frysingerfccb4c92013-10-19 02:42:07 -040022/*
23 * These are syscalls used by the syslog() C library call. You can find them
24 * by running a simple test program. See below for x86_64 behavior:
25 * $ cat test.c
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080026 * #include <syslog.h>
Mike Frysingerfccb4c92013-10-19 02:42:07 -040027 * main() { syslog(0, "foo"); }
28 * $ gcc test.c -static
29 * $ strace ./a.out
30 * ...
31 * socket(PF_FILE, SOCK_DGRAM|SOCK_CLOEXEC, 0) = 3 <- look for socket connection
32 * connect(...) <- important
33 * sendto(...) <- important
34 * exit_group(0) <- finish!
35 */
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070036#if defined(__x86_64__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080037#if defined(__ANDROID__)
38const char *log_syscalls[] = {"socket", "connect", "fcntl", "writev"};
Alex Deymo7c6899c2016-01-27 18:24:19 -080039#else
Zach Reiznerb1f517e2018-03-30 16:44:26 -070040const char *log_syscalls[] = {"socket", "connect", "sendto", "writev"};
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080041#endif
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070042#elif defined(__i386__)
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080043#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080044const char *log_syscalls[] = {"socketcall", "writev", "fcntl64",
45 "clock_gettime"};
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080046#else
Sonny Rao33d49852018-05-18 13:38:43 -070047const char *log_syscalls[] = {"socketcall", "time", "writev"};
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080048#endif
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070049#elif defined(__arm__)
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080050#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080051const char *log_syscalls[] = {"clock_gettime", "connect", "fcntl64", "socket",
52 "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080053#else
Sonny Rao33d49852018-05-18 13:38:43 -070054const char *log_syscalls[] = {"socket", "connect", "gettimeofday", "send",
55 "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080056#endif
57#elif defined(__aarch64__)
58#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080059const char *log_syscalls[] = {"connect", "fcntl", "sendto", "socket", "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080060#else
Sonny Rao33d49852018-05-18 13:38:43 -070061const char *log_syscalls[] = {"socket", "connect", "send", "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080062#endif
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080063#elif defined(__powerpc__) || defined(__ia64__) || defined(__hppa__) || \
64 defined(__sparc__) || defined(__mips__)
Mike Frysinger09560862017-09-27 01:13:15 -040065const char *log_syscalls[] = {"socket", "connect", "send"};
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070066#else
67#error "Unsupported platform"
68#endif
69
Mike Frysinger404d2bb2017-01-17 19:29:00 -050070const size_t log_syscalls_len = ARRAY_SIZE(log_syscalls);
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070071
Luis Hector Chavez114a9302017-09-05 20:36:58 -070072/* clang-format off */
73static struct logging_config_t {
74 /* The logging system to use. The default is syslog. */
75 enum logging_system_t logger;
76
77 /* File descriptor to log to. Only used when logger is LOG_TO_FD. */
78 int fd;
79
80 /* Minimum priority to log. Only used when logger is LOG_TO_FD. */
81 int min_priority;
82} logging_config = {
83 .logger = LOG_TO_SYSLOG,
84};
85/* clang-format on */
86
Luis Hector Chavezcc559e82018-07-09 13:26:31 -070087#if defined(USE_EXIT_ON_DIE)
88#define do_abort() exit(1)
89#else
90#define do_abort() abort()
91#endif
92
Luis Hector Chavez31b02652018-07-09 14:14:49 -070093#if defined(__clang__)
94#define attribute_no_optimize __attribute__((optnone))
95#else
96#define attribute_no_optimize __attribute__((__optimize__(0)))
97#endif
98
99/* Forces the compiler to perform no optimizations on |var|. */
100static void attribute_no_optimize alias(const void *var)
101{
102 (void)var;
103}
104
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700105void do_fatal_log(int priority, const char *format, ...)
106{
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700107 va_list args, stack_args;
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700108 va_start(args, format);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700109 va_copy(stack_args, args);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700110 if (logging_config.logger == LOG_TO_SYSLOG) {
111 vsyslog(priority, format, args);
112 } else {
113 vdprintf(logging_config.fd, format, args);
114 dprintf(logging_config.fd, "\n");
115 }
116 va_end(args);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700117
118 /*
119 * Write another copy of the first few characters of the message into a
120 * stack-based buffer so that it can appear in minidumps. Choosing a
121 * small-ish buffer size since breakpad will only pick up the first few
122 * kilobytes of each stack, so that will prevent this buffer from
123 * kicking out other stack frames.
124 */
125 char log_line[512];
126 vsnprintf(log_line, sizeof(log_line), format, stack_args);
127 va_end(stack_args);
128 alias(log_line);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700129 do_abort();
130}
131
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700132void do_log(int priority, const char *format, ...)
133{
134 if (logging_config.logger == LOG_TO_SYSLOG) {
135 va_list args;
136 va_start(args, format);
137 vsyslog(priority, format, args);
138 va_end(args);
139 return;
140 }
141
142 if (logging_config.min_priority < priority)
143 return;
144
145 va_list args;
146 va_start(args, format);
147 vdprintf(logging_config.fd, format, args);
148 va_end(args);
149 dprintf(logging_config.fd, "\n");
150}
151
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000152/*
153 * TODO(crbug.com/1145660): We would like for this get the length at
154 * compile-time from gen_syscalls.sh.
155 */
156size_t get_num_syscalls(void)
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700157{
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000158 static size_t num_syscalls = 0;
159 if (num_syscalls) {
160 return num_syscalls;
161 }
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700162 const struct syscall_entry *entry = syscall_table;
163 for (; entry->name && entry->nr >= 0; ++entry)
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000164 num_syscalls++;
165 return num_syscalls;
166}
167
168/*
169 * Returns the syscall nr and optionally populates the index in the pointer
170 * |ind| if it is non-NULL.
171 */
172int lookup_syscall(const char *name, size_t *ind)
173{
174 size_t ind_tmp = 0;
175 const struct syscall_entry *entry = syscall_table;
176 for (; entry->name && entry->nr >= 0; ++entry) {
177 if (!strcmp(entry->name, name)) {
178 if (ind != NULL)
179 *ind = ind_tmp;
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700180 return entry->nr;
Nicole Anderson-Aubcc8cfd2020-11-10 20:33:27 +0000181 }
182 ind_tmp++;
183 }
184 if (ind != NULL)
185 *ind = -1;
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700186 return -1;
187}
188
189const char *lookup_syscall_name(int nr)
190{
191 const struct syscall_entry *entry = syscall_table;
192 for (; entry->name && entry->nr >= 0; ++entry)
193 if (entry->nr == nr)
194 return entry->name;
195 return NULL;
196}
197
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400198long int parse_single_constant(char *constant_str, char **endptr)
199{
200 const struct constant_entry *entry = constant_table;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400201 long int res = 0;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400202 for (; entry->name; ++entry) {
203 if (!strcmp(entry->name, constant_str)) {
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700204 *endptr = constant_str + strlen(constant_str);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400205 return entry->value;
206 }
207 }
208
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400209 errno = 0;
210 res = strtol(constant_str, endptr, 0);
211 if (errno == ERANGE) {
212 if (res == LONG_MAX) {
213 /* See if the constant fits in an unsigned long int. */
214 errno = 0;
215 res = strtoul(constant_str, endptr, 0);
216 if (errno == ERANGE) {
217 /*
218 * On unsigned overflow, use the same convention
219 * as when strtol(3) finds no digits: set
220 * |*endptr| to |constant_str| and return 0.
221 */
222 warn("unsigned overflow: '%s'", constant_str);
223 *endptr = constant_str;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700224 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400225 }
226 } else if (res == LONG_MIN) {
227 /*
228 * Same for signed underflow: set |*endptr| to
229 * |constant_str| and return 0.
230 */
231 warn("signed underflow: '%s'", constant_str);
232 *endptr = constant_str;
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700233 return 0;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400234 }
235 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700236 if (**endptr != '\0') {
237 warn("trailing garbage after constant: '%s'", constant_str);
238 *endptr = constant_str;
239 return 0;
240 }
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400241 return res;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400242}
243
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700244static char *tokenize_parenthesized_expression(char **stringp)
245{
246 char *ret = NULL, *found = NULL;
247 size_t paren_count = 1;
248
249 /* If the string is NULL, there are no parens to be found. */
250 if (stringp == NULL || *stringp == NULL)
251 return NULL;
252
253 /* If the string is not on an open paren, the results are undefined. */
254 if (**stringp != '(')
255 return NULL;
256
257 for (found = *stringp + 1; *found; ++found) {
258 switch (*found) {
259 case '(':
260 ++paren_count;
261 break;
262 case ')':
263 --paren_count;
264 if (!paren_count) {
265 *found = '\0';
266 ret = *stringp + 1;
267 *stringp = found + 1;
268 return ret;
269 }
270 break;
271 }
272 }
273
274 /* We got to the end without finding the closing paren. */
275 warn("unclosed parenthesis: '%s'", *stringp);
276 return NULL;
277}
278
Luis Hector Chavez40b25742013-09-22 19:44:06 -0700279long int parse_constant(char *constant_str, char **endptr)
280{
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700281 long int value = 0, current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000282 char *group, *lastpos = constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000283
284 /*
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700285 * If |endptr| is provided, parsing errors are signaled as |endptr|
286 * pointing to |constant_str|.
287 */
288 if (endptr)
289 *endptr = constant_str;
290
291 /*
292 * Try to parse constant expressions. Valid constant expressions are:
293 *
294 * - A number that can be parsed with strtol(3).
295 * - A named constant expression.
296 * - A parenthesized, valid constant expression.
297 * - A valid constant expression prefixed with the unary bitwise
298 * complement operator ~.
299 * - A series of valid constant expressions separated by pipes. Note
300 * that since |constant_str| is an atom, there can be no spaces
301 * between the constant and the pipe.
Luis Hector Chavez21224552015-06-27 18:10:39 +0000302 *
303 * If there is an error parsing any of the constants, the whole process
304 * fails.
305 */
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700306 while (constant_str && *constant_str) {
307 bool negate = false;
308 if (*constant_str == '~') {
309 negate = true;
310 ++constant_str;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000311 }
Luis Hector Chavez466f2312018-10-31 10:44:43 -0700312 if (*constant_str == '(') {
313 group =
314 tokenize_parenthesized_expression(&constant_str);
315 if (group == NULL)
316 return 0;
317 char *end = group;
318 /* Recursively parse the parenthesized subexpression. */
319 current_value = parse_constant(group, &end);
320 if (end == group)
321 return 0;
322 if (constant_str && *constant_str) {
323 /*
324 * If this is not the end of the atom, there
325 * should be another | followed by more stuff.
326 */
327 if (*constant_str != '|') {
328 warn("unterminated constant "
329 "expression: '%s'",
330 constant_str);
331 return 0;
332 }
333 ++constant_str;
334 if (*constant_str == '\0') {
335 warn("unterminated constant "
336 "expression: '%s'",
337 constant_str);
338 return 0;
339 }
340 }
341 lastpos = end;
342 } else {
343 group = tokenize(&constant_str, "|");
344 char *end = group;
345 current_value = parse_single_constant(group, &end);
346 if (end == group)
347 return 0;
348 lastpos = end;
349 }
350 if (negate)
351 current_value = ~current_value;
352 value |= current_value;
Luis Hector Chavez21224552015-06-27 18:10:39 +0000353 }
354 if (endptr)
355 *endptr = lastpos;
356 return value;
357}
358
Martin Pelikánab9eb442017-01-25 11:53:58 +1100359/*
360 * parse_size, specified as a string with a decimal number in bytes,
361 * possibly with one 1-character suffix like "10K" or "6G".
362 * Assumes both pointers are non-NULL.
363 *
364 * Returns 0 on success, negative errno on failure.
365 * Only writes to result on success.
366 */
367int parse_size(size_t *result, const char *sizespec)
368{
369 const char prefixes[] = "KMGTPE";
370 size_t i, multiplier = 1, nsize, size = 0;
371 unsigned long long parsed;
372 const size_t len = strlen(sizespec);
373 char *end;
374
375 if (len == 0 || sizespec[0] == '-')
376 return -EINVAL;
377
378 for (i = 0; i < sizeof(prefixes); ++i) {
379 if (sizespec[len - 1] == prefixes[i]) {
380#if __WORDSIZE == 32
381 if (i >= 3)
382 return -ERANGE;
383#endif
384 multiplier = 1024;
385 while (i-- > 0)
386 multiplier *= 1024;
387 break;
388 }
389 }
390
391 /* We only need size_t but strtoul(3) is too small on IL32P64. */
392 parsed = strtoull(sizespec, &end, 10);
393 if (parsed == ULLONG_MAX)
394 return -errno;
395 if (parsed >= SIZE_MAX)
396 return -ERANGE;
397 if ((multiplier != 1 && end != sizespec + len - 1) ||
398 (multiplier == 1 && end != sizespec + len))
399 return -EINVAL;
400 size = (size_t)parsed;
401
402 nsize = size * multiplier;
403 if (nsize / multiplier != size)
404 return -ERANGE;
405 *result = nsize;
406 return 0;
407}
408
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700409char *strip(char *s)
410{
411 char *end;
412 while (*s && isblank(*s))
413 s++;
414 end = s + strlen(s) - 1;
415 while (end >= s && *end && (isblank(*end) || *end == '\n'))
416 end--;
417 *(end + 1) = '\0';
418 return s;
419}
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800420
Jorge Lucangeli Obesc8b21e12014-06-13 14:26:16 -0700421char *tokenize(char **stringp, const char *delim)
422{
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800423 char *ret = NULL;
424
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500425 /* If the string is NULL, there are no tokens to be found. */
426 if (stringp == NULL || *stringp == NULL)
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800427 return NULL;
428
429 /*
430 * If the delimiter is NULL or empty,
431 * the full string makes up the only token.
432 */
433 if (delim == NULL || *delim == '\0') {
434 ret = *stringp;
435 *stringp = NULL;
436 return ret;
437 }
438
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500439 char *found = strstr(*stringp, delim);
440 if (!found) {
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800441 /*
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500442 * The delimiter was not found, so the full string
443 * makes up the only token, and we're done.
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800444 */
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500445 ret = *stringp;
446 *stringp = NULL;
447 } else {
448 /* There's a token here, possibly empty. That's OK. */
449 *found = '\0';
450 ret = *stringp;
451 *stringp = found + strlen(delim);
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800452 }
453
454 return ret;
455}
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400456
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400457char *path_join(const char *external_path, const char *internal_path)
458{
459 char *path;
460 size_t pathlen;
461
462 /* One extra char for '/' and one for '\0', hence + 2. */
463 pathlen = strlen(external_path) + strlen(internal_path) + 2;
464 path = malloc(pathlen);
Mike Frysinger1036cd82020-08-28 00:15:59 -0400465 if (path)
466 snprintf(path, pathlen, "%s/%s", external_path, internal_path);
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400467
468 return path;
469}
470
471void *consumebytes(size_t length, char **buf, size_t *buflength)
472{
473 char *p = *buf;
474 if (length > *buflength)
475 return NULL;
476 *buf += length;
477 *buflength -= length;
478 return p;
479}
480
481char *consumestr(char **buf, size_t *buflength)
482{
483 size_t len = strnlen(*buf, *buflength);
484 if (len == *buflength)
485 /* There's no null-terminator. */
486 return NULL;
487 return consumebytes(len + 1, buf, buflength);
488}
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700489
490void init_logging(enum logging_system_t logger, int fd, int min_priority)
491{
492 logging_config.logger = logger;
493 logging_config.fd = fd;
494 logging_config.min_priority = min_priority;
495}
Mattias Nisslerb35f2c12020-02-07 13:37:36 +0100496
497void minijail_free_env(char **env)
498{
499 if (!env)
500 return;
501
502 for (char **entry = env; *entry; ++entry) {
503 free(*entry);
504 }
505
506 free(env);
507}
508
509char **minijail_copy_env(char *const *env)
510{
511 if (!env)
512 return calloc(1, sizeof(char *));
513
514 int len = 0;
515 while (env[len])
516 ++len;
517
518 char **copy = calloc(len + 1, sizeof(char *));
519 if (!copy)
520 return NULL;
521
522 for (char **entry = copy; *env; ++env, ++entry) {
523 *entry = strdup(*env);
524 if (!*entry) {
525 minijail_free_env(copy);
526 return NULL;
527 }
528 }
529
530 return copy;
531}
532
533int minijail_setenv(char ***env, const char *name, const char *value,
534 int overwrite)
535{
536 if (!env || !*env || !name || !*name || !value)
537 return EINVAL;
538
539 size_t name_len = strlen(name);
540
541 char **dest = NULL;
542 size_t env_len = 0;
543 for (char **entry = *env; *entry; ++entry, ++env_len) {
544 if (!dest && strncmp(name, *entry, name_len) == 0 &&
545 (*entry)[name_len] == '=') {
546 if (!overwrite)
547 return 0;
548
549 dest = entry;
550 }
551 }
552
553 char *new_entry = NULL;
554 if (asprintf(&new_entry, "%s=%s", name, value) == -1)
555 return ENOMEM;
556
557 if (dest) {
558 free(*dest);
559 *dest = new_entry;
560 return 0;
561 }
562
563 env_len++;
564 char **new_env = realloc(*env, (env_len + 1) * sizeof(char *));
565 if (!new_env) {
566 free(new_entry);
567 return ENOMEM;
568 }
569
570 new_env[env_len - 1] = new_entry;
571 new_env[env_len] = NULL;
572 *env = new_env;
573 return 0;
574}