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