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. */
34 #include "endianness.h"
35 #include "timestamp.h"
36 #include "wimlib_internal.h"
47 # define pread win32_pread
48 # define pwrite win32_pwrite
49 # define writev win32_writev
51 # include <sys/uio.h> /* for writev() and `struct iovec' */
55 utf16le_strlen(const utf16lechar *s)
57 const utf16lechar *p = s;
60 return (p - s) * sizeof(utf16lechar);
64 # define wimlib_vfprintf vfwprintf
66 /* Handle %W for UTF16-LE printing.
68 * TODO: this is not yet done properly--- it's assumed that if the format string
69 * contains %W, then it contains no other format specifiers.
72 wimlib_vfprintf(FILE *fp, const tchar *format, va_list va)
77 for (p = format; *p; p++)
78 if (*p == T('%') && *(p + 1) == T('W'))
80 return tvfprintf(fp, format, va);
83 for (p = format; *p; p++) {
84 if (*p == T('%') && (*(p + 1) == T('W'))) {
88 utf16lechar *ucs = va_arg(va, utf16lechar*);
91 size_t ucs_nbytes = utf16le_strlen(ucs);
93 ret = utf16le_to_tstr(ucs, ucs_nbytes,
96 ret = tfprintf(fp, T("??????"));
98 ret = tfprintf(fp, T("%"TS), tstr);
106 n += tfprintf(fp, T("(null)"));
110 if (tputc(*p, fp) == EOF)
119 wimlib_printf(const tchar *format, ...)
124 va_start(va, format);
125 ret = wimlib_vfprintf(stdout, format, va);
131 wimlib_fprintf(FILE *fp, const tchar *format, ...)
136 va_start(va, format);
137 ret = wimlib_vfprintf(fp, format, va);
143 #if defined(ENABLE_ERROR_MESSAGES) || defined(ENABLE_DEBUG)
145 wimlib_vmsg(const tchar *tag, const tchar *format,
146 va_list va, bool perror)
149 if (wimlib_print_errors) {
151 int errno_save = errno;
154 wimlib_vfprintf(stderr, format, va);
155 if (perror && errno_save != 0) {
158 res = tstrerror_r(errno_save, buf, sizeof(buf));
161 T("unknown error (errno=%d)"),
164 tfprintf(stderr, T(": %"TS), buf);
166 tputc(T('\n'), stderr);
175 /* True if wimlib is to print an informational message when an error occurs.
176 * This can be turned off by calling wimlib_set_print_errors(false). */
177 #ifdef ENABLE_ERROR_MESSAGES
178 static bool wimlib_print_errors = false;
182 wimlib_error(const tchar *format, ...)
186 va_start(va, format);
187 wimlib_vmsg(T("\r[ERROR] "), format, va, false);
192 wimlib_error_with_errno(const tchar *format, ...)
196 va_start(va, format);
197 wimlib_vmsg(T("\r[ERROR] "), format, va, true);
202 wimlib_warning(const tchar *format, ...)
206 va_start(va, format);
207 wimlib_vmsg(T("\r[WARNING] "), format, va, false);
212 wimlib_warning_with_errno(const tchar *format, ...)
216 va_start(va, format);
217 wimlib_vmsg(T("\r[WARNING] "), format, va, true);
223 #if defined(ENABLE_DEBUG) || defined(ENABLE_MORE_DEBUG)
224 void wimlib_debug(const tchar *file, int line, const char *func,
225 const tchar *format, ...)
228 tchar buf[tstrlen(file) + strlen(func) + 30];
230 tsprintf(buf, T("[%"TS" %d] %s(): "), file, line, func);
232 va_start(va, format);
233 wimlib_vmsg(buf, format, va, false);
239 wimlib_set_print_errors(bool show_error_messages)
241 #ifdef ENABLE_ERROR_MESSAGES
242 wimlib_print_errors = show_error_messages;
245 if (show_error_messages)
246 return WIMLIB_ERR_UNSUPPORTED;
252 static const tchar *error_strings[] = {
255 [WIMLIB_ERR_ALREADY_LOCKED]
256 = T("The WIM is already locked for writing"),
257 [WIMLIB_ERR_COMPRESSED_LOOKUP_TABLE]
258 = T("Lookup table is compressed"),
259 [WIMLIB_ERR_DECOMPRESSION]
260 = T("Failed to decompress compressed data"),
261 [WIMLIB_ERR_DELETE_STAGING_DIR]
262 = T("Failed to delete staging directory"),
263 [WIMLIB_ERR_FILESYSTEM_DAEMON_CRASHED]
264 = T("The process servicing the mounted WIM has crashed"),
266 = T("Failed to fork another process"),
268 = T("An error was returned by fuse_main()"),
269 [WIMLIB_ERR_FUSERMOUNT]
270 = T("Could not execute the `fusermount' program, or it exited "
271 "with a failure status"),
272 [WIMLIB_ERR_ICONV_NOT_AVAILABLE]
273 = T("The iconv() function does not seem to work. "
274 "Maybe check to make sure the directory /usr/lib/gconv exists"),
275 [WIMLIB_ERR_IMAGE_COUNT]
276 = T("Inconsistent image count among the metadata "
277 "resources, the WIM header, and/or the XML data"),
278 [WIMLIB_ERR_INSUFFICIENT_PRIVILEGES_TO_EXTRACT]
279 = T("User does not have sufficient privileges to correctly extract the data"),
280 [WIMLIB_ERR_IMAGE_NAME_COLLISION]
281 = T("Tried to add an image with a name that is already in use"),
282 [WIMLIB_ERR_INTEGRITY]
283 = T("The WIM failed an integrity check"),
284 [WIMLIB_ERR_INVALID_CAPTURE_CONFIG]
285 = T("The capture configuration string was invalid"),
286 [WIMLIB_ERR_INVALID_CHUNK_SIZE]
287 = T("The WIM is compressed but does not have a chunk "
289 [WIMLIB_ERR_INVALID_COMPRESSION_TYPE]
290 = T("The WIM is compressed, but is not marked as having LZX or "
291 "XPRESS compression"),
292 [WIMLIB_ERR_INVALID_DENTRY]
293 = T("A directory entry in the WIM was invalid"),
294 [WIMLIB_ERR_INVALID_HEADER_SIZE]
295 = T("The WIM header was not 208 bytes"),
296 [WIMLIB_ERR_INVALID_IMAGE]
297 = T("Tried to select an image that does not exist in the WIM"),
298 [WIMLIB_ERR_INVALID_INTEGRITY_TABLE]
299 = T("The WIM's integrity table is invalid"),
300 [WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY]
301 = T("An entry in the WIM's lookup table is invalid"),
302 [WIMLIB_ERR_INVALID_MULTIBYTE_STRING]
303 = T("A string was not valid in the current locale's character encoding"),
304 [WIMLIB_ERR_INVALID_OVERLAY]
305 = T("Conflicting files in overlay when creating a WIM image"),
306 [WIMLIB_ERR_INVALID_PARAM]
307 = T("An invalid parameter was given"),
308 [WIMLIB_ERR_INVALID_PART_NUMBER]
309 = T("The part number or total parts of the WIM is invalid"),
310 [WIMLIB_ERR_INVALID_REPARSE_DATA]
311 = T("The reparse data of a reparse point was invalid"),
312 [WIMLIB_ERR_INVALID_RESOURCE_HASH]
313 = T("The SHA1 message digest of a WIM resource did not match the expected value"),
314 [WIMLIB_ERR_INVALID_RESOURCE_SIZE]
315 = T("A resource entry in the WIM has an invalid size"),
316 [WIMLIB_ERR_INVALID_SECURITY_DATA]
317 = T("The table of security descriptors in the WIM is invalid"),
318 [WIMLIB_ERR_INVALID_UNMOUNT_MESSAGE]
319 = T("The version of wimlib that has mounted a WIM image is incompatible with the "
320 "version being used to unmount it"),
321 [WIMLIB_ERR_INVALID_UTF8_STRING]
322 = T("A string provided as input by the user was not a valid UTF-8 string"),
323 [WIMLIB_ERR_INVALID_UTF16_STRING]
324 = T("A string in a WIM dentry is not a valid UTF-16LE string"),
325 [WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE]
326 = T("libxml2 was unable to find a character encoding conversion handler "
329 = T("Failed to create a hard or symbolic link when extracting "
330 "a file from the WIM"),
332 = T("Failed to create a directory"),
334 = T("Failed to create or use a POSIX message queue"),
336 = T("Ran out of memory"),
338 = T("Expected a directory"),
339 [WIMLIB_ERR_NOT_A_WIM_FILE]
340 = T("The file did not begin with the magic characters that "
341 "identify a WIM file"),
342 [WIMLIB_ERR_NO_FILENAME]
343 = T("The WIM is not identified with a filename"),
345 = T("NTFS-3g encountered an error (check errno)"),
347 = T("Failed to open a file"),
349 = T("Failed to open a directory"),
351 = T("Could not read data from a file"),
352 [WIMLIB_ERR_READLINK]
353 = T("Could not read the target of a symbolic link"),
355 = T("Could not rename a file"),
356 [WIMLIB_ERR_REPARSE_POINT_FIXUP_FAILED]
357 = T("Unable to complete reparse point fixup"),
358 [WIMLIB_ERR_RESOURCE_ORDER]
359 = T("The components of the WIM were arranged in an unexpected order"),
360 [WIMLIB_ERR_SPECIAL_FILE]
361 = T("Encountered a special file that cannot be archived"),
362 [WIMLIB_ERR_SPLIT_INVALID]
363 = T("The WIM is part of an invalid split WIM"),
364 [WIMLIB_ERR_SPLIT_UNSUPPORTED]
365 = T("The WIM is part of a split WIM, which is not supported for this operation"),
367 = T("Could not read the metadata for a file or directory"),
369 = T("Timed out while waiting for a message to arrive from another process"),
370 [WIMLIB_ERR_UNICODE_STRING_NOT_REPRESENTABLE]
371 = T("A Unicode string could not be represented in the current locale's encoding"),
372 [WIMLIB_ERR_UNKNOWN_VERSION]
373 = T("The WIM file is marked with an unknown version number"),
374 [WIMLIB_ERR_UNSUPPORTED]
375 = T("The requested operation is unsupported"),
376 [WIMLIB_ERR_VOLUME_LACKS_FEATURES]
377 = T("The volume did not support a feature necessary to complete the operation"),
379 = T("Failed to write data to a file"),
381 = T("The XML data of the WIM is invalid"),
384 WIMLIBAPI const tchar *
385 wimlib_get_error_string(enum wimlib_error_code code)
387 if (code < 0 || code >= ARRAY_LEN(error_strings))
390 return error_strings[code];
395 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
396 void *(*wimlib_malloc_func) (size_t) = malloc;
397 void (*wimlib_free_func) (void *) = free;
398 void *(*wimlib_realloc_func)(void *, size_t) = realloc;
401 wimlib_calloc(size_t nmemb, size_t size)
403 size_t total_size = nmemb * size;
404 void *p = MALLOC(total_size);
406 memset(p, 0, total_size);
411 wimlib_strdup(const char *str)
417 p = MALLOC(size + 1);
419 memcpy(p, str, size + 1);
425 wimlib_wcsdup(const wchar_t *str)
431 p = MALLOC((size + 1) * sizeof(wchar_t));
433 memcpy(p, str, (size + 1) * sizeof(wchar_t));
439 xml_set_memory_allocator(void *(*malloc_func)(size_t),
440 void (*free_func)(void *),
441 void *(*realloc_func)(void *, size_t));
445 wimlib_set_memory_allocator(void *(*malloc_func)(size_t),
446 void (*free_func)(void *),
447 void *(*realloc_func)(void *, size_t))
449 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
450 wimlib_malloc_func = malloc_func ? malloc_func : malloc;
451 wimlib_free_func = free_func ? free_func : free;
452 wimlib_realloc_func = realloc_func ? realloc_func : realloc;
454 xml_set_memory_allocator(wimlib_malloc_func, wimlib_free_func,
455 wimlib_realloc_func);
458 ERROR("Cannot set custom memory allocator functions:");
459 ERROR("wimlib was compiled with the --without-custom-memory-allocator "
461 return WIMLIB_ERR_UNSUPPORTED;
465 static bool seeded = false;
470 srand(time(NULL) * getpid());
474 /* Fills @n characters pointed to by @p with random alphanumeric characters. */
476 randomize_char_array_with_alnum(tchar p[], size_t n)
491 /* Fills @n bytes pointer to by @p with random numbers. */
493 randomize_byte_array(u8 *p, size_t n)
502 path_basename_with_len(const tchar *path, size_t len)
504 const tchar *p = &path[len] - 1;
506 /* Trailing slashes. */
515 while ((p != path - 1) && *p != T('/'))
521 /* Like the basename() function, but does not modify @path; it just returns a
524 path_basename(const tchar *path)
526 return path_basename_with_len(path, tstrlen(path));
530 * Returns a pointer to the part of @path following the first colon in the last
531 * path component, or NULL if the last path component does not contain a colon.
534 path_stream_name(const tchar *path)
536 const tchar *base = path_basename(path);
537 const tchar *stream_name = tstrchr(base, T(':'));
541 return stream_name + 1;
548 gettimeofday(&tv, NULL);
549 return timeval_to_wim_timestamp(tv);
553 wim_timestamp_to_str(u64 timestamp, tchar *buf, size_t len)
556 time_t t = wim_timestamp_to_unix(timestamp);
558 tstrftime(buf, len, T("%a %b %d %H:%M:%S %Y UTC"), &tm);
562 zap_backslashes(tchar *s)
565 while (*s != T('\0')) {
573 /* Like read(), but keep trying until everything has been written or we know for
574 * sure that there was an error (or end-of-file). */
576 full_read(int fd, void *buf, size_t count)
579 size_t bytes_remaining;
581 for (bytes_remaining = count;
582 bytes_remaining != 0;
583 bytes_remaining -= bytes_read, buf += bytes_read)
585 bytes_read = read(fd, buf, bytes_remaining);
586 if (bytes_read <= 0) {
589 else if (errno == EINTR)
594 return count - bytes_remaining;
597 /* Like write(), but keep trying until everything has been written or we know
598 * for sure that there was an error. */
600 full_write(int fd, const void *buf, size_t count)
602 ssize_t bytes_written;
603 size_t bytes_remaining;
605 for (bytes_remaining = count;
606 bytes_remaining != 0;
607 bytes_remaining -= bytes_written, buf += bytes_written)
609 bytes_written = write(fd, buf, bytes_remaining);
610 if (bytes_written < 0) {
616 return count - bytes_remaining;
619 /* Like pread(), but keep trying until everything has been read or we know for
620 * sure that there was an error (or end-of-file) */
622 full_pread(int fd, void *buf, size_t count, off_t offset)
625 size_t bytes_remaining;
627 for (bytes_remaining = count;
628 bytes_remaining != 0;
629 bytes_remaining -= bytes_read, buf += bytes_read,
630 offset += bytes_read)
632 bytes_read = pread(fd, buf, bytes_remaining, offset);
633 if (bytes_read <= 0) {
636 else if (errno == EINTR)
641 return count - bytes_remaining;
644 /* Like pwrite(), but keep trying until everything has been written or we know
645 * for sure that there was an error. */
647 full_pwrite(int fd, const void *buf, size_t count, off_t offset)
649 ssize_t bytes_written;
650 size_t bytes_remaining;
652 for (bytes_remaining = count;
653 bytes_remaining != 0;
654 bytes_remaining -= bytes_written, buf += bytes_written,
655 offset += bytes_written)
657 bytes_written = pwrite(fd, buf, bytes_remaining, offset);
658 if (bytes_written < 0) {
664 return count - bytes_remaining;
667 /* Like writev(), but keep trying until everything has been written or we know
668 * for sure that there was an error. */
670 full_writev(int fd, struct iovec *iov, int iovcnt)
672 size_t total_bytes_written = 0;
674 ssize_t bytes_written;
676 bytes_written = writev(fd, iov, iovcnt);
677 if (bytes_written < 0) {
682 total_bytes_written += bytes_written;
683 while (bytes_written) {
684 if (bytes_written >= iov[0].iov_len) {
685 bytes_written -= iov[0].iov_len;
689 iov[0].iov_base += bytes_written;
690 iov[0].iov_len -= bytes_written;
695 return total_bytes_written;
699 filedes_offset(int fd)
701 return lseek(fd, 0, SEEK_CUR);