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