6 * Copyright (C) 2012, 2013 Eric Biggers
8 * This file is part of wimlib, a library for working with WIM files.
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)
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
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/.
28 /* Make sure the POSIX-compatible strerror_r() is declared, rather than the GNU
29 * version, which has a different return type. */
35 #include "wimlib_internal.h"
36 #include "endianness.h"
37 #include "timestamp.h"
49 utf16le_strlen(const utf16lechar *s)
51 const utf16lechar *p = s;
54 return (p - s) * sizeof(utf16lechar);
58 # define wimlib_vfprintf vfwprintf
60 /* Handle %W for UTF16-LE printing.
62 * TODO: this is not yet done properly--- it's assumed that if the format string
63 * contains %W, then it contains no other format specifiers.
66 wimlib_vfprintf(FILE *fp, const tchar *format, va_list va)
71 for (p = format; *p; p++)
72 if (*p == T('%') && *(p + 1) == T('W'))
74 return tvfprintf(fp, format, va);
77 for (p = format; *p; p++) {
78 if (*p == T('%') && (*(p + 1) == T('W'))) {
82 utf16lechar *ucs = va_arg(va, utf16lechar*);
85 size_t ucs_nbytes = utf16le_strlen(ucs);
87 ret = utf16le_to_tstr(ucs, ucs_nbytes,
90 ret = tfprintf(fp, T("??????"));
92 ret = tfprintf(fp, T("%"TS), tstr);
100 n += tfprintf(fp, T("(null)"));
104 if (tputc(*p, fp) == EOF)
113 wimlib_printf(const tchar *format, ...)
118 va_start(va, format);
119 ret = wimlib_vfprintf(stdout, format, va);
125 wimlib_fprintf(FILE *fp, const tchar *format, ...)
130 va_start(va, format);
131 ret = wimlib_vfprintf(fp, format, va);
137 #if defined(ENABLE_ERROR_MESSAGES) || defined(ENABLE_DEBUG)
139 wimlib_vmsg(const tchar *tag, const tchar *format,
140 va_list va, bool perror)
143 if (wimlib_print_errors) {
145 int errno_save = errno;
148 wimlib_vfprintf(stderr, format, va);
149 if (perror && errno_save != 0) {
152 res = tstrerror_r(errno_save, buf, sizeof(buf));
155 T("unknown error (errno=%d)"),
158 tfprintf(stderr, T(": %"TS), buf);
160 tputc(T('\n'), stderr);
169 /* True if wimlib is to print an informational message when an error occurs.
170 * This can be turned off by calling wimlib_set_print_errors(false). */
171 #ifdef ENABLE_ERROR_MESSAGES
172 static bool wimlib_print_errors = false;
176 wimlib_error(const tchar *format, ...)
180 va_start(va, format);
181 wimlib_vmsg(T("\r[ERROR] "), format, va, false);
186 wimlib_error_with_errno(const tchar *format, ...)
190 va_start(va, format);
191 wimlib_vmsg(T("\r[ERROR] "), format, va, true);
196 wimlib_warning(const tchar *format, ...)
200 va_start(va, format);
201 wimlib_vmsg(T("\r[WARNING] "), format, va, false);
206 wimlib_warning_with_errno(const tchar *format, ...)
210 va_start(va, format);
211 wimlib_vmsg(T("\r[WARNING] "), format, va, true);
217 #if defined(ENABLE_DEBUG) || defined(ENABLE_MORE_DEBUG)
218 void wimlib_debug(const tchar *file, int line, const char *func,
219 const tchar *format, ...)
222 tchar buf[tstrlen(file) + strlen(func) + 30];
224 tsprintf(buf, T("[%"TS" %d] %s(): "), file, line, func);
226 va_start(va, format);
227 wimlib_vmsg(buf, format, va, false);
233 wimlib_set_print_errors(bool show_error_messages)
235 #ifdef ENABLE_ERROR_MESSAGES
236 wimlib_print_errors = show_error_messages;
239 if (show_error_messages)
240 return WIMLIB_ERR_UNSUPPORTED;
246 static const tchar *error_strings[] = {
249 [WIMLIB_ERR_ALREADY_LOCKED]
250 = T("The WIM is already locked for writing"),
251 [WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE]
252 = T("Lookup table is compressed"),
253 [WIMLIB_ERR_DECOMPRESSION]
254 = T("Failed to decompress compressed data"),
255 [WIMLIB_ERR_DELETE_STAGING_DIR]
256 = T("Failed to delete staging directory"),
257 [WIMLIB_ERR_FILESYSTEM_DAEMON_CRASHED]
258 = T("The process servicing the mounted WIM has crashed"),
260 = T("Failed to fork another process"),
262 = T("An error was returned by fuse_main()"),
263 [WIMLIB_ERR_FUSERMOUNT]
264 = T("Could not execute the `fusermount' program, or it exited "
265 "with a failure status"),
266 [WIMLIB_ERR_ICONV_NOT_AVAILABLE]
267 = T("The iconv() function does not seem to work. "
268 "Maybe check to make sure the directory /usr/lib/gconv exists"),
269 [WIMLIB_ERR_IMAGE_COUNT]
270 = T("Inconsistent image count among the metadata "
271 "resources, the WIM header, and/or the XML data"),
272 [WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT]
273 = T("User does not have sufficient privileges to correctly extract the data"),
274 [WIMLIB_ERR_IMAGE_NAME_COLLISION]
275 = T("Tried to add an image with a name that is already in use"),
276 [WIMLIB_ERR_INTEGRITY]
277 = T("The WIM failed an integrity check"),
278 [WIMLIB_ERR_INVALID_CAPTURE_CONFIG]
279 = T("The capture configuration string was invalid"),
280 [WIMLIB_ERR_INVALID_CHUNK_SIZE]
281 = T("The WIM is compressed but does not have a chunk "
283 [WIMLIB_ERR_INVALID_COMPRESSION_TYPE]
284 = T("The WIM is compressed, but is not marked as having LZX or "
285 "XPRESS compression"),
286 [WIMLIB_ERR_INVALID_DENTRY]
287 = T("A directory entry in the WIM was invalid"),
288 [WIMLIB_ERR_INVALID_HEADER_SIZE]
289 = T("The WIM header was not 208 bytes"),
290 [WIMLIB_ERR_INVALID_IMAGE]
291 = T("Tried to select an image that does not exist in the WIM"),
292 [WIMLIB_ERR_INVALID_INTEGRITY_TABLE]
293 = T("The WIM's integrity table is invalid"),
294 [WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY]
295 = T("An entry in the WIM's lookup table is invalid"),
296 [WIMLIB_ERR_INVALID_MULTIBYTE_STRING]
297 = T("A string was not valid in the current locale's character encoding"),
298 [WIMLIB_ERR_INVALID_OVERLAY]
299 = T("Conflicting files in overlay when creating a WIM image"),
300 [WIMLIB_ERR_INVALID_PARAM]
301 = T("An invalid parameter was given"),
302 [WIMLIB_ERR_INVALID_PART_NUMBER]
303 = T("The part number or total parts of the WIM is invalid"),
304 [WIMLIB_ERR_INVALID_REPARSE_DATA]
305 = T("The reparse data of a reparse point was invalid"),
306 [WIMLIB_ERR_INVALID_RESOURCE_HASH]
307 = T("The SHA1 message digest of a WIM resource did not match the expected value"),
308 [WIMLIB_ERR_INVALID_RESOURCE_SIZE]
309 = T("A resource entry in the WIM has an invalid size"),
310 [WIMLIB_ERR_INVALID_SECURITY_DATA]
311 = T("The table of security descriptors in the WIM is invalid"),
312 [WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE]
313 = T("The version of wimlib that has mounted a WIM image is incompatible with the "
314 "version being used to unmount it"),
315 [WIMLIB_ERR_INVALID_UTF8_STRING]
316 = T("A string provided as input by the user was not a valid UTF-8 string"),
317 [WIMLIB_ERR_INVALID_UTF16_STRING]
318 = T("A string in a WIM dentry is not a valid UTF-16LE string"),
319 [WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE]
320 = T("libxml2 was unable to find a character encoding conversion handler "
323 = T("Failed to create a hard or symbolic link when extracting "
324 "a file from the WIM"),
326 = T("Failed to create a directory"),
328 = T("Failed to create or use a POSIX message queue"),
330 = T("Ran out of memory"),
332 = T("Expected a directory"),
333 [WIMLIB_ERR_NOT_A_WIM_FILE]
334 = T("The file did not begin with the magic characters that "
335 "identify a WIM file"),
336 [WIMLIB_ERR_NO_FILENAME]
337 = T("The WIM is not identified with a filename"),
339 = T("NTFS-3g encountered an error (check errno)"),
341 = T("Failed to open a file"),
343 = T("Failed to open a directory"),
345 = T("Could not read data from a file"),
346 [WIMLIB_ERR_READLINK]
347 = T("Could not read the target of a symbolic link"),
349 = T("Could not rename a file"),
350 [WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED]
351 = T("Unable to complete reparse point fixup"),
352 [WIMLIB_ERR_RESOURCE_ORDER]
353 = T("The components of the WIM were arranged in an unexpected order"),
354 [WIMLIB_ERR_SPECIAL_FILE]
355 = T("Encountered a special file that cannot be archived"),
356 [WIMLIB_ERR_SPLIT_INVALID]
357 = T("The WIM is part of an invalid split WIM"),
358 [WIMLIB_ERR_SPLIT_UNSUPPORTED]
359 = T("The WIM is part of a split WIM, which is not supported for this operation"),
361 = T("Could not read the metadata for a file or directory"),
363 = T("Timed out while waiting for a message to arrive from another process"),
364 [WIMLIB_ERR_UNICODE_STRING_NOT_REPRESENTABLE]
365 = T("A Unicode string could not be represented in the current locale's encoding"),
366 [WIMLIB_ERR_UNKNOWN_VERSION]
367 = T("The WIM file is marked with an unknown version number"),
368 [WIMLIB_ERR_UNSUPPORTED]
369 = T("The requested operation is unsupported"),
370 [WIMLIB_ERR_VOLUME_LACKS_FEATURES]
371 = T("The volume did not support a feature necessary to complete the operation"),
373 = T("Failed to write data to a file"),
375 = T("The XML data of the WIM is invalid"),
378 WIMLIBAPI const tchar *
379 wimlib_get_error_string(enum wimlib_error_code code)
381 if (code < 0 || code >= ARRAY_LEN(error_strings))
384 return error_strings[code];
389 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
390 void *(*wimlib_malloc_func) (size_t) = malloc;
391 void (*wimlib_free_func) (void *) = free;
392 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
395 wimlib_calloc(size_t nmemb, size_t size)
397 size_t total_size = nmemb * size;
398 void *p = MALLOC(total_size);
400 memset(p, 0, total_size);
405 wimlib_strdup(const char *str)
411 p = MALLOC(size + 1);
413 memcpy(p, str, size + 1);
419 wimlib_wcsdup(const wchar_t *str)
425 p = MALLOC((size + 1) * sizeof(wchar_t));
427 memcpy(p, str, (size + 1) * sizeof(wchar_t));
433 xml_set_memory_allocator(void *(*malloc_func)(size_t),
434 void (*free_func)(void *),
435 void *(*realloc_func)(void *, size_t));
439 wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
440 void (*free_func)(void *),
441 void *(*realloc_func)(void *, size_t))
443 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
444 wimlib_malloc_func = malloc_func ? malloc_func : malloc;
445 wimlib_free_func = free_func ? free_func : free;
446 wimlib_realloc_func = realloc_func ? realloc_func : realloc;
448 xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
449 wimlib_realloc_func);
452 ERROR("Cannot set custom memory allocator functions:");
453 ERROR("wimlib was compiled with the --without-custom-memory-allocator "
455 return WIMLIB_ERR_UNSUPPORTED;
459 static bool seeded = false;
464 srand(time(NULL) * getpid());
468 /* Fills @n characters pointed to by @p with random alphanumeric characters. */
470 randomize_char_array_with_alnum(tchar p[], size_t n)
485 /* Fills @n bytes pointer to by @p with random numbers. */
487 randomize_byte_array(u8 *p, size_t n)
496 path_basename_with_len(const tchar *path, size_t len)
498 const tchar *p = &path[len] - 1;
500 /* Trailing slashes. */
509 while ((p != path - 1) && *p != T('/'))
515 /* Like the basename() function, but does not modify @path; it just returns a
518 path_basename(const tchar *path)
520 return path_basename_with_len(path, tstrlen(path));
524 * Returns a pointer to the part of @path following the first colon in the last
525 * path component, or NULL if the last path component does not contain a colon.
528 path_stream_name(const tchar *path)
530 const tchar *base = path_basename(path);
531 const tchar *stream_name = tstrchr(base, T(':'));
535 return stream_name + 1;
542 gettimeofday(&tv, NULL);
543 return timeval_to_wim_timestamp(tv);
547 wim_timestamp_to_str(u64 timestamp, tchar *buf, size_t len)
550 time_t t = wim_timestamp_to_unix(timestamp);
552 tstrftime(buf, len, T("%a %b %d %H:%M:%S %Y UTC"), &tm);
556 zap_backslashes(tchar *s)
559 while (*s != T('\0')) {
567 /* Write @n bytes from @buf to the file descriptor @fd, retrying on internupt
568 * and on short writes.
570 * Returns short count and set errno on failure. */
572 full_write(int fd, const void *buf, size_t n)
579 ret = write(fd, p, n);
593 /* Read @n bytes from the file descriptor @fd to the buffer @buf, retrying on
594 * interrupt and on short reads.
596 * Returns short count and set errno on failure. */
598 full_read(int fd, void *buf, size_t n)
600 size_t bytes_remaining = n;
601 while (bytes_remaining) {
602 ssize_t bytes_read = read(fd, buf, bytes_remaining);
603 if (bytes_read <= 0) {
610 bytes_remaining -= bytes_read;
613 return n - bytes_remaining;
616 /* Read @n bytes from the file descriptor @fd at the offset @offset to the
617 * buffer @buf, retrying on interrupt and on short reads.
619 * Returns short count and set errno on failure. */
621 full_pread(int fd, void *buf, size_t nbyte, off_t offset)
623 size_t bytes_remaining = nbyte;
626 while (bytes_remaining) {
627 bytes_read = pread(fd, buf, bytes_remaining, offset);
628 if (bytes_read <= 0) {
635 bytes_remaining -= bytes_read;
637 offset += bytes_read;
639 return nbyte - bytes_remaining;
642 /* Like pwrite(), but keep trying until everything has been written or we know
643 * for sure that there was an error. */
645 full_pwrite(int fd, const void *buf, size_t count, off_t offset)
647 ssize_t bytes_remaining = count;
648 ssize_t bytes_written;
650 while (bytes_remaining > 0) {
651 bytes_written = pwrite(fd, buf, bytes_remaining, offset);
652 if (bytes_written <= 0) {
655 if (bytes_written == 0)
659 bytes_remaining -= bytes_written;
660 buf += bytes_written;
661 offset += bytes_written;
663 return count - bytes_remaining;
668 filedes_offset(filedes_t fd)
670 return lseek(fd, 0, SEEK_CUR);