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