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