2 * Copyright (C) 2008-2012 Tobias Brunner
3 * Copyright (C) 2005-2008 Martin Willi
4 * Hochschule fuer Technik Rapperswil
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 2 of the License, or (at your
9 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
30 #include "collections/enumerator.h"
31 #include "utils/debug.h"
33 ENUM(status_names
, SUCCESS
, NEED_MORE
,
49 * Described in header.
51 void *clalloc(void * pointer
, size_t size
)
56 memcpy(data
, pointer
, size
);
62 * Described in header.
64 void memxor(u_int8_t dst
[], u_int8_t src
[], size_t n
)
68 /* byte wise XOR until dst aligned */
69 for (i
= 0; (uintptr_t)&dst
[i
] % sizeof(long) && i
< n
; i
++)
73 /* try to use words if src shares an aligment with dst */
74 switch (((uintptr_t)&src
[i
] % sizeof(long)))
77 for (m
= n
- sizeof(long); i
<= m
; i
+= sizeof(long))
79 *(long*)&dst
[i
] ^= *(long*)&src
[i
];
83 for (m
= n
- sizeof(int); i
<= m
; i
+= sizeof(int))
85 *(int*)&dst
[i
] ^= *(int*)&src
[i
];
89 for (m
= n
- sizeof(short); i
<= m
; i
+= sizeof(short))
91 *(short*)&dst
[i
] ^= *(short*)&src
[i
];
97 /* byte wise XOR of the rest */
105 * Described in header.
107 void memwipe_noinline(void *ptr
, size_t n
)
109 memwipe_inline(ptr
, n
);
113 * Described in header.
115 void *memstr(const void *haystack
, const char *needle
, size_t n
)
117 unsigned const char *pos
= haystack
;
118 size_t l
= strlen(needle
);
119 for (; n
>= l
; ++pos
, --n
)
121 if (memeq(pos
, needle
, l
))
130 * Described in header.
132 char* translate(char *str
, const char *from
, const char *to
)
135 if (strlen(from
) != strlen(to
))
142 if ((match
= strchr(from
, *pos
)) != NULL
)
144 *pos
= to
[match
- from
];
152 * Described in header.
154 bool mkdir_p(const char *path
, mode_t mode
)
157 char *pos
, full
[PATH_MAX
];
159 if (!path
|| *path
== '\0')
163 len
= snprintf(full
, sizeof(full
)-1, "%s", path
);
164 if (len
< 0 || len
>= sizeof(full
)-1)
166 DBG1(DBG_LIB
, "path string %s too long", path
);
169 /* ensure that the path ends with a '/' */
170 if (full
[len
-1] != '/')
175 /* skip '/' at the beginning */
180 while ((pos
= strchr(pos
, '/')))
183 if (access(full
, F_OK
) < 0)
185 if (mkdir(full
, mode
) < 0)
187 DBG1(DBG_LIB
, "failed to create directory %s", full
);
199 * The size of the thread-specific error buffer
201 #define STRERROR_BUF_LEN 256
204 * Key to store thread-specific error buffer
206 static pthread_key_t strerror_buf_key
;
209 * Only initialize the key above once
211 static pthread_once_t strerror_buf_key_once
= PTHREAD_ONCE_INIT
;
214 * Create the key used for the thread-specific error buffer
216 static void create_strerror_buf_key()
218 pthread_key_create(&strerror_buf_key
, free
);
222 * Retrieve the error buffer assigned to the current thread (or create it)
224 static inline char *get_strerror_buf()
228 pthread_once(&strerror_buf_key_once
, create_strerror_buf_key
);
229 buf
= pthread_getspecific(strerror_buf_key
);
232 buf
= malloc(STRERROR_BUF_LEN
);
233 pthread_setspecific(strerror_buf_key
, buf
);
238 #ifdef HAVE_STRERROR_R
240 * Described in header.
242 const char *safe_strerror(int errnum
)
244 char *buf
= get_strerror_buf(), *msg
;
246 #ifdef STRERROR_R_CHAR_P
247 /* char* version which may or may not return the original buffer */
248 msg
= strerror_r(errnum
, buf
, STRERROR_BUF_LEN
);
250 /* int version returns 0 on success */
251 msg
= strerror_r(errnum
, buf
, STRERROR_BUF_LEN
) ?
"Unknown error" : buf
;
255 #else /* HAVE_STRERROR_R */
256 /* we actually wan't to call strerror(3) below */
259 * Described in header.
261 const char *safe_strerror(int errnum
)
263 static pthread_mutex_t mutex
= PTHREAD_MUTEX_INITIALIZER
;
264 char *buf
= get_strerror_buf();
266 /* use a mutex to ensure calling strerror(3) is thread-safe */
267 pthread_mutex_lock(&mutex
);
268 strncpy(buf
, strerror(errnum
), STRERROR_BUF_LEN
);
269 pthread_mutex_unlock(&mutex
);
270 buf
[STRERROR_BUF_LEN
- 1] = '\0';
273 #endif /* HAVE_STRERROR_R */
276 #ifndef HAVE_CLOSEFROM
278 * Described in header.
280 void closefrom(int lowfd
)
282 char fd_dir
[PATH_MAX
];
285 /* try to close only open file descriptors on Linux... */
286 len
= snprintf(fd_dir
, sizeof(fd_dir
), "/proc/%u/fd", getpid());
287 if (len
> 0 && len
< sizeof(fd_dir
) && access(fd_dir
, F_OK
) == 0)
289 enumerator_t
*enumerator
= enumerator_create_directory(fd_dir
);
293 while (enumerator
->enumerate(enumerator
, &rel
, NULL
, NULL
))
301 enumerator
->destroy(enumerator
);
306 /* ...fall back to closing all fds otherwise */
307 maxfd
= (int)sysconf(_SC_OPEN_MAX
);
312 for (fd
= lowfd
; fd
< maxfd
; fd
++)
317 #endif /* HAVE_CLOSEFROM */
320 * Return monotonic time
322 time_t time_monotonic(timeval_t
*tv
)
324 #if defined(HAVE_CLOCK_GETTIME) && \
325 (defined(HAVE_CONDATTR_CLOCK_MONOTONIC) || \
326 defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
327 /* as we use time_monotonic() for condvar operations, we use the
328 * monotonic time source only if it is also supported by pthread. */
331 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0)
335 tv
->tv_sec
= ts
.tv_sec
;
336 tv
->tv_usec
= ts
.tv_nsec
/ 1000;
340 #endif /* HAVE_CLOCK_GETTIME && (...) */
341 /* Fallback to non-monotonic timestamps:
342 * On MAC OS X, creating monotonic timestamps is rather difficult. We
343 * could use mach_absolute_time() and catch sleep/wakeup notifications.
344 * We stick to the simpler (non-monotonic) gettimeofday() for now.
345 * But keep in mind: we need the same time source here as in condvar! */
350 if (gettimeofday(tv
, NULL
) != 0)
351 { /* should actually never fail if passed pointers are valid */
384 status_t
return_failed()
396 #ifndef HAVE_GCC_ATOMIC_OPERATIONS
399 * We use a single mutex for all refcount variables.
401 static pthread_mutex_t ref_mutex
= PTHREAD_MUTEX_INITIALIZER
;
406 void ref_get(refcount_t
*ref
)
408 pthread_mutex_lock(&ref_mutex
);
410 pthread_mutex_unlock(&ref_mutex
);
416 bool ref_put(refcount_t
*ref
)
420 pthread_mutex_lock(&ref_mutex
);
421 more_refs
= --(*ref
) > 0;
422 pthread_mutex_unlock(&ref_mutex
);
427 * Single mutex for all compare and swap operations.
429 static pthread_mutex_t cas_mutex
= PTHREAD_MUTEX_INITIALIZER
;
432 * Compare and swap if equal to old value
434 #define _cas_impl(name, type) \
435 bool cas_##name(type *ptr, type oldval, type newval) \
438 pthread_mutex_lock(&cas_mutex); \
439 if ((swapped = (*ptr == oldval))) { *ptr = newval; } \
440 pthread_mutex_unlock(&cas_mutex); \
444 _cas_impl(bool, bool)
445 _cas_impl(ptr
, void*)
447 #endif /* HAVE_GCC_ATOMIC_OPERATIONS */
450 * Described in header.
452 int time_printf_hook(printf_hook_data_t
*data
, printf_hook_spec_t
*spec
,
453 const void *const *args
)
455 static const char* months
[] = {
456 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
457 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
459 time_t *time
= *((time_t**)(args
[0]));
460 bool utc
= *((bool*)(args
[1]));;
463 if (time
== UNDEFINED_TIME
)
465 return print_in_hook(data
, "--- -- --:--:--%s----",
466 utc ?
" UTC " : " ");
474 localtime_r(time
, &t
);
476 return print_in_hook(data
, "%s %02d %02d:%02d:%02d%s%04d",
477 months
[t
.tm_mon
], t
.tm_mday
, t
.tm_hour
, t
.tm_min
,
478 t
.tm_sec
, utc ?
" UTC " : " ", t
.tm_year
+ 1900);
482 * Described in header.
484 int time_delta_printf_hook(printf_hook_data_t
*data
, printf_hook_spec_t
*spec
,
485 const void *const *args
)
487 char* unit
= "second";
488 time_t *arg1
= *((time_t**)(args
[0]));
489 time_t *arg2
= *((time_t**)(args
[1]));
490 u_int64_t delta
= llabs(*arg1
- *arg2
);
492 if (delta
> 2 * 60 * 60 * 24)
494 delta
/= 60 * 60 * 24;
497 else if (delta
> 2 * 60 * 60)
502 else if (delta
> 2 * 60)
507 return print_in_hook(data
, "%" PRIu64
" %s%s", delta
, unit
,
508 (delta
== 1) ?
"" : "s");
512 * Number of bytes per line to dump raw data
514 #define BYTES_PER_LINE 16
516 static char hexdig_upper
[] = "0123456789ABCDEF";
519 * Described in header.
521 int mem_printf_hook(printf_hook_data_t
*data
,
522 printf_hook_spec_t
*spec
, const void *const *args
)
524 char *bytes
= *((void**)(args
[0]));
525 u_int len
= *((int*)(args
[1]));
527 char buffer
[BYTES_PER_LINE
* 3];
528 char ascii_buffer
[BYTES_PER_LINE
+ 1];
529 char *buffer_pos
= buffer
;
530 char *bytes_pos
= bytes
;
531 char *bytes_roof
= bytes
+ len
;
536 written
+= print_in_hook(data
, "=> %u bytes @ %p", len
, bytes
);
538 while (bytes_pos
< bytes_roof
)
540 *buffer_pos
++ = hexdig_upper
[(*bytes_pos
>> 4) & 0xF];
541 *buffer_pos
++ = hexdig_upper
[ *bytes_pos
& 0xF];
544 (*bytes_pos
> 31 && *bytes_pos
< 127) ?
*bytes_pos
: '.';
546 if (++bytes_pos
== bytes_roof
|| i
== BYTES_PER_LINE
)
548 int padding
= 3 * (BYTES_PER_LINE
- i
);
554 *buffer_pos
++ = '\0';
555 ascii_buffer
[i
] = '\0';
557 written
+= print_in_hook(data
, "\n%4d: %s %s",
558 line_start
, buffer
, ascii_buffer
);
561 line_start
+= BYTES_PER_LINE
;