common_func.c 17.1 KB
Newer Older
1
/* common_func.c - functions used almost everywhere */
2 3

#include <assert.h>
4 5
#include <ctype.h>
#include <errno.h>
6
#include <stdarg.h>
7 8
#include <stdlib.h>
#include <string.h>
9
#include <wchar.h>
10

11 12
#if defined( _WIN32) || defined(__CYGWIN__)
# include <windows.h>
13
#endif
14

15
#include "common_func.h"
16
#include "parse_cmdline.h"
17
#include "version.h"
18
#include "win_utils.h"
19 20 21 22

/*=========================================================================
 * String functions
 *=========================================================================*/
23 24

/**
25 26 27 28 29 30
 * Print a 0-terminated string representation of a 64-bit number to
 * a string buffer.
 *
 * @param dst the string buffer to write the number to
 * @param number the 64-bit number to output
 * @param min_width the minimum width, the number must take
31
 */
32
void sprintI64(char *dst, uint64_t number, int min_width)
33
{
34 35 36 37
	char buf[24]; /* internal buffer to output the number to */
	size_t len;
	char *p = buf + 23; /* start filling from the buffer end */
	*(p--) = 0; /* last symbol should be '\0' */
38
	if (number == 0) {
39 40
		*(p--) = '0';
	} else {
41
		for (; p >= buf && number != 0; p--, number /= 10) {
42 43 44 45
			*p = '0' + (char)(number % 10);
		}
	}
	len = buf + 22 - p;
46
	if ((size_t)min_width > len) {
47 48 49 50
		memset(dst, 0x20, min_width - len); /* fill by spaces */
		dst += min_width - len;
	}
	memcpy(dst, p+1, len+1); /* copy the number to the output buffer */
51 52 53 54
}

/**
 * Calculate length of decimal representation of given 64-bit integer.
55
 *
56 57 58 59 60
 * @param num integer to calculate the length for
 * @return length of decimal representation
 */
int int_len(uint64_t num)
{
61
	int len;
62
	for (len = 0; num; len++, num /= 10);
63
	return (len == 0 ? 1 : len); /* note: int_len(0) == 1 */
64 65
}

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
/**
 * Convert a byte to a hexadecimal string. The result, consisting of two
 * hexadecimal digits is stored into a buffer.
 *
 * @param dst  the buffer to receive two symbols of hex representation
 * @param byte the byte to decode
 * @param upper_case flag to print string in uppercase
 * @return pointer to the next char in buffer (dst+2)
 */
static char* print_hex_byte(char *dst, const unsigned char byte, int upper_case)
{
	const char add = (upper_case ? 'A' - 10 : 'a' - 10);
	unsigned char c = (byte >> 4) & 15;
	*dst++ = (c > 9 ? c + add : c + '0');
	c = byte & 15;
	*dst++ = (c > 9 ? c + add : c + '0');
	return dst;
}

85
/* unsafe characters are "<>{}[]%#/|\^~`@:;?=&+ */
86
#define IS_GOOD_URL_CHAR(c) (isalnum((unsigned char)c) || strchr("$-_.!'(),", c))
87 88

/**
89
 * URL-encode a string.
90
 *
91
 * @param dst buffer to receive result or NULL to calculate
92
 *    the lengths of encoded string
93 94 95 96 97
 * @param filename the file name
 * @return the length of the result string
 */
int urlencode(char *dst, const char *name)
{
98
	const char *start;
99
	if (!dst) {
100
		int len;
101
		for (len = 0; *name; name++) len += (IS_GOOD_URL_CHAR(*name) ? 1 : 3);
102 103 104
		return len;
	}
	/* encode URL as specified by RFC 1738 */
105 106
	for (start = dst; *name; name++) {
		if ( IS_GOOD_URL_CHAR(*name) ) {
107 108 109
			*dst++ = *name;
		} else {
			*dst++ = '%';
110
			dst = print_hex_byte(dst, *name, 'A');
111 112 113 114
		}
	}
	*dst = 0;
	return (int)(dst - start);
115 116 117 118 119 120 121 122 123 124 125 126
}

/**
 * Convert given string to lower case.
 * The result string will be allocated by malloc.
 * The allocated memory should be freed by calling free().
 *
 * @param str a string to convert
 * @return converted string allocated by malloc
 */
char* str_tolower(const char* str)
{
127 128
	char* buf = rsh_strdup(str);
	char* p;
129 130
	if (buf) {
		for (p = buf; *p; p++) *p = tolower(*p);
131 132
	}
	return buf;
133 134 135 136 137 138 139 140 141 142
}

/**
 * Remove spaces from the begin and the end of the string.
 *
 * @param str the modifiable buffer with the string
 * @return trimmed string
 */
char* str_trim(char* str)
{
143
	char* last = str + strlen(str) - 1;
144 145
	while (isspace((unsigned char)*str)) str++;
	while (isspace((unsigned char)*last) && last > str) *(last--) = 0;
146
	return str;
147 148 149
}

/**
150
 * Fill a buffer with NULL-terminated string consisting
151 152 153 154 155 156 157 158 159
 * solely of a given repeated character.
 *
 * @param buf  the modifiable buffer to fill
 * @param ch   the character to fill string with
 * @param length the length of the string to construct
 * @return the buffer
 */
char* str_set(char* buf, int ch, int length)
{
160 161 162
	memset(buf, ch, length);
	buf[length] = '\0';
	return buf;
163 164
}

165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
/**
 * Concatenates two strings and returns allocated buffer with result.
 *
 * @param orig original string
 * @param append the string to append
 * @return the buffer
 */
char* str_append(const char* orig, const char* append)
{
	size_t len1 = strlen(orig);
	size_t len2 = strlen(append);
	char* res = (char*)rsh_malloc(len1 + len2 + 1);

	/* concatenate two strings */
	memcpy(res, orig, len1);
	memcpy(res + len1, append, len2 + 1);
	return res;
}

184 185 186 187 188 189 190 191 192
/**
 * Check if a string is a binary string, which means the string contain
 * a character with ACII code below 0x20 other than '\r', '\n', '\t'.
 *
 * @param str a string to check
 * @return non zero if string is binary
 */
int is_binary_string(const char* str)
{
193 194
	for (; *str; str++) {
		if (((unsigned char)*str) < 32 && ((1 << (unsigned char)*str) & ~0x2600)) {
195 196 197 198
			return 1;
		}
	}
	return 0;
199 200 201 202 203 204 205 206 207 208
}

/**
 * Count number of utf8 characters in a 0-terminated string
 *
 * @param str the string to measure
 * @return number of utf8 characters in the string
 */
size_t strlen_utf8_c(const char *str)
{
209
	size_t length = 0;
210 211
	for (; *str; str++) {
		if ((*str & 0xc0) != 0x80) length++;
212 213
	}
	return length;
214 215
}

216 217 218 219 220
/*=========================================================================
* Program version information
*=========================================================================*/

const char* get_version_string(void)
221
{
222 223
	static const char* version_string = VERSION;
	return version_string;
224 225
}

226 227 228 229 230 231 232 233 234 235
const char* get_bt_program_name(void)
{
	static const char* bt_program_name = PROGRAM_NAME "/" VERSION;
	return bt_program_name;
}

/*=========================================================================
 * Timer functions
 *=========================================================================*/

236
/**
237 238 239
 * Return real-value representing number of seconds
 * stored in the given timeval structure.
 * The function is used with timers, when printing time statistics.
240
 *
241 242
 * @param delta time delta to be converted
 * @return number of seconds
243
 */
244
static double rsh_fsec(timedelta_t* timer)
245
{
246
#if defined( _WIN32) || defined(__CYGWIN__)
247 248 249 250 251 252
	LARGE_INTEGER freq;
	QueryPerformanceFrequency(&freq);
	return (double)*timer / freq.QuadPart;
#else
	return ((double)timer->tv_usec / 1000000.0) + timer->tv_sec;
#endif
253 254
}

255
#if defined( _WIN32) || defined(__CYGWIN__)
256 257 258 259 260 261
#define get_timedelta(delta) QueryPerformanceCounter((LARGE_INTEGER*)delta)
#else
#define get_timedelta(delta) gettimeofday(delta, NULL)
#endif

void rsh_timer_start(timedelta_t* timer)
262
{
263 264 265 266 267 268 269
	get_timedelta(timer);
}

double rsh_timer_stop(timedelta_t* timer)
{
	timedelta_t end;
	get_timedelta(&end);
270
#if defined( _WIN32) || defined(__CYGWIN__)
271 272 273 274 275 276
	*timer = end - *timer;
#else
	timer->tv_sec  = end.tv_sec  - timer->tv_sec - (end.tv_usec >= timer->tv_usec ? 0 : 1);
	timer->tv_usec = end.tv_usec + (end.tv_usec >= timer->tv_usec ? 0 : 1000000 ) - timer->tv_usec;
#endif
	return rsh_fsec(timer);
277
}
278 279 280

unsigned rhash_get_ticks(void)
{
281
#if defined( _WIN32) || defined(__CYGWIN__)
282
	return GetTickCount();
283
#else
284 285 286
	struct timeval tv;
	gettimeofday(&tv, NULL);
	return (tv.tv_sec * 1000 + tv.tv_usec / 1000);
287 288
#endif
}
289

290
/*=========================================================================
291
 * Custom program exit function
292 293
 *=========================================================================*/

294
struct rhash_exit_handlers_t
295
{
296 297 298
	unsigned handlers_count;
	exit_handler_t handlers[4];
} rhash_exit_handlers = { 0, { 0 } };
299

300
/**
301 302 303 304 305
* Install a handler to be called on program exit.
*
* @param handler the hadler to add
*/
void rsh_install_exit_handler(exit_handler_t handler)
306
{
307 308 309 310
	if (rhash_exit_handlers.handlers_count >= (sizeof(rhash_exit_handlers.handlers) / sizeof(rhash_exit_handlers.handlers[0])))
	{
		assert(!"to many handlers");
		rsh_exit(2);
311
	}
312 313
	rhash_exit_handlers.handlers[rhash_exit_handlers.handlers_count] = handler;
	rhash_exit_handlers.handlers_count++;
314 315
}

316
/**
317 318 319
* Remove the last installed exit handler.
*/
void rsh_remove_exit_handler(void)
320
{
321 322 323 324
	if (rhash_exit_handlers.handlers_count == 0)
	{
		assert(rhash_exit_handlers.handlers_count > 0 && "no handlers installed");
		rsh_exit(2);
325
	}
326
	rhash_exit_handlers.handlers_count--;
327 328 329
}

/**
330
* Call all installed exit handlers, starting from the latest one, and exit the program.
331 332 333
*
* @param code the program exit code
*/
334
void rsh_exit(int code)
335
{
336 337
	while (rhash_exit_handlers.handlers_count > 0)
		rhash_exit_handlers.handlers[--rhash_exit_handlers.handlers_count]();
338
	exit(code);
339
}
340

341 342 343
/*=========================================================================
 * Error reporting functions
 *=========================================================================*/
344 345 346 347 348 349 350 351 352 353 354 355

static void report_error_default(const char* srcfile, int srcline,
	const char* format, ...);

void (*rsh_report_error)(const char* srcfile, int srcline,
	const char* format, ...) = report_error_default;

/**
 * Print given library failure to stderr.
 *
 * @param srcfile source file to report error on fail
 * @param srcline source code line to be reported on fail
356
 * @param format printf-formatted error message
357 358 359 360
 */
static void report_error_default(const char* srcfile, int srcline, const char* format, ...)
{
	va_list ap;
361
	rsh_fprintf(stderr, "RHash: error at %s:%u: ", srcfile, srcline);
362
	va_start(ap, format);
363
	rsh_vfprintf(stderr, format, ap); /* report the error to stderr */
364 365 366
	va_end(ap);
}

367 368 369
/*=========================================================================
 * Memory functions
 *=========================================================================*/
370 371 372 373 374 375 376 377 378 379 380 381

/**
 * Allocates a buffer via malloc with reporting memory error to stderr.
 *
 * @param size size of the block to allocate
 * @param srcfile source file to report error on fail
 * @param srcline source code line to be reported on fail
 * @return allocated block
 */
void* rhash_malloc(size_t size, const char* srcfile, int srcline)
{
	void* res = malloc(size);
382
	if (!res) {
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
		rsh_report_error(srcfile, srcline, "%s(%u) failed\n", "malloc", (unsigned)size);
		rsh_exit(2);
	}
	return res;
}

/**
 * Allocates a buffer via calloc with reporting memory error to stderr.
 *
 * @param num number of elements to be allocated
 * @param size size of elements
 * @param srcfile source file to report error on fail
 * @param srcline source code line to be reported on fail
 * @return allocated block
 */
void* rhash_calloc(size_t num, size_t size, const char* srcfile, int srcline)
{
	void* res = calloc(num, size);
401
	if (!res) {
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
		rsh_report_error(srcfile, srcline, "calloc(%u, %u) failed\n", (unsigned)num, (unsigned)size);
		rsh_exit(2);
	}
	return res;
}


/**
 * Duplicate c-string with reporting memory error to stderr.
 *
 * @param str the zero-terminated string to duplicate
 * @param srcfile source file to report error on fail
 * @param srcline source code line to be reported on fail
 * @return allocated memory buffer with copied string
 */
char* rhash_strdup(const char* str, const char* srcfile, int srcline)
{
#ifndef __STRICT_ANSI__
	char* res = strdup(str);
#else
	char* res = (char*)malloc(strlen(str)+1);
423
	if (res) strcpy(res, str);
424 425
#endif

426
	if (!res) {
427 428 429 430 431 432
		rsh_report_error(srcfile, srcline, "strdup(\"%s\") failed\n", str);
		rsh_exit(2);
	}
	return res;
}

433 434 435 436 437 438 439 440 441
#ifdef _WIN32
/**
 * Duplicate wide string with reporting memory error to stderr.
 *
 * @param str the zero-terminated string to duplicate
 * @param srcfile source file to report error on fail
 * @param srcline source code line to be reported on fail
 * @return allocated memory buffer with copied string
 */
442
wchar_t* rhash_wcsdup(const wchar_t* str, const char* srcfile, int srcline)
443
{
444
#ifndef __STRICT_ANSI__
445
	wchar_t* res = wcsdup(str);
446 447
#else
	wchar_t* res = (wchar_t*)malloc((wcslen(str) + 1) * sizeof(wchar_t));
448
	if (res) wcscpy(res, str);
449
#endif
450

451
	if (!res) {
452
		rsh_report_error(srcfile, srcline, "wcsdup(\"%u\") failed\n", (wcslen(str) + 1));
453 454 455 456 457 458
		rsh_exit(2);
	}
	return res;
}
#endif

459 460 461 462 463 464 465 466 467 468 469 470
/**
 * Reallocates a buffer via realloc with reporting memory error to stderr.
 *
 * @param mem a memory block to re-allocate
 * @param size the new size of the block
 * @param srcfile source file to report error on fail
 * @param srcline source code line to be reported on fail
 * @return re-allocated memory buffer
 */
void* rhash_realloc(void* mem, size_t size, const char* srcfile, int srcline)
{
	void* res = realloc(mem, size);
471
	if (!res) {
472 473 474 475 476 477
		rsh_report_error(srcfile, srcline, "realloc(%p, %u) failed\n", mem, (unsigned)size);
		rsh_exit(2);
	}
	return res;
}

478 479 480
/*=========================================================================
 * Containers
 *=========================================================================*/
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515

/**
 * Allocate an empty vector.
 *
 * @param destructor pointer to the cleanup/deallocate function called
 *                   on each element when the vector is destructed,
 *                   NULL if items doesn't need to be freed
 * @return allocated vector
 */
vector_t* rsh_vector_new(void (*destructor)(void*))
{
	vector_t* ptr = (vector_t*)rsh_malloc(sizeof(vector_t));
	memset(ptr, 0, sizeof(vector_t));
	ptr->destructor = destructor;
	return ptr;
}

/**
 * Allocate an empty vector of pointers to memory blocks,
 * which will be deallocated at destruction time by calling free().
 *
 * @return allocated vector
 */
struct vector_t* rsh_vector_new_simple(void)
{
	return rsh_vector_new(free);
}

/**
 * Release memory allocated by vector, but the vector structure itself.
 *
 * @param vect the vector to free
 */
void rsh_vector_destroy(vector_t* vect)
{
516 517
	if (!vect) return;
	if (vect->destructor) {
518
		unsigned i;
519
		for (i=0; i<vect->size; i++) vect->destructor(vect->array[i]);
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
	}
	free(vect->array);
	vect->size = vect->allocated = 0;
	vect->array = 0;
}

/**
 * Release all memory allocated by vector.
 *
 * @param vect the vector to free
 */
void rsh_vector_free(vector_t* vect)
{
	rsh_vector_destroy(vect);
	free(vect);
}

/**
 * Add an item to vector.
 *
 * @param vect vector to add item to
 * @param item the item to add
 */
void rsh_vector_add_ptr(vector_t* vect, void* item)
{
545
	/* check if vect contains enough space for the next item */
546
	if (vect->size >= vect->allocated) {
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
		size_t size = (vect->allocated==0 ? 128 : vect->allocated * 2);
		vect->array = (void**)rsh_realloc(vect->array, size * sizeof(void*));
		vect->allocated = size;
	}
	/* add new item to the vector */
	vect->array[vect->size] = item;
	vect->size++;
}

/**
 * Add a sized item to vector.
 *
 * @param vect pointer to the vector to add item to
 * @param item_size the size of a vector item
 */
void rsh_vector_add_empty(struct vector_t* vect, size_t item_size)
{
	/* check if vect contains enough space for next item */
565
	if (vect->size >= vect->allocated) {
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
		size_t size = (vect->allocated==0 ? 128 : vect->allocated * 2);
		vect->array = (void**)rsh_realloc(vect->array, size * item_size);
		vect->allocated = size;
	}
	vect->size++;
}

/**
 * Initialize empty blocks vector.
 *
 * @param bvector pointer to the blocks vector
 */
void rsh_blocks_vector_init(blocks_vector_t* bvector)
{
	memset(bvector, 0, sizeof(*bvector));
	bvector->blocks.destructor = free;
}

/**
 * Free memory allocated by blocks vector, the function
 * doesn't deallocate memory additionally allocated for each element.
 *
 * @param bvector pointer to the blocks vector
 */
void rsh_blocks_vector_destroy(blocks_vector_t* bvector)
{
	rsh_vector_destroy(&bvector->blocks);
}

595 596 597
/*=========================================================================
 * String buffer functions
 *=========================================================================*/
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617

/**
 * Allocate an empty string buffer.
 *
 * @return allocated string buffer
 */
strbuf_t* rsh_str_new(void)
{
	strbuf_t *res = (strbuf_t*)malloc(sizeof(strbuf_t));
	memset(res, 0, sizeof(strbuf_t));
	return res;
}

/**
 * Free memory allocated by string buffer object
 *
 * @param ptr pointer to the string buffer to destroy
 */
void rsh_str_free(strbuf_t* ptr)
{
618
	if (ptr) {
619 620 621 622 623 624 625 626 627 628 629 630 631 632
		free(ptr->str);
		free(ptr);
	}
}

/**
 * Grow, if needed, internal buffer of the given string to ensure it contains
 * at least new_size number bytes.
 *
 * @param str pointer to the string-buffer object
 * @param new_size number of bytes buffer must contain
 */
void rsh_str_ensure_size(strbuf_t *str, size_t new_size)
{
633 634
	if (new_size >= (size_t)str->allocated) {
		if (new_size < 64) new_size = 64;
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
		str->str = (char*)rsh_realloc(str->str, new_size);
		str->allocated = new_size;
	}
}

/**
 * Append a sequence of single-byte characters of the specified length to
 * string buffer. The array is fully copied even if it contains the '\\0'
 * character. The function ensures the string buffer still contains
 * null-terminated string.
 *
 * @param str pointer to the string buffer
 * @param text the text to append
 * @param length number of character to append.
 */
void rsh_str_append_n(strbuf_t *str, const char* text, size_t length)
{
	rsh_str_ensure_length(str, str->len + length + 1);
	memcpy(str->str + str->len, text, length);
	str->len += length;
	str->str[str->len] = '\0';
}

/**
 * Append a null-terminated string to the string string buffer.
 *
 * @param str pointer to the string buffer
 * @param text the null-terminated string to append
 */
void rsh_str_append(strbuf_t *str, const char* text)
{
	rsh_str_append_n(str, text, strlen(text));
}