blob: 0bdc196fd443cf9db50629acefb250da824ac8be [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
Jorge Lucangeli Obes0b208772017-04-19 14:15:46 -04006#include "util.h"
7
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -07008#include <ctype.h>
Jorge Lucangeli Obesf205fff2016-08-06 09:06:21 -04009#include <errno.h>
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -040010#include <limits.h>
Luis Hector Chavez114a9302017-09-05 20:36:58 -070011#include <stdarg.h>
Martin Pelikánab9eb442017-01-25 11:53:58 +110012#include <stdint.h>
Luis Hector Chavez40b25742013-09-22 19:44:06 -070013#include <stdio.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070014#include <string.h>
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070015
Luis Hector Chavez40b25742013-09-22 19:44:06 -070016#include "libconstants.h"
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -070017#include "libsyscalls.h"
18
Mike Frysingerfccb4c92013-10-19 02:42:07 -040019/*
20 * These are syscalls used by the syslog() C library call. You can find them
21 * by running a simple test program. See below for x86_64 behavior:
22 * $ cat test.c
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080023 * #include <syslog.h>
Mike Frysingerfccb4c92013-10-19 02:42:07 -040024 * main() { syslog(0, "foo"); }
25 * $ gcc test.c -static
26 * $ strace ./a.out
27 * ...
28 * socket(PF_FILE, SOCK_DGRAM|SOCK_CLOEXEC, 0) = 3 <- look for socket connection
29 * connect(...) <- important
30 * sendto(...) <- important
31 * exit_group(0) <- finish!
32 */
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070033#if defined(__x86_64__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080034#if defined(__ANDROID__)
35const char *log_syscalls[] = {"socket", "connect", "fcntl", "writev"};
Alex Deymo7c6899c2016-01-27 18:24:19 -080036#else
Zach Reiznerb1f517e2018-03-30 16:44:26 -070037const char *log_syscalls[] = {"socket", "connect", "sendto", "writev"};
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080038#endif
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070039#elif defined(__i386__)
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080040#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080041const char *log_syscalls[] = {"socketcall", "writev", "fcntl64",
42 "clock_gettime"};
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080043#else
Sonny Rao33d49852018-05-18 13:38:43 -070044const char *log_syscalls[] = {"socketcall", "time", "writev"};
Jeff Vander Stoep1482f202016-01-07 11:21:31 -080045#endif
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070046#elif defined(__arm__)
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080047#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080048const char *log_syscalls[] = {"clock_gettime", "connect", "fcntl64", "socket",
49 "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080050#else
Sonny Rao33d49852018-05-18 13:38:43 -070051const char *log_syscalls[] = {"socket", "connect", "gettimeofday", "send",
52 "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080053#endif
54#elif defined(__aarch64__)
55#if defined(__ANDROID__)
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080056const char *log_syscalls[] = {"connect", "fcntl", "sendto", "socket", "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080057#else
Sonny Rao33d49852018-05-18 13:38:43 -070058const char *log_syscalls[] = {"socket", "connect", "send", "writev"};
Jeff Vander Stoepd38f3992015-12-02 10:54:51 -080059#endif
Jorge Lucangeli Obesb98ad292016-01-25 15:07:30 -080060#elif defined(__powerpc__) || defined(__ia64__) || defined(__hppa__) || \
61 defined(__sparc__) || defined(__mips__)
Mike Frysinger09560862017-09-27 01:13:15 -040062const char *log_syscalls[] = {"socket", "connect", "send"};
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070063#else
64#error "Unsupported platform"
65#endif
66
Mike Frysinger404d2bb2017-01-17 19:29:00 -050067const size_t log_syscalls_len = ARRAY_SIZE(log_syscalls);
Jorge Lucangeli Obesbda833c2012-07-31 16:25:56 -070068
Luis Hector Chavez114a9302017-09-05 20:36:58 -070069/* clang-format off */
70static struct logging_config_t {
71 /* The logging system to use. The default is syslog. */
72 enum logging_system_t logger;
73
74 /* File descriptor to log to. Only used when logger is LOG_TO_FD. */
75 int fd;
76
77 /* Minimum priority to log. Only used when logger is LOG_TO_FD. */
78 int min_priority;
79} logging_config = {
80 .logger = LOG_TO_SYSLOG,
81};
82/* clang-format on */
83
Luis Hector Chavezcc559e82018-07-09 13:26:31 -070084#if defined(USE_EXIT_ON_DIE)
85#define do_abort() exit(1)
86#else
87#define do_abort() abort()
88#endif
89
Luis Hector Chavez31b02652018-07-09 14:14:49 -070090#if defined(__clang__)
91#define attribute_no_optimize __attribute__((optnone))
92#else
93#define attribute_no_optimize __attribute__((__optimize__(0)))
94#endif
95
96/* Forces the compiler to perform no optimizations on |var|. */
97static void attribute_no_optimize alias(const void *var)
98{
99 (void)var;
100}
101
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700102void do_fatal_log(int priority, const char *format, ...)
103{
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700104 va_list args, stack_args;
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700105 va_start(args, format);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700106 va_copy(stack_args, args);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700107 if (logging_config.logger == LOG_TO_SYSLOG) {
108 vsyslog(priority, format, args);
109 } else {
110 vdprintf(logging_config.fd, format, args);
111 dprintf(logging_config.fd, "\n");
112 }
113 va_end(args);
Luis Hector Chavez31b02652018-07-09 14:14:49 -0700114
115 /*
116 * Write another copy of the first few characters of the message into a
117 * stack-based buffer so that it can appear in minidumps. Choosing a
118 * small-ish buffer size since breakpad will only pick up the first few
119 * kilobytes of each stack, so that will prevent this buffer from
120 * kicking out other stack frames.
121 */
122 char log_line[512];
123 vsnprintf(log_line, sizeof(log_line), format, stack_args);
124 va_end(stack_args);
125 alias(log_line);
Luis Hector Chavezcc559e82018-07-09 13:26:31 -0700126 do_abort();
127}
128
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700129void do_log(int priority, const char *format, ...)
130{
131 if (logging_config.logger == LOG_TO_SYSLOG) {
132 va_list args;
133 va_start(args, format);
134 vsyslog(priority, format, args);
135 va_end(args);
136 return;
137 }
138
139 if (logging_config.min_priority < priority)
140 return;
141
142 va_list args;
143 va_start(args, format);
144 vdprintf(logging_config.fd, format, args);
145 va_end(args);
146 dprintf(logging_config.fd, "\n");
147}
148
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700149int lookup_syscall(const char *name)
150{
151 const struct syscall_entry *entry = syscall_table;
152 for (; entry->name && entry->nr >= 0; ++entry)
153 if (!strcmp(entry->name, name))
154 return entry->nr;
155 return -1;
156}
157
158const char *lookup_syscall_name(int nr)
159{
160 const struct syscall_entry *entry = syscall_table;
161 for (; entry->name && entry->nr >= 0; ++entry)
162 if (entry->nr == nr)
163 return entry->name;
164 return NULL;
165}
166
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400167long int parse_single_constant(char *constant_str, char **endptr)
168{
169 const struct constant_entry *entry = constant_table;
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400170 long int res = 0;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400171 for (; entry->name; ++entry) {
172 if (!strcmp(entry->name, constant_str)) {
173 if (endptr)
174 *endptr = constant_str + strlen(constant_str);
175
176 return entry->value;
177 }
178 }
179
Jorge Lucangeli Obes07459372016-10-19 15:33:31 -0400180 errno = 0;
181 res = strtol(constant_str, endptr, 0);
182 if (errno == ERANGE) {
183 if (res == LONG_MAX) {
184 /* See if the constant fits in an unsigned long int. */
185 errno = 0;
186 res = strtoul(constant_str, endptr, 0);
187 if (errno == ERANGE) {
188 /*
189 * On unsigned overflow, use the same convention
190 * as when strtol(3) finds no digits: set
191 * |*endptr| to |constant_str| and return 0.
192 */
193 warn("unsigned overflow: '%s'", constant_str);
194 *endptr = constant_str;
195 res = 0;
196 }
197 } else if (res == LONG_MIN) {
198 /*
199 * Same for signed underflow: set |*endptr| to
200 * |constant_str| and return 0.
201 */
202 warn("signed underflow: '%s'", constant_str);
203 *endptr = constant_str;
204 res = 0;
205 }
206 }
207 return res;
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400208}
209
Luis Hector Chavez40b25742013-09-22 19:44:06 -0700210long int parse_constant(char *constant_str, char **endptr)
211{
Luis Hector Chavez21224552015-06-27 18:10:39 +0000212 long int value = 0;
213 char *group, *lastpos = constant_str;
214 char *original_constant_str = constant_str;
215
216 /*
217 * Try to parse constants separated by pipes. Note that since
218 * |constant_str| is an atom, there can be no spaces between the
219 * constant and the pipe. Constants can be either a named constant
Jorge Lucangeli Obesfd6f8e32016-10-12 11:19:28 -0400220 * defined in libconstants.gen.c or a number parsed with strtol(3).
Luis Hector Chavez21224552015-06-27 18:10:39 +0000221 *
222 * If there is an error parsing any of the constants, the whole process
223 * fails.
224 */
225 while ((group = tokenize(&constant_str, "|")) != NULL) {
226 char *end = group;
227 value |= parse_single_constant(group, &end);
228 if (end == group) {
229 lastpos = original_constant_str;
230 value = 0;
231 break;
232 }
233 lastpos = end;
234 }
235 if (endptr)
236 *endptr = lastpos;
237 return value;
238}
239
Martin Pelikánab9eb442017-01-25 11:53:58 +1100240/*
241 * parse_size, specified as a string with a decimal number in bytes,
242 * possibly with one 1-character suffix like "10K" or "6G".
243 * Assumes both pointers are non-NULL.
244 *
245 * Returns 0 on success, negative errno on failure.
246 * Only writes to result on success.
247 */
248int parse_size(size_t *result, const char *sizespec)
249{
250 const char prefixes[] = "KMGTPE";
251 size_t i, multiplier = 1, nsize, size = 0;
252 unsigned long long parsed;
253 const size_t len = strlen(sizespec);
254 char *end;
255
256 if (len == 0 || sizespec[0] == '-')
257 return -EINVAL;
258
259 for (i = 0; i < sizeof(prefixes); ++i) {
260 if (sizespec[len - 1] == prefixes[i]) {
261#if __WORDSIZE == 32
262 if (i >= 3)
263 return -ERANGE;
264#endif
265 multiplier = 1024;
266 while (i-- > 0)
267 multiplier *= 1024;
268 break;
269 }
270 }
271
272 /* We only need size_t but strtoul(3) is too small on IL32P64. */
273 parsed = strtoull(sizespec, &end, 10);
274 if (parsed == ULLONG_MAX)
275 return -errno;
276 if (parsed >= SIZE_MAX)
277 return -ERANGE;
278 if ((multiplier != 1 && end != sizespec + len - 1) ||
279 (multiplier == 1 && end != sizespec + len))
280 return -EINVAL;
281 size = (size_t)parsed;
282
283 nsize = size * multiplier;
284 if (nsize / multiplier != size)
285 return -ERANGE;
286 *result = nsize;
287 return 0;
288}
289
Jorge Lucangeli Obesa6b034d2012-08-07 15:29:20 -0700290char *strip(char *s)
291{
292 char *end;
293 while (*s && isblank(*s))
294 s++;
295 end = s + strlen(s) - 1;
296 while (end >= s && *end && (isblank(*end) || *end == '\n'))
297 end--;
298 *(end + 1) = '\0';
299 return s;
300}
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800301
Jorge Lucangeli Obesc8b21e12014-06-13 14:26:16 -0700302char *tokenize(char **stringp, const char *delim)
303{
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800304 char *ret = NULL;
305
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500306 /* If the string is NULL, there are no tokens to be found. */
307 if (stringp == NULL || *stringp == NULL)
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800308 return NULL;
309
310 /*
311 * If the delimiter is NULL or empty,
312 * the full string makes up the only token.
313 */
314 if (delim == NULL || *delim == '\0') {
315 ret = *stringp;
316 *stringp = NULL;
317 return ret;
318 }
319
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500320 char *found = strstr(*stringp, delim);
321 if (!found) {
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800322 /*
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500323 * The delimiter was not found, so the full string
324 * makes up the only token, and we're done.
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800325 */
Mike Frysingerb4c7e772018-01-17 17:40:15 -0500326 ret = *stringp;
327 *stringp = NULL;
328 } else {
329 /* There's a token here, possibly empty. That's OK. */
330 *found = '\0';
331 ret = *stringp;
332 *stringp = found + strlen(delim);
Jorge Lucangeli Obes66cfc142012-11-30 15:42:52 -0800333 }
334
335 return ret;
336}
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400337
Jorge Lucangeli Obes7b2e29c2016-08-04 12:21:03 -0400338char *path_join(const char *external_path, const char *internal_path)
339{
340 char *path;
341 size_t pathlen;
342
343 /* One extra char for '/' and one for '\0', hence + 2. */
344 pathlen = strlen(external_path) + strlen(internal_path) + 2;
345 path = malloc(pathlen);
346 snprintf(path, pathlen, "%s/%s", external_path, internal_path);
347
348 return path;
349}
350
351void *consumebytes(size_t length, char **buf, size_t *buflength)
352{
353 char *p = *buf;
354 if (length > *buflength)
355 return NULL;
356 *buf += length;
357 *buflength -= length;
358 return p;
359}
360
361char *consumestr(char **buf, size_t *buflength)
362{
363 size_t len = strnlen(*buf, *buflength);
364 if (len == *buflength)
365 /* There's no null-terminator. */
366 return NULL;
367 return consumebytes(len + 1, buf, buflength);
368}
Luis Hector Chavez114a9302017-09-05 20:36:58 -0700369
370void init_logging(enum logging_system_t logger, int fd, int min_priority)
371{
372 logging_config.logger = logger;
373 logging_config.fd = fd;
374 logging_config.min_priority = min_priority;
375}