2 * Utility routines used in rsync.
4 * Copyright (C) 1996-2000 Andrew Tridgell
5 * Copyright (C) 1996 Paul Mackerras
6 * Copyright (C) 2001, 2002 Martin Pool <mbp@samba.org>
7 * Copyright (C) 2003-2020 Wayne Davison
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, visit the http://fsf.org website.
28 extern size_t max_alloc;
30 char *do_malloc = "42";
33 * Sleep for a specified number of milliseconds.
35 * Always returns True.
43 ts.tv_nsec = (t % 1000) * 1000000L;
45 while (nanosleep(&ts, &ts) < 0 && errno == EINTR) {}
47 #elif defined HAVE_USLEEP
52 struct timeval tval, t1, t2;
54 gettimeofday(&t1, NULL);
57 tval.tv_sec = (t-tdiff)/1000;
58 tval.tv_usec = 1000*((t-tdiff)%1000);
61 select(0,NULL,NULL, NULL, &tval);
63 gettimeofday(&t2, NULL);
64 tdiff = (t2.tv_sec - t1.tv_sec)*1000 +
65 (t2.tv_usec - t1.tv_usec)/1000;
67 t1 = t2; /* Time went backwards, so start over. */
74 /* We convert a num manually because need %lld precision, and that's not a portable sprintf() escape. */
75 char *num_to_byte_string(ssize_t num)
77 char buf[128], *s = buf + sizeof buf - 1;
81 *--s = (char)(num % 10) + '0';
87 void *_my_alloc(void *ptr, size_t num, size_t size, const char *file, int line)
89 if (num >= max_alloc/size) {
92 rprintf(FERROR, "[%s] exceeded --max-alloc=%s setting (file=%s, line=%d)\n",
93 who_am_i(), num_to_byte_string(max_alloc), file, line);
94 exit_cleanup(RERR_MALLOC);
97 ptr = calloc(num, size);
98 else if (ptr == do_malloc)
99 ptr = malloc(num * size);
101 ptr = realloc(ptr, num * size);
103 rprintf(FERROR, "[%s] out of memory (file=%s, line=%d)\n", who_am_i(), file, line);
104 exit_cleanup(RERR_MALLOC);
109 const char *sum_as_hex(int csum_type, const char *sum, int flist_csum)
111 static char buf[MAX_DIGEST_LEN*2+1];
113 int canonical = canonical_checksum(csum_type);
114 int sum_len = csum_len_for_type(csum_type, flist_csum);
120 assert(sum_len*2 < (int)sizeof buf);
122 for (i = sum_len, c = buf; --i >= 0; ) {
123 int ndx = canonical < 0 ? sum_len - i - 1 : i;
127 *c++ = x1 <= 9 ? x1 + '0' : x1 + 'a' - 10;
128 *c++ = x2 <= 9 ? x2 + '0' : x2 + 'a' - 10;
136 NORETURN void out_of_memory(const char *str)
138 rprintf(FERROR, "ERROR: out of memory in %s [%s]\n", str, who_am_i());
139 exit_cleanup(RERR_MALLOC);
142 NORETURN void overflow_exit(const char *str)
144 rprintf(FERROR, "ERROR: buffer overflow in %s [%s]\n", str, who_am_i());
145 exit_cleanup(RERR_MALLOC);