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