]> wimlib.net Git - wimlib/blob - src/util.c
Remove printf extension
[wimlib] / src / util.c
1 /*
2  * util.c
3  */
4
5 /*
6  * Copyright (C) 2012, 2013 Eric Biggers
7  *
8  * This file is part of wimlib, a library for working with WIM files.
9  *
10  * wimlib is free software; you can redistribute it and/or modify it under the
11  * terms of the GNU General Public License as published by the Free
12  * Software Foundation; either version 3 of the License, or (at your option)
13  * any later version.
14  *
15  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
16  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17  * A PARTICULAR PURPOSE. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with wimlib; if not, see http://www.gnu.org/licenses/.
22  */
23
24 #ifdef HAVE_CONFIG_H
25 #  include "config.h"
26 #endif
27
28 #ifdef _GNU_SOURCE
29 #  define _GNU_SOURCE_DEFINED 1
30 #  undef _GNU_SOURCE
31 #endif
32 /* Make sure the POSIX-compatible strerror_r() is declared, rather than the GNU
33  * version, which has a different return type. */
34 #include <string.h>
35 #ifdef _GNU_SOURCE_DEFINED
36 #  define _GNU_SOURCE
37 #endif
38
39 #include "wimlib.h"
40 #include "wimlib/compiler.h"
41 #include "wimlib/encoding.h"
42 #include "wimlib/error.h"
43 #include "wimlib/types.h"
44 #include "wimlib/util.h"
45 #include "wimlib/xml.h"
46
47 #ifdef __WIN32__
48 #  include "wimlib/win32.h" /* win32_strerror_r_replacement */
49 #endif
50
51 #include <errno.h>
52 #include <stdarg.h>
53 #include <stdlib.h>
54 #include <time.h>
55 #include <unistd.h>
56
57 size_t
58 utf16le_strlen(const utf16lechar *s)
59 {
60         const utf16lechar *p = s;
61         while (*p)
62                 p++;
63         return (p - s) * sizeof(utf16lechar);
64 }
65
66 #ifdef ENABLE_ERROR_MESSAGES
67 bool wimlib_print_errors = false;
68 #endif
69
70 #if defined(ENABLE_ERROR_MESSAGES) || defined(ENABLE_DEBUG)
71 static void
72 wimlib_vmsg(const tchar *tag, const tchar *format,
73             va_list va, bool perror)
74 {
75 #if !defined(ENABLE_DEBUG)
76         if (wimlib_print_errors)
77 #endif
78         {
79                 int errno_save = errno;
80                 fflush(stdout);
81                 tfputs(tag, stderr);
82                 tvfprintf(stderr, format, va);
83                 if (perror && errno_save != 0) {
84                         tchar buf[64];
85                         int res;
86                         res = tstrerror_r(errno_save, buf, ARRAY_LEN(buf));
87                         if (res) {
88                                 tsprintf(buf,
89                                          T("unknown error (errno=%d)"),
90                                          errno_save);
91                         }
92                 #ifdef WIN32
93                         if (errno_save == EBUSY)
94                                 tstrcpy(buf, T("Resource busy"));
95                 #endif
96                         tfprintf(stderr, T(": %"TS), buf);
97                 }
98                 tputc(T('\n'), stderr);
99                 fflush(stderr);
100                 errno = errno_save;
101         }
102 }
103 #endif
104
105 /* True if wimlib is to print an informational message when an error occurs.
106  * This can be turned off by calling wimlib_set_print_errors(false). */
107 #ifdef ENABLE_ERROR_MESSAGES
108 void
109 wimlib_error(const tchar *format, ...)
110 {
111         va_list va;
112
113         va_start(va, format);
114         wimlib_vmsg(T("\r[ERROR] "), format, va, false);
115         va_end(va);
116 }
117
118 void
119 wimlib_error_with_errno(const tchar *format, ...)
120 {
121         va_list va;
122
123         va_start(va, format);
124         wimlib_vmsg(T("\r[ERROR] "), format, va, true);
125         va_end(va);
126 }
127
128 void
129 wimlib_warning(const tchar *format, ...)
130 {
131         va_list va;
132
133         va_start(va, format);
134         wimlib_vmsg(T("\r[WARNING] "), format, va, false);
135         va_end(va);
136 }
137
138 void
139 wimlib_warning_with_errno(const tchar *format, ...)
140 {
141         va_list va;
142
143         va_start(va, format);
144         wimlib_vmsg(T("\r[WARNING] "), format, va, true);
145         va_end(va);
146 }
147
148 #endif
149
150 #if defined(ENABLE_DEBUG) || defined(ENABLE_MORE_DEBUG)
151 void wimlib_debug(const tchar *file, int line, const char *func,
152                   const tchar *format, ...)
153 {
154         va_list va;
155         tchar buf[tstrlen(file) + strlen(func) + 30];
156
157         static bool debug_enabled = false;
158         if (!debug_enabled) {
159                 char *value = getenv("WIMLIB_DEBUG");
160                 if (!value || strcmp(value, "0"))
161                         debug_enabled = true;
162                 else
163                         return;
164         }
165
166         tsprintf(buf, T("[%"TS" %d] %s(): "), file, line, func);
167
168         va_start(va, format);
169         wimlib_vmsg(buf, format, va, false);
170         va_end(va);
171 }
172 #endif
173
174 /* API function documented in wimlib.h  */
175 WIMLIBAPI int
176 wimlib_set_print_errors(bool show_error_messages)
177 {
178 #ifdef ENABLE_ERROR_MESSAGES
179         wimlib_print_errors = show_error_messages;
180         return 0;
181 #else
182         if (show_error_messages)
183                 return WIMLIB_ERR_UNSUPPORTED;
184         else
185                 return 0;
186 #endif
187 }
188
189 static const tchar *error_strings[] = {
190         [WIMLIB_ERR_SUCCESS]
191                 = T("Success"),
192         [WIMLIB_ERR_ALREADY_LOCKED]
193                 = T("The WIM is already locked for writing"),
194         [WIMLIB_ERR_DECOMPRESSION]
195                 = T("Failed to decompress compressed data"),
196         [WIMLIB_ERR_DELETE_STAGING_DIR]
197                 = T("Failed to delete staging directory"),
198         [WIMLIB_ERR_FILESYSTEM_DAEMON_CRASHED]
199                 = T("The process servicing the mounted WIM has crashed"),
200         [WIMLIB_ERR_FORK]
201                 = T("Failed to fork another process"),
202         [WIMLIB_ERR_FUSE]
203                 = T("An error was returned by fuse_main()"),
204         [WIMLIB_ERR_FUSERMOUNT]
205                 = T("Could not execute the `fusermount' program, or it exited "
206                         "with a failure status"),
207         [WIMLIB_ERR_GLOB_HAD_NO_MATCHES]
208                 = T("The provided file glob did not match any files"),
209         [WIMLIB_ERR_ICONV_NOT_AVAILABLE]
210                 = T("The iconv() function does not seem to work. "
211                   "Maybe check to make sure the directory /usr/lib/gconv exists"),
212         [WIMLIB_ERR_IMAGE_COUNT]
213                 = T("Inconsistent image count among the metadata "
214                         "resources, the WIM header, and/or the XML data"),
215         [WIMLIB_ERR_IMAGE_NAME_COLLISION]
216                 = T("Tried to add an image with a name that is already in use"),
217         [WIMLIB_ERR_INSUFFICIENT_PRIVILEGES]
218                 = T("The user does not have sufficient privileges"),
219         [WIMLIB_ERR_INTEGRITY]
220                 = T("The WIM failed an integrity check"),
221         [WIMLIB_ERR_INVALID_CAPTURE_CONFIG]
222                 = T("The capture configuration string was invalid"),
223         [WIMLIB_ERR_INVALID_CHUNK_SIZE]
224                 = T("The WIM chunk size was invalid"),
225         [WIMLIB_ERR_INVALID_COMPRESSION_TYPE]
226                 = T("The WIM compression type was invalid"),
227         [WIMLIB_ERR_INVALID_HEADER]
228                 = T("The WIM header was invalid"),
229         [WIMLIB_ERR_INVALID_IMAGE]
230                 = T("Tried to select an image that does not exist in the WIM"),
231         [WIMLIB_ERR_INVALID_INTEGRITY_TABLE]
232                 = T("The WIM's integrity table is invalid"),
233         [WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY]
234                 = T("An entry in the WIM's lookup table is invalid"),
235         [WIMLIB_ERR_INVALID_MULTIBYTE_STRING]
236                 = T("A string was not valid in the current locale's character encoding"),
237         [WIMLIB_ERR_INVALID_OVERLAY]
238                 = T("Conflicting files in overlay when creating a WIM image"),
239         [WIMLIB_ERR_INVALID_PARAM]
240                 = T("An invalid parameter was given"),
241         [WIMLIB_ERR_INVALID_PART_NUMBER]
242                 = T("The part number or total parts of the WIM is invalid"),
243         [WIMLIB_ERR_INVALID_PIPABLE_WIM]
244                 = T("The pipable WIM is invalid"),
245         [WIMLIB_ERR_INVALID_REPARSE_DATA]
246                 = T("The reparse data of a reparse point was invalid"),
247         [WIMLIB_ERR_INVALID_RESOURCE_HASH]
248                 = T("The SHA1 message digest of a WIM resource did not match the expected value"),
249         [WIMLIB_ERR_INVALID_METADATA_RESOURCE]
250                 = T("The metadata resource is invalid"),
251         [WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE]
252                 = T("The version of wimlib that has mounted a WIM image is incompatible with the "
253                   "version being used to unmount it"),
254         [WIMLIB_ERR_INVALID_UTF8_STRING]
255                 = T("A string provided as input by the user was not a valid UTF-8 string"),
256         [WIMLIB_ERR_INVALID_UTF16_STRING]
257                 = T("A string in a WIM dentry is not a valid UTF-16LE string"),
258         [WIMLIB_ERR_IS_DIRECTORY]
259                 = T("One of the specified paths to delete was a directory"),
260         [WIMLIB_ERR_IS_SPLIT_WIM]
261                 = T("The WIM is part of a split WIM, which is not supported for this operation"),
262         [WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE]
263                 = T("libxml2 was unable to find a character encoding conversion handler "
264                   "for UTF-16LE"),
265         [WIMLIB_ERR_LINK]
266                 = T("Failed to create a hard or symbolic link when extracting "
267                         "a file from the WIM"),
268         [WIMLIB_ERR_METADATA_NOT_FOUND]
269                 = T("A required metadata resource could not be located"),
270         [WIMLIB_ERR_MKDIR]
271                 = T("Failed to create a directory"),
272         [WIMLIB_ERR_MQUEUE]
273                 = T("Failed to create or use a POSIX message queue"),
274         [WIMLIB_ERR_NOMEM]
275                 = T("Ran out of memory"),
276         [WIMLIB_ERR_NOTDIR]
277                 = T("Expected a directory"),
278         [WIMLIB_ERR_NOTEMPTY]
279                 = T("Directory was not empty"),
280         [WIMLIB_ERR_NOT_A_WIM_FILE]
281                 = T("The file did not begin with the magic characters that "
282                         "identify a WIM file"),
283         [WIMLIB_ERR_NOT_A_REGULAR_FILE]
284                 = T("One of the specified paths to extract did not "
285                     "correspond to a regular file"),
286         [WIMLIB_ERR_NO_FILENAME]
287                 = T("The WIM is not identified with a filename"),
288         [WIMLIB_ERR_NOT_PIPABLE]
289                 = T("The WIM was not captured such that it can be "
290                     "applied from a pipe"),
291         [WIMLIB_ERR_NTFS_3G]
292                 = T("NTFS-3g encountered an error (check errno)"),
293         [WIMLIB_ERR_OPEN]
294                 = T("Failed to open a file"),
295         [WIMLIB_ERR_OPENDIR]
296                 = T("Failed to open a directory"),
297         [WIMLIB_ERR_PATH_DOES_NOT_EXIST]
298                 = T("The path does not exist in the WIM image"),
299         [WIMLIB_ERR_READ]
300                 = T("Could not read data from a file"),
301         [WIMLIB_ERR_READLINK]
302                 = T("Could not read the target of a symbolic link"),
303         [WIMLIB_ERR_RENAME]
304                 = T("Could not rename a file"),
305         [WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED]
306                 = T("Unable to complete reparse point fixup"),
307         [WIMLIB_ERR_RESOURCE_NOT_FOUND]
308                 = T("A file resource needed to complete the operation was missing from the WIM"),
309         [WIMLIB_ERR_RESOURCE_ORDER]
310                 = T("The components of the WIM were arranged in an unexpected order"),
311         [WIMLIB_ERR_SET_ATTRIBUTES]
312                 = T("Failed to set attributes on extracted file"),
313         [WIMLIB_ERR_SET_REPARSE_DATA]
314                 = T("Failed to set reparse data on extracted file"),
315         [WIMLIB_ERR_SET_SECURITY]
316                 = T("Failed to set file owner, group, or other permissions on extracted file"),
317         [WIMLIB_ERR_SET_SHORT_NAME]
318                 = T("Failed to set short name on extracted file"),
319         [WIMLIB_ERR_SET_TIMESTAMPS]
320                 = T("Failed to set timestamps on extracted file"),
321         [WIMLIB_ERR_SPLIT_INVALID]
322                 = T("The WIM is part of an invalid split WIM"),
323         [WIMLIB_ERR_STAT]
324                 = T("Could not read the metadata for a file or directory"),
325         [WIMLIB_ERR_TIMEOUT]
326                 = T("Timed out while waiting for a message to arrive from another process"),
327         [WIMLIB_ERR_UNEXPECTED_END_OF_FILE]
328                 = T("Unexpectedly reached the end of the file"),
329         [WIMLIB_ERR_UNICODE_STRING_NOT_REPRESENTABLE]
330                 = T("A Unicode string could not be represented in the current locale's encoding"),
331         [WIMLIB_ERR_UNKNOWN_VERSION]
332                 = T("The WIM file is marked with an unknown version number"),
333         [WIMLIB_ERR_UNSUPPORTED]
334                 = T("The requested operation is unsupported"),
335         [WIMLIB_ERR_UNSUPPORTED_FILE]
336                 = T("A file in the directory tree to archive was not of a supported type"),
337         [WIMLIB_ERR_VOLUME_LACKS_FEATURES]
338                 = T("The volume did not support a feature necessary to complete the operation"),
339         [WIMLIB_ERR_WIM_IS_READONLY]
340                 = T("The WIM is read-only (file permissions, header flag, or split WIM)"),
341         [WIMLIB_ERR_WRITE]
342                 = T("Failed to write data to a file"),
343         [WIMLIB_ERR_XML]
344                 = T("The XML data of the WIM is invalid"),
345         [WIMLIB_ERR_WIM_IS_ENCRYPTED]
346                 = T("The WIM file (or parts of it) is encrypted"),
347         [WIMLIB_ERR_WIMBOOT]
348                 = T("Failed to set WIMBoot pointer data"),
349 };
350
351 /* API function documented in wimlib.h  */
352 WIMLIBAPI const tchar *
353 wimlib_get_error_string(enum wimlib_error_code code)
354 {
355         if ((int)code < 0 || code >= ARRAY_LEN(error_strings))
356                 return NULL;
357         else
358                 return error_strings[code];
359 }
360
361
362
363 static void *(*wimlib_malloc_func) (size_t)          = malloc;
364 static void  (*wimlib_free_func)   (void *)          = free;
365 static void *(*wimlib_realloc_func)(void *, size_t) = realloc;
366
367 void *
368 wimlib_malloc(size_t size)
369 {
370         void *ptr;
371
372 retry:
373         ptr = (*wimlib_malloc_func)(size);
374         if (unlikely(!ptr)) {
375                 if (!size) {
376                         size++;
377                         goto retry;
378                 }
379                 ERROR("memory exhausted");
380         }
381         return ptr;
382 }
383
384 void
385 wimlib_free_memory(void *ptr)
386 {
387         (*wimlib_free_func)(ptr);
388 }
389
390 void *
391 wimlib_realloc(void *ptr, size_t size)
392 {
393         if (size == 0)
394                 size = 1;
395         ptr = (*wimlib_realloc_func)(ptr, size);
396         if (ptr == NULL)
397                 ERROR("memory exhausted");
398         return ptr;
399 }
400
401 void *
402 wimlib_calloc(size_t nmemb, size_t size)
403 {
404         size_t total_size = nmemb * size;
405         void *p = MALLOC(total_size);
406         if (p)
407                 p = memset(p, 0, total_size);
408         return p;
409 }
410
411 char *
412 wimlib_strdup(const char *str)
413 {
414         size_t size;
415         char *p;
416
417         size = strlen(str);
418         p = MALLOC(size + 1);
419         if (p)
420                 p = memcpy(p, str, size + 1);
421         return p;
422 }
423
424 #ifdef __WIN32__
425 wchar_t *
426 wimlib_wcsdup(const wchar_t *str)
427 {
428         size_t size;
429         wchar_t *p;
430
431         size = wcslen(str);
432         p = MALLOC((size + 1) * sizeof(wchar_t));
433         if (p)
434                 p = wmemcpy(p, str, size + 1);
435         return p;
436 }
437 #endif
438
439 void *
440 memdup(const void *mem, size_t size)
441 {
442         void *ptr = MALLOC(size);
443         if (ptr)
444                 ptr = memcpy(ptr, mem, size);
445         return ptr;
446 }
447
448 /* API function documented in wimlib.h  */
449 WIMLIBAPI int
450 wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
451                             void (*free_func)(void *),
452                             void *(*realloc_func)(void *, size_t))
453 {
454         wimlib_malloc_func  = malloc_func  ? malloc_func  : malloc;
455         wimlib_free_func    = free_func    ? free_func    : free;
456         wimlib_realloc_func = realloc_func ? realloc_func : realloc;
457
458         xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
459                                  wimlib_realloc_func);
460         return 0;
461 }
462
463 static bool seeded = false;
464
465 static void
466 seed_random(void)
467 {
468         srand(time(NULL) * getpid());
469         seeded = true;
470 }
471
472 /* Fills @n characters pointed to by @p with random alphanumeric characters. */
473 void
474 randomize_char_array_with_alnum(tchar p[], size_t n)
475 {
476         if (!seeded)
477                 seed_random();
478         while (n--) {
479                 int r = rand() % 62;
480                 if (r < 26)
481                         *p++ = r + 'a';
482                 else if (r < 52)
483                         *p++ = r - 26 + 'A';
484                 else
485                         *p++ = r - 52 + '0';
486         }
487 }
488
489 /* Fills @n bytes pointer to by @p with random numbers. */
490 void
491 randomize_byte_array(u8 *p, size_t n)
492 {
493         if (!seeded)
494                 seed_random();
495         while (n--)
496                 *p++ = rand();
497 }
498
499
500 void print_byte_field(const u8 field[], size_t len, FILE *out)
501 {
502         while (len--)
503                 tfprintf(out, T("%02hhx"), *field++);
504 }
505
506 #ifndef HAVE_MEMPCPY
507 void *mempcpy(void *dst, const void *src, size_t n)
508 {
509         return memcpy(dst, src, n) + n;
510 }
511 #endif