Do not wait full streams for WIMLIB_PROGRESS_MSG_WRITE_STREAMS
[wimlib] / src / write.c
1 /*
2  * write.c
3  *
4  * Support for writing WIM files; write a WIM file, overwrite a WIM file, write
5  * compressed file resources, etc.
6  */
7
8 /*
9  * Copyright (C) 2012, 2013 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU General Public License as published by the Free
15  * Software Foundation; either version 3 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #  include "config.h"
29 #endif
30
31 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
32 /* On BSD, this should be included before "wimlib/list.h" so that "wimlib/list.h" can
33  * overwrite the LIST_HEAD macro. */
34 #  include <sys/file.h>
35 #endif
36
37 #include "wimlib/compress_chunks.h"
38 #include "wimlib/endianness.h"
39 #include "wimlib/error.h"
40 #include "wimlib/file_io.h"
41 #include "wimlib/header.h"
42 #include "wimlib/integrity.h"
43 #include "wimlib/lookup_table.h"
44 #include "wimlib/metadata.h"
45 #include "wimlib/resource.h"
46 #ifdef __WIN32__
47 #  include "wimlib/win32.h" /* win32_rename_replacement() */
48 #endif
49 #include "wimlib/write.h"
50 #include "wimlib/xml.h"
51
52 #include <errno.h>
53 #include <fcntl.h>
54 #include <stdlib.h>
55 #include <unistd.h>
56
57 #ifdef HAVE_ALLOCA_H
58 #  include <alloca.h>
59 #endif
60
61 static inline int
62 write_flags_to_resource_flags(int write_flags)
63 {
64         int write_resource_flags = 0;
65
66         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
67                 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS;
68         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
69                 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
70         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
71                 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS;
72         return write_resource_flags;
73 }
74
75 struct filter_context {
76         int write_flags;
77         WIMStruct *wim;
78 };
79
80 /* Determine specified stream should be filtered out from the write.
81  *
82  * Return values:
83  *
84  *  < 0 : The stream should be hard-filtered; that is, not included in the
85  *        output WIM at all.
86  *    0 : The stream should not be filtered out.
87  *  > 0 : The stream should be soft-filtered; that is, it already exists in the
88  *        WIM file and may not need to be written again.
89  */
90 static int
91 stream_filtered(const struct wim_lookup_table_entry *lte,
92                 const struct filter_context *ctx)
93 {
94         int write_flags = ctx->write_flags;
95         WIMStruct *wim = ctx->wim;
96
97         if (ctx == NULL)
98                 return 0;
99
100         if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE &&
101             lte->resource_location == RESOURCE_IN_WIM &&
102             lte->rspec->wim == wim)
103                 return 1;
104
105         if (write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS &&
106             lte->resource_location == RESOURCE_IN_WIM &&
107             lte->rspec->wim != wim)
108                 return -1;
109
110         return 0;
111 }
112
113 static bool
114 stream_hard_filtered(const struct wim_lookup_table_entry *lte,
115                      struct filter_context *ctx)
116 {
117         return stream_filtered(lte, ctx) < 0;
118 }
119
120 static inline int
121 may_soft_filter_streams(const struct filter_context *ctx)
122 {
123         if (ctx == NULL)
124                 return 0;
125         return ctx->write_flags & WIMLIB_WRITE_FLAG_OVERWRITE;
126 }
127
128 static inline int
129 may_hard_filter_streams(const struct filter_context *ctx)
130 {
131         if (ctx == NULL)
132                 return 0;
133         return ctx->write_flags & WIMLIB_WRITE_FLAG_SKIP_EXTERNAL_WIMS;
134 }
135
136 static inline int
137 may_filter_streams(const struct filter_context *ctx)
138 {
139         return (may_soft_filter_streams(ctx) ||
140                 may_hard_filter_streams(ctx));
141 }
142
143
144 /* Return true if the specified resource is compressed and the compressed data
145  * can be reused with the specified output parameters.  */
146 static bool
147 can_raw_copy(const struct wim_lookup_table_entry *lte,
148              int write_resource_flags, int out_ctype, u32 out_chunk_size)
149 {
150         const struct wim_resource_spec *rspec;
151
152         if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_RECOMPRESS)
153                 return false;
154
155         if (out_ctype == WIMLIB_COMPRESSION_TYPE_NONE)
156                 return false;
157
158         if (lte->resource_location != RESOURCE_IN_WIM)
159                 return false;
160
161         rspec = lte->rspec;
162
163         if (rspec->is_pipable != !!(write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE))
164                 return false;
165
166
167         if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
168                 /* Normal compressed resource: Must use same compression type
169                  * and chunk size.  */
170                 return (rspec->wim->compression_type == out_ctype &&
171                         rspec->wim->chunk_size == out_chunk_size);
172         }
173
174         if ((rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) &&
175             (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
176         {
177                 /* Packed resource: Such resources may contain multiple streams,
178                  * and in general only a subset of them need to be written.  As
179                  * a heuristic, re-use the raw data if at least half the
180                  * uncompressed size is being written.  */
181
182                 /* Note: packed resources contain a header that specifies the
183                  * compression type and chunk size; therefore we don't need to
184                  * check if they are compatible with @out_ctype and
185                  * @out_chunk_size.  */
186
187                 struct wim_lookup_table_entry *res_stream;
188                 u64 write_size = 0;
189
190                 list_for_each_entry(res_stream, &rspec->stream_list, rspec_node)
191                         if (res_stream->will_be_in_output_wim)
192                                 write_size += res_stream->size;
193
194                 return (write_size > rspec->uncompressed_size / 2);
195         }
196         return false;
197 }
198
199 static u8
200 filter_resource_flags(u8 flags)
201 {
202         return (flags & ~(WIM_RESHDR_FLAG_PACKED_STREAMS |
203                           WIM_RESHDR_FLAG_COMPRESSED |
204                           WIM_RESHDR_FLAG_SPANNED |
205                           WIM_RESHDR_FLAG_FREE));
206 }
207
208 static void
209 stream_set_out_reshdr_for_reuse(struct wim_lookup_table_entry *lte)
210 {
211         const struct wim_resource_spec *rspec;
212
213         wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
214         rspec = lte->rspec;
215
216         if (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
217
218                 wimlib_assert(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS);
219
220                 lte->out_reshdr.offset_in_wim = lte->offset_in_res;
221                 lte->out_reshdr.uncompressed_size = 0;
222                 lte->out_reshdr.size_in_wim = lte->size;
223
224                 lte->out_res_offset_in_wim = rspec->offset_in_wim;
225                 lte->out_res_size_in_wim = rspec->size_in_wim;
226                 /*lte->out_res_uncompressed_size = rspec->uncompressed_size;*/
227         } else {
228                 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
229
230                 lte->out_reshdr.offset_in_wim = rspec->offset_in_wim;
231                 lte->out_reshdr.uncompressed_size = rspec->uncompressed_size;
232                 lte->out_reshdr.size_in_wim = rspec->size_in_wim;
233         }
234         lte->out_reshdr.flags = lte->flags;
235 }
236
237
238 /* Write the header for a stream in a pipable WIM.  */
239 static int
240 write_pwm_stream_header(const struct wim_lookup_table_entry *lte,
241                         struct filedes *out_fd,
242                         int additional_reshdr_flags)
243 {
244         struct pwm_stream_hdr stream_hdr;
245         u32 reshdr_flags;
246         int ret;
247
248         stream_hdr.magic = cpu_to_le64(PWM_STREAM_MAGIC);
249         stream_hdr.uncompressed_size = cpu_to_le64(lte->size);
250         if (additional_reshdr_flags & PWM_RESHDR_FLAG_UNHASHED) {
251                 zero_out_hash(stream_hdr.hash);
252         } else {
253                 wimlib_assert(!lte->unhashed);
254                 copy_hash(stream_hdr.hash, lte->hash);
255         }
256
257         reshdr_flags = filter_resource_flags(lte->flags);
258         reshdr_flags |= additional_reshdr_flags;
259         stream_hdr.flags = cpu_to_le32(reshdr_flags);
260         ret = full_write(out_fd, &stream_hdr, sizeof(stream_hdr));
261         if (ret)
262                 ERROR_WITH_ERRNO("Write error");
263         return ret;
264 }
265
266 #if 0
267 static int
268 seek_and_truncate(struct filedes *out_fd, off_t offset)
269 {
270         if (filedes_seek(out_fd, offset) == -1 ||
271             ftruncate(out_fd->fd, offset))
272         {
273                 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
274                 return WIMLIB_ERR_WRITE;
275         }
276         return 0;
277 }
278 #endif
279
280 struct write_streams_progress_data {
281         wimlib_progress_func_t progress_func;
282         union wimlib_progress_info progress;
283         uint64_t next_progress;
284         WIMStruct *prev_wim_part;
285 };
286
287 static void
288 do_write_streams_progress(struct write_streams_progress_data *progress_data,
289                           u64 size,
290                           bool discarded,
291                           struct wim_lookup_table_entry *cur_stream)
292 {
293         union wimlib_progress_info *progress = &progress_data->progress;
294         bool new_wim_part;
295
296         if (discarded) {
297                 progress->write_streams.total_bytes -= size;
298                 if (progress_data->next_progress != ~(uint64_t)0 &&
299                     progress_data->next_progress > progress->write_streams.total_bytes)
300                 {
301                         progress_data->next_progress = progress->write_streams.total_bytes;
302                 }
303         } else {
304                 progress->write_streams.completed_bytes += size;
305         }
306         new_wim_part = false;
307         if (cur_stream->resource_location == RESOURCE_IN_WIM &&
308             cur_stream->rspec->wim != progress_data->prev_wim_part)
309         {
310                 if (progress_data->prev_wim_part) {
311                         new_wim_part = true;
312                         progress->write_streams.completed_parts++;
313                 }
314                 progress_data->prev_wim_part = cur_stream->rspec->wim;
315         }
316         progress->write_streams.completed_streams++;
317         if (progress_data->progress_func
318             && (progress->write_streams.completed_bytes >= progress_data->next_progress
319                 || new_wim_part))
320         {
321                 progress_data->progress_func(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
322                                              progress);
323                 if (progress_data->next_progress == progress->write_streams.total_bytes) {
324                         progress_data->next_progress = ~(uint64_t)0;
325                 } else {
326                         progress_data->next_progress =
327                                 min(progress->write_streams.total_bytes,
328                                     progress->write_streams.completed_bytes +
329                                         progress->write_streams.total_bytes / 100);
330                 }
331         }
332 }
333
334 struct write_streams_ctx {
335         /* File descriptor the streams are being written to.  */
336         struct filedes *out_fd;
337
338         /* Lookup table for the WIMStruct on whose behalf the streams are being
339          * written.  */
340         struct wim_lookup_table *lookup_table;
341
342         /* Compression format to use.  */
343         int out_ctype;
344
345         /* Maximum uncompressed chunk size in compressed resources to use.  */
346         u32 out_chunk_size;
347
348         /* Flags that affect how the streams will be written.  */
349         int write_resource_flags;
350
351         /* Data used for issuing WRITE_STREAMS progress.  */
352         struct write_streams_progress_data progress_data;
353
354         struct filter_context *filter_ctx;
355
356         /* Upper bound on the total number of bytes that need to be compressed.
357          * */
358         u64 num_bytes_to_compress;
359
360         /* Pointer to the chunk_compressor implementation being used for
361          * compressing chunks of data, or NULL if chunks are being written
362          * uncompressed.  */
363         struct chunk_compressor *compressor;
364
365         /* Buffer for dividing the read data into chunks of size
366          * @out_chunk_size.  */
367         u8 *chunk_buf;
368
369         /* Number of bytes in @chunk_buf that are currently filled.  */
370         size_t chunk_buf_filled;
371
372         /* List of streams that currently have chunks being compressed.  */
373         struct list_head pending_streams;
374
375         /* Set to true if the stream currently being read was a duplicate, and
376          * therefore the corresponding stream entry needs to be freed once the
377          * read finishes.  (In this case we add the duplicate entry to
378          * pending_streams rather than the entry being read.)  */
379         bool stream_was_duplicate;
380
381         /* Current uncompressed offset in the resource being read.  */
382         u64 cur_read_res_offset;
383
384         /* Uncompressed size of the resource currently being read.  */
385         u64 cur_read_res_size;
386
387         /* Current uncompressed offset in the resource being written.  */
388         u64 cur_write_res_offset;
389
390         /* Uncompressed size of resource currently being written.  */
391         u64 cur_write_res_size;
392
393         /* Array that is filled in with compressed chunk sizes as a resource is
394          * being written.  */
395         u64 *chunk_csizes;
396
397         /* Index of next entry in @chunk_csizes to fill in.  */
398         size_t chunk_index;
399
400         /* Number of entries in @chunk_csizes currently allocated.  */
401         size_t num_alloc_chunks;
402
403         /* Offset in the output file of the start of the chunks of the resource
404          * currently being written.  */
405         u64 chunks_start_offset;
406 };
407
408 static u64
409 get_chunk_entry_size(u64 res_size, int write_resource_flags)
410 {
411         if (res_size <= UINT32_MAX ||
412             (write_resource_flags & WIM_RESHDR_FLAG_PACKED_STREAMS))
413                 return 4;
414         else
415                 return 8;
416 }
417
418 /* Reserve space for the chunk table and prepare to accumulate the chunk table
419  * in memory.  */
420 static int
421 begin_chunk_table(struct write_streams_ctx *ctx, u64 res_expected_size)
422 {
423         u64 expected_num_chunks;
424         u64 expected_num_chunk_entries;
425         size_t reserve_size;
426         int ret;
427
428         /* Calculate the number of chunks and chunk entries that should be
429          * needed for the resource.  These normally will be the final values,
430          * but in PACKED_STREAMS mode some of the streams we're planning to
431          * write into the resource may be duplicates, and therefore discarded,
432          * potentially decreasing the number of chunk entries needed.  */
433         expected_num_chunks = DIV_ROUND_UP(res_expected_size, ctx->out_chunk_size);
434         expected_num_chunk_entries = expected_num_chunks;
435         if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
436                 expected_num_chunk_entries--;
437
438         /* Make sure the chunk_csizes array is long enough to store the
439          * compressed size of each chunk.  */
440         if (expected_num_chunks > ctx->num_alloc_chunks) {
441                 u64 new_length = expected_num_chunks + 50;
442
443                 if ((size_t)new_length != new_length) {
444                         ERROR("Resource size too large (%"PRIu64" bytes!",
445                               res_expected_size);
446                         return WIMLIB_ERR_NOMEM;
447                 }
448
449                 FREE(ctx->chunk_csizes);
450                 ctx->chunk_csizes = MALLOC(new_length * sizeof(ctx->chunk_csizes[0]));
451                 if (ctx->chunk_csizes == NULL) {
452                         ctx->num_alloc_chunks = 0;
453                         return WIMLIB_ERR_NOMEM;
454                 }
455                 ctx->num_alloc_chunks = new_length;
456         }
457
458         ctx->chunk_index = 0;
459
460         if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE)) {
461                 /* Reserve space for the chunk table in the output file.  In the
462                  * case of packed resources this reserves the upper bound for
463                  * the needed space, not necessarily the exact space which will
464                  * prove to be needed.  At this point, we just use @chunk_csizes
465                  * for a buffer of 0's because the actual compressed chunk sizes
466                  * are unknown.  */
467                 reserve_size = expected_num_chunk_entries *
468                                get_chunk_entry_size(res_expected_size,
469                                                     ctx->write_resource_flags);
470                 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS)
471                         reserve_size += sizeof(struct alt_chunk_table_header_disk);
472                 memset(ctx->chunk_csizes, 0, reserve_size);
473                 ret = full_write(ctx->out_fd, ctx->chunk_csizes, reserve_size);
474                 if (ret)
475                         return ret;
476         }
477         return 0;
478 }
479
480 static int
481 begin_write_resource(struct write_streams_ctx *ctx, u64 res_expected_size)
482 {
483         int ret;
484
485         wimlib_assert(res_expected_size != 0);
486
487         if (ctx->compressor != NULL) {
488                 ret = begin_chunk_table(ctx, res_expected_size);
489                 if (ret)
490                         return ret;
491         }
492
493         /* Output file descriptor is now positioned at the offset at which to
494          * write the first chunk of the resource.  */
495         ctx->chunks_start_offset = ctx->out_fd->offset;
496         ctx->cur_write_res_offset = 0;
497         ctx->cur_write_res_size = res_expected_size;
498         return 0;
499 }
500
501 static int
502 end_chunk_table(struct write_streams_ctx *ctx, u64 res_actual_size,
503                 u64 *res_start_offset_ret, u64 *res_store_size_ret)
504 {
505         size_t actual_num_chunks;
506         size_t actual_num_chunk_entries;
507         size_t chunk_entry_size;
508         int ret;
509
510         actual_num_chunks = ctx->chunk_index;
511         actual_num_chunk_entries = actual_num_chunks;
512         if (!(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
513                 actual_num_chunk_entries--;
514
515         chunk_entry_size = get_chunk_entry_size(res_actual_size,
516                                                 ctx->write_resource_flags);
517
518         typedef le64 __attribute__((may_alias)) aliased_le64_t;
519         typedef le32 __attribute__((may_alias)) aliased_le32_t;
520
521         if (chunk_entry_size == 4) {
522                 aliased_le32_t *entries = (aliased_le32_t*)ctx->chunk_csizes;
523
524                 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
525                         for (size_t i = 0; i < actual_num_chunk_entries; i++)
526                                 entries[i] = cpu_to_le32(ctx->chunk_csizes[i]);
527                 } else {
528                         u32 offset = ctx->chunk_csizes[0];
529                         for (size_t i = 0; i < actual_num_chunk_entries; i++) {
530                                 u32 next_size = ctx->chunk_csizes[i + 1];
531                                 entries[i] = cpu_to_le32(offset);
532                                 offset += next_size;
533                         }
534                 }
535         } else {
536                 aliased_le64_t *entries = (aliased_le64_t*)ctx->chunk_csizes;
537
538                 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
539                         for (size_t i = 0; i < actual_num_chunk_entries; i++)
540                                 entries[i] = cpu_to_le64(ctx->chunk_csizes[i]);
541                 } else {
542                         u64 offset = ctx->chunk_csizes[0];
543                         for (size_t i = 0; i < actual_num_chunk_entries; i++) {
544                                 u64 next_size = ctx->chunk_csizes[i + 1];
545                                 entries[i] = cpu_to_le64(offset);
546                                 offset += next_size;
547                         }
548                 }
549         }
550
551         size_t chunk_table_size = actual_num_chunk_entries * chunk_entry_size;
552         u64 res_start_offset;
553         u64 res_end_offset;
554
555         if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
556                 ret = full_write(ctx->out_fd, ctx->chunk_csizes, chunk_table_size);
557                 if (ret)
558                         goto error;
559                 res_end_offset = ctx->out_fd->offset;
560                 res_start_offset = ctx->chunks_start_offset;
561         } else {
562                 res_end_offset = ctx->out_fd->offset;
563
564                 u64 chunk_table_offset;
565
566                 chunk_table_offset = ctx->chunks_start_offset - chunk_table_size;
567
568                 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
569                         struct alt_chunk_table_header_disk hdr;
570
571                         hdr.res_usize = cpu_to_le64(res_actual_size);
572                         hdr.chunk_size = cpu_to_le32(ctx->out_chunk_size);
573                         hdr.compression_format = cpu_to_le32(ctx->out_ctype);
574
575                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
576                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
577                         BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
578
579                         ret = full_pwrite(ctx->out_fd, &hdr, sizeof(hdr),
580                                           chunk_table_offset - sizeof(hdr));
581                         if (ret)
582                                 goto error;
583                         res_start_offset = chunk_table_offset - sizeof(hdr);
584                 } else {
585                         res_start_offset = chunk_table_offset;
586                 }
587
588                 ret = full_pwrite(ctx->out_fd, ctx->chunk_csizes,
589                                   chunk_table_size, chunk_table_offset);
590                 if (ret)
591                         goto error;
592         }
593
594         *res_start_offset_ret = res_start_offset;
595         *res_store_size_ret = res_end_offset - res_start_offset;
596
597         return 0;
598
599 error:
600         ERROR_WITH_ERRNO("Write error");
601         return ret;
602 }
603
604 /* Finish writing a WIM resource by writing or updating the chunk table (if not
605  * writing the data uncompressed) and loading its metadata into @out_reshdr.  */
606 static int
607 end_write_resource(struct write_streams_ctx *ctx, struct wim_reshdr *out_reshdr)
608 {
609         int ret;
610         u64 res_size_in_wim;
611         u64 res_uncompressed_size;
612         u64 res_offset_in_wim;
613
614         wimlib_assert(ctx->cur_write_res_size == ctx->cur_write_res_offset);
615         res_uncompressed_size = ctx->cur_write_res_size;
616
617         if (ctx->compressor) {
618                 ret = end_chunk_table(ctx, res_uncompressed_size,
619                                       &res_offset_in_wim, &res_size_in_wim);
620                 if (ret)
621                         return ret;
622         } else {
623                 res_offset_in_wim = ctx->chunks_start_offset;
624                 res_size_in_wim = ctx->out_fd->offset - res_offset_in_wim;
625         }
626         out_reshdr->uncompressed_size = res_uncompressed_size;
627         out_reshdr->size_in_wim = res_size_in_wim;
628         out_reshdr->offset_in_wim = res_offset_in_wim;
629         DEBUG("Finished writing resource: %"PRIu64" => %"PRIu64" @ %"PRIu64"",
630               res_uncompressed_size, res_size_in_wim, res_offset_in_wim);
631         return 0;
632 }
633
634 /* Begin processing a stream for writing.  */
635 static int
636 write_stream_begin_read(struct wim_lookup_table_entry *lte,
637                         bool is_partial_res, void *_ctx)
638 {
639         struct write_streams_ctx *ctx = _ctx;
640         int ret;
641
642         wimlib_assert(lte->size > 0);
643
644         ctx->cur_read_res_offset = 0;
645         ctx->cur_read_res_size = lte->size;
646
647         /* As an optimization, we allow some streams to be "unhashed", meaning
648          * their SHA1 message digests are unknown.  This is the case with
649          * streams that are added by scanning a directry tree with
650          * wimlib_add_image(), for example.  Since WIM uses single-instance
651          * streams, we don't know whether such each such stream really need to
652          * written until it is actually checksummed, unless it has a unique
653          * size.  In such cases we read and checksum the stream in this
654          * function, thereby advancing ahead of read_stream_list(), which will
655          * still provide the data again to write_stream_process_chunk().  This
656          * is okay because an unhashed stream cannot be in a WIM resource, which
657          * might be costly to decompress.  */
658         ctx->stream_was_duplicate = false;
659         if (ctx->lookup_table != NULL && lte->unhashed && !lte->unique_size) {
660
661                 wimlib_assert(!is_partial_res);
662
663                 struct wim_lookup_table_entry *lte_new;
664
665                 ret = hash_unhashed_stream(lte, ctx->lookup_table, &lte_new);
666                 if (ret)
667                         return ret;
668                 if (lte_new != lte) {
669                         /* Duplicate stream detected.  */
670
671                         if (lte_new->will_be_in_output_wim ||
672                             stream_filtered(lte_new, ctx->filter_ctx))
673                         {
674                                 /* The duplicate stream is already being
675                                  * included in the output WIM, or it would be
676                                  * filtered out if it had been.  Skip writing
677                                  * this stream (and reading it again) entirely,
678                                  * passing its output reference count to the
679                                  * duplicate stream in the former case.  */
680                                 DEBUG("Discarding duplicate stream of "
681                                       "length %"PRIu64, lte->size);
682                                 do_write_streams_progress(&ctx->progress_data,
683                                                           lte->size, true, lte);
684                                 list_del(&lte->write_streams_list);
685                                 list_del(&lte->lookup_table_list);
686                                 if (lte_new->will_be_in_output_wim)
687                                         lte_new->out_refcnt += lte->out_refcnt;
688                                 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS)
689                                         ctx->cur_write_res_size -= lte->size;
690                                 free_lookup_table_entry(lte);
691                                 return BEGIN_STREAM_STATUS_SKIP_STREAM;
692                         } else {
693                                 /* The duplicate stream can validly be written,
694                                  * but was not marked as such.  Discard the
695                                  * current stream entry and use the duplicate,
696                                  * but actually freeing the current entry must
697                                  * wait until read_stream_list() has finished
698                                  * reading its data.  */
699                                 DEBUG("Stream duplicate, but not already "
700                                       "selected for writing.");
701                                 list_replace(&lte->write_streams_list,
702                                              &lte_new->write_streams_list);
703                                 list_replace(&lte->lookup_table_list,
704                                              &lte_new->lookup_table_list);
705                                 lte_new->out_refcnt = lte->out_refcnt;
706                                 lte_new->will_be_in_output_wim = 1;
707                                 ctx->stream_was_duplicate = true;
708                                 lte = lte_new;
709                         }
710                 }
711         }
712         list_move_tail(&lte->write_streams_list, &ctx->pending_streams);
713         return 0;
714 }
715
716 /* Write the next chunk of (typically compressed) data to the output WIM,
717  * handling the writing of the chunk table.  */
718 static int
719 write_chunk(struct write_streams_ctx *ctx, const void *cchunk,
720             size_t csize, size_t usize)
721 {
722         int ret;
723
724         struct wim_lookup_table_entry *lte;
725
726         lte = list_entry(ctx->pending_streams.next,
727                          struct wim_lookup_table_entry, write_streams_list);
728
729         if (ctx->cur_write_res_offset == 0 &&
730             !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
731         {
732                 /* Starting to write a new stream in non-packed mode.  */
733
734                 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
735                         int additional_reshdr_flags = 0;
736                         if (ctx->compressor != NULL)
737                                 additional_reshdr_flags |= WIM_RESHDR_FLAG_COMPRESSED;
738
739                         DEBUG("Writing pipable WIM stream header "
740                               "(offset=%"PRIu64")", ctx->out_fd->offset);
741
742                         ret = write_pwm_stream_header(lte, ctx->out_fd,
743                                                       additional_reshdr_flags);
744                         if (ret)
745                                 return ret;
746                 }
747
748                 ret = begin_write_resource(ctx, lte->size);
749                 if (ret)
750                         return ret;
751         }
752
753         if (ctx->compressor != NULL) {
754                 /* Record the compresed chunk size.  */
755                 wimlib_assert(ctx->chunk_index < ctx->num_alloc_chunks);
756                 ctx->chunk_csizes[ctx->chunk_index++] = csize;
757
758                /* If writing a pipable WIM, before the chunk data write a chunk
759                 * header that provides the compressed chunk size.  */
760                 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
761                         struct pwm_chunk_hdr chunk_hdr = {
762                                 .compressed_size = cpu_to_le32(csize),
763                         };
764                         ret = full_write(ctx->out_fd, &chunk_hdr,
765                                          sizeof(chunk_hdr));
766                         if (ret)
767                                 goto error;
768                 }
769         }
770
771         /* Write the chunk data.  */
772         ret = full_write(ctx->out_fd, cchunk, csize);
773         if (ret)
774                 goto error;
775
776         ctx->cur_write_res_offset += usize;
777
778         do_write_streams_progress(&ctx->progress_data,
779                                   usize, false, lte);
780
781         if (ctx->cur_write_res_offset == ctx->cur_write_res_size &&
782             !(ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS))
783         {
784                 struct wim_lookup_table_entry *lte;
785
786                 lte = list_entry(ctx->pending_streams.next,
787                                  struct wim_lookup_table_entry, write_streams_list);
788                 wimlib_assert(ctx->cur_write_res_offset == lte->size);
789
790                 /* Finished writing a stream in non-packed mode.  */
791
792                 ret = end_write_resource(ctx, &lte->out_reshdr);
793                 if (ret)
794                         return ret;
795
796                 wimlib_assert(lte->out_reshdr.uncompressed_size == lte->size);
797
798                 lte->out_reshdr.flags = filter_resource_flags(lte->flags);
799                 if (ctx->compressor != NULL)
800                         lte->out_reshdr.flags |= WIM_RESHDR_FLAG_COMPRESSED;
801
802                 list_del(&lte->write_streams_list);
803                 ctx->cur_write_res_offset = 0;
804         }
805
806         return 0;
807
808 error:
809         ERROR_WITH_ERRNO("Write error");
810         return ret;
811 }
812
813 static int
814 submit_chunk_for_compression(struct write_streams_ctx *ctx,
815                              const void *chunk, size_t size)
816 {
817         /* While we are unable to submit the chunk for compression (due to too
818          * many chunks already outstanding), retrieve and write the next
819          * compressed chunk.  */
820         while (!ctx->compressor->submit_chunk(ctx->compressor, chunk, size)) {
821                 const void *cchunk;
822                 unsigned csize;
823                 unsigned usize;
824                 bool bret;
825                 int ret;
826
827                 bret = ctx->compressor->get_chunk(ctx->compressor,
828                                                   &cchunk, &csize, &usize);
829
830                 wimlib_assert(bret);
831
832                 ret = write_chunk(ctx, cchunk, csize, usize);
833                 if (ret)
834                         return ret;
835         }
836         return 0;
837 }
838
839 /* Process the next chunk of data to be written to a WIM resource.  */
840 static int
841 write_stream_process_chunk(const void *chunk, size_t size, void *_ctx)
842 {
843         struct write_streams_ctx *ctx = _ctx;
844         int ret;
845         const u8 *chunkptr, *chunkend;
846
847         wimlib_assert(size != 0);
848
849         if (ctx->compressor == NULL) {
850                 /* Write chunk uncompressed.  */
851                  ret = write_chunk(ctx, chunk, size, size);
852                  if (ret)
853                          return ret;
854                  ctx->cur_read_res_offset += size;
855                  return 0;
856         }
857
858         /* Submit the chunk for compression, but take into account that the
859          * @size the chunk was provided in may not correspond to the
860          * @out_chunk_size being used for compression.  */
861         chunkptr = chunk;
862         chunkend = chunkptr + size;
863         do {
864                 const u8 *resized_chunk;
865                 size_t needed_chunk_size;
866
867                 if (ctx->write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
868                         needed_chunk_size = ctx->out_chunk_size;
869                 } else {
870                         u64 res_bytes_remaining;
871
872                         res_bytes_remaining = ctx->cur_read_res_size -
873                                               ctx->cur_read_res_offset;
874                         needed_chunk_size = min(ctx->out_chunk_size,
875                                                 ctx->chunk_buf_filled +
876                                                         res_bytes_remaining);
877                 }
878
879                 if (ctx->chunk_buf_filled == 0 &&
880                     chunkend - chunkptr >= needed_chunk_size)
881                 {
882                         /* No intermediate buffering needed.  */
883                         resized_chunk = chunkptr;
884                         chunkptr += needed_chunk_size;
885                         ctx->cur_read_res_offset += needed_chunk_size;
886                 } else {
887                         /* Intermediate buffering needed.  */
888                         size_t bytes_consumed;
889
890                         bytes_consumed = min(chunkend - chunkptr,
891                                              needed_chunk_size - ctx->chunk_buf_filled);
892
893                         memcpy(&ctx->chunk_buf[ctx->chunk_buf_filled],
894                                chunkptr, bytes_consumed);
895
896                         resized_chunk = ctx->chunk_buf;
897
898                         chunkptr += bytes_consumed;
899                         ctx->cur_read_res_offset += bytes_consumed;
900                         ctx->chunk_buf_filled += bytes_consumed;
901                         if (ctx->chunk_buf_filled == needed_chunk_size) {
902                                 resized_chunk = ctx->chunk_buf;
903                                 ctx->chunk_buf_filled = 0;
904                         } else {
905                                 break;
906                         }
907
908                 }
909
910                 ret = submit_chunk_for_compression(ctx, resized_chunk,
911                                                    needed_chunk_size);
912                 if (ret)
913                         return ret;
914
915         } while (chunkptr != chunkend);
916         return 0;
917 }
918
919 /* Finish processing a stream for writing.  It may not have been completely
920  * written yet, as the chunk_compressor implementation may still have chunks
921  * buffered or being compressed.  */
922 static int
923 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
924 {
925         struct write_streams_ctx *ctx = _ctx;
926         if (status == 0)
927                 wimlib_assert(ctx->cur_read_res_offset == ctx->cur_read_res_size);
928         if (ctx->stream_was_duplicate) {
929                 free_lookup_table_entry(lte);
930         } else if (lte->unhashed && ctx->lookup_table != NULL) {
931                 list_del(&lte->unhashed_list);
932                 lookup_table_insert(ctx->lookup_table, lte);
933                 lte->unhashed = 0;
934         }
935         return status;
936 }
937
938 /* Compute statistics about a list of streams that will be written.
939  *
940  * Assumes the streams are sorted such that all streams located in each distinct
941  * WIM (specified by WIMStruct) are together.  */
942 static void
943 compute_stream_list_stats(struct list_head *stream_list,
944                           struct write_streams_ctx *ctx)
945 {
946         struct wim_lookup_table_entry *lte;
947         u64 total_bytes = 0;
948         u64 num_streams = 0;
949         u64 total_parts = 0;
950         WIMStruct *prev_wim_part = NULL;
951
952         list_for_each_entry(lte, stream_list, write_streams_list) {
953                 num_streams++;
954                 total_bytes += lte->size;
955                 if (lte->resource_location == RESOURCE_IN_WIM) {
956                         if (prev_wim_part != lte->rspec->wim) {
957                                 prev_wim_part = lte->rspec->wim;
958                                 total_parts++;
959                         }
960                 }
961         }
962         ctx->progress_data.progress.write_streams.total_bytes       = total_bytes;
963         ctx->progress_data.progress.write_streams.total_streams     = num_streams;
964         ctx->progress_data.progress.write_streams.completed_bytes   = 0;
965         ctx->progress_data.progress.write_streams.completed_streams = 0;
966         ctx->progress_data.progress.write_streams.compression_type  = ctx->out_ctype;
967         ctx->progress_data.progress.write_streams.total_parts       = total_parts;
968         ctx->progress_data.progress.write_streams.completed_parts   = 0;
969         ctx->progress_data.next_progress = 0;
970         ctx->progress_data.prev_wim_part = NULL;
971 }
972
973 /* Find streams in @stream_list that can be copied to the output WIM in raw form
974  * rather than compressed.  Delete these streams from @stream_list, and move one
975  * per resource to @raw_copy_resources.  Return the total uncompressed size of
976  * the streams that need to be compressed.  */
977 static u64
978 find_raw_copy_resources(struct list_head *stream_list,
979                         int write_resource_flags,
980                         int out_ctype,
981                         u32 out_chunk_size,
982                         struct list_head *raw_copy_resources)
983 {
984         struct wim_lookup_table_entry *lte, *tmp;
985         u64 num_bytes_to_compress = 0;
986
987         INIT_LIST_HEAD(raw_copy_resources);
988
989         /* Initialize temporary raw_copy_ok flag.  */
990         list_for_each_entry(lte, stream_list, write_streams_list)
991                 if (lte->resource_location == RESOURCE_IN_WIM)
992                         lte->rspec->raw_copy_ok = 0;
993
994         list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
995                 if (lte->resource_location == RESOURCE_IN_WIM &&
996                     lte->rspec->raw_copy_ok)
997                 {
998                         list_del(&lte->write_streams_list);
999                 } else if (can_raw_copy(lte, write_resource_flags,
1000                                  out_ctype, out_chunk_size))
1001                 {
1002                         lte->rspec->raw_copy_ok = 1;
1003                         list_move_tail(&lte->write_streams_list,
1004                                        raw_copy_resources);
1005                 } else {
1006                         num_bytes_to_compress += lte->size;
1007                 }
1008         }
1009
1010         return num_bytes_to_compress;
1011 }
1012
1013 /* Copy a raw compressed resource located in another WIM file to the WIM file
1014  * being written.  */
1015 static int
1016 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1017                         struct filedes *out_fd)
1018 {
1019         u64 cur_read_offset;
1020         u64 end_read_offset;
1021         u8 buf[BUFFER_SIZE];
1022         size_t bytes_to_read;
1023         int ret;
1024         struct filedes *in_fd;
1025         struct wim_lookup_table_entry *lte;
1026         u64 out_offset_in_wim;
1027
1028         DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1029               "uncompressed_size=%"PRIu64")",
1030               in_rspec->size_in_wim, in_rspec->uncompressed_size);
1031
1032         /* Copy the raw data.  */
1033         cur_read_offset = in_rspec->offset_in_wim;
1034         end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1035
1036         out_offset_in_wim = out_fd->offset;
1037
1038         if (in_rspec->is_pipable) {
1039                 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1040                         return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1041                 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1042                 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1043         }
1044         in_fd = &in_rspec->wim->in_fd;
1045         while (cur_read_offset != end_read_offset) {
1046
1047                 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1048
1049                 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1050                 if (ret)
1051                         return ret;
1052
1053                 ret = full_write(out_fd, buf, bytes_to_read);
1054                 if (ret)
1055                         return ret;
1056
1057                 cur_read_offset += bytes_to_read;
1058         }
1059
1060         list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1061                 if (lte->will_be_in_output_wim) {
1062                         stream_set_out_reshdr_for_reuse(lte);
1063                         if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1064                                 lte->out_res_offset_in_wim = out_offset_in_wim;
1065                         else
1066                                 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1067
1068                 }
1069         }
1070         return 0;
1071 }
1072
1073 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1074  * file being written.  */
1075 static int
1076 write_raw_copy_resources(struct list_head *raw_copy_resources,
1077                          struct filedes *out_fd)
1078 {
1079         struct wim_lookup_table_entry *lte;
1080         int ret;
1081
1082         list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1083                 ret = write_raw_copy_resource(lte->rspec, out_fd);
1084                 if (ret)
1085                         return ret;
1086         }
1087         return 0;
1088 }
1089
1090 /* Wait for and write all chunks pending in the compressor.  */
1091 static int
1092 finish_remaining_chunks(struct write_streams_ctx *ctx)
1093 {
1094         const void *cdata;
1095         unsigned csize;
1096         unsigned usize;
1097         int ret;
1098
1099         if (ctx->compressor == NULL)
1100                 return 0;
1101
1102         if (ctx->chunk_buf_filled != 0) {
1103                 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1104                                                    ctx->chunk_buf_filled);
1105                 if (ret)
1106                         return ret;
1107         }
1108
1109         while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1110                 ret = write_chunk(ctx, cdata, csize, usize);
1111                 if (ret)
1112                         return ret;
1113         }
1114         return 0;
1115 }
1116
1117 static void
1118 remove_zero_length_streams(struct list_head *stream_list)
1119 {
1120         struct wim_lookup_table_entry *lte, *tmp;
1121
1122         list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1123                 wimlib_assert(lte->will_be_in_output_wim);
1124                 if (lte->size == 0) {
1125                         list_del(&lte->write_streams_list);
1126                         lte->out_reshdr.offset_in_wim = 0;
1127                         lte->out_reshdr.size_in_wim = 0;
1128                         lte->out_reshdr.uncompressed_size = 0;
1129                         lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1130                 }
1131         }
1132 }
1133
1134 static int
1135 write_stream_list(struct list_head *stream_list,
1136                   struct filedes *out_fd,
1137                   int write_resource_flags,
1138                   int out_ctype,
1139                   u32 out_chunk_size,
1140                   unsigned num_threads,
1141                   struct wim_lookup_table *lookup_table,
1142                   struct filter_context *filter_ctx,
1143                   struct wimlib_lzx_context **comp_ctx,
1144                   wimlib_progress_func_t progress_func)
1145 {
1146         int ret;
1147         struct write_streams_ctx ctx;
1148         struct list_head raw_copy_resources;
1149
1150         remove_zero_length_streams(stream_list);
1151
1152         if (list_empty(stream_list)) {
1153                 DEBUG("No streams to write.");
1154                 return 0;
1155         }
1156
1157         memset(&ctx, 0, sizeof(ctx));
1158
1159         /* Pre-sorting the streams is required for compute_stream_list_stats().
1160          * Afterwards, read_stream_list() need not sort them again.  */
1161         ret = sort_stream_list_by_sequential_order(stream_list,
1162                                                    offsetof(struct wim_lookup_table_entry,
1163                                                             write_streams_list));
1164         if (ret)
1165                 return ret;
1166
1167         ctx.out_fd = out_fd;
1168         ctx.lookup_table = lookup_table;
1169         ctx.out_ctype = out_ctype;
1170         ctx.out_chunk_size = out_chunk_size;
1171         ctx.write_resource_flags = write_resource_flags;
1172         ctx.filter_ctx = filter_ctx;
1173
1174         if (out_chunk_size <= STACK_MAX) {
1175                 ctx.chunk_buf = alloca(out_chunk_size);
1176         } else {
1177                 ctx.chunk_buf = MALLOC(out_chunk_size);
1178                 if (ctx.chunk_buf == NULL) {
1179                         ret = WIMLIB_ERR_NOMEM;
1180                         goto out_destroy_context;
1181                 }
1182         }
1183         ctx.chunk_buf_filled = 0;
1184
1185         compute_stream_list_stats(stream_list, &ctx);
1186
1187         ctx.progress_data.progress_func = progress_func;
1188
1189         ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1190                                                             write_resource_flags,
1191                                                             out_ctype,
1192                                                             out_chunk_size,
1193                                                             &raw_copy_resources);
1194
1195         DEBUG("Writing stream list "
1196               "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1197               "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1198               "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1199               out_fd->offset, write_resource_flags,
1200               out_ctype, out_chunk_size, num_threads,
1201               ctx.progress_data.progress.write_streams.total_bytes,
1202               ctx.num_bytes_to_compress);
1203
1204         if (ctx.num_bytes_to_compress == 0) {
1205                 DEBUG("No compression needed; skipping to raw copy!");
1206                 goto out_write_raw_copy_resources;
1207         }
1208
1209         /* Unless uncompressed output was required, allocate a chunk_compressor
1210          * to do compression.  There are serial and parallel implementations of
1211          * the chunk_compressor interface.  We default to parallel using the
1212          * specified number of threads, unless the upper bound on the number
1213          * bytes needing to be compressed is less 2000000 (heuristic value).  */
1214         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1215
1216                 if (ctx.num_bytes_to_compress >= 2000000) {
1217                         ret = new_parallel_chunk_compressor(out_ctype,
1218                                                             out_chunk_size,
1219                                                             num_threads, 0,
1220                                                             &ctx.compressor);
1221                         if (ret) {
1222                                 DEBUG("Couldn't create parallel chunk compressor "
1223                                       "(status %d)", ret);
1224                         }
1225                 }
1226
1227                 if (ctx.compressor == NULL) {
1228                         if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1229                                 ret = wimlib_lzx_alloc_context(out_chunk_size,
1230                                                                NULL,
1231                                                                comp_ctx);
1232                                 if (ret)
1233                                         goto out_destroy_context;
1234                         }
1235                         ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1236                                                           *comp_ctx, &ctx.compressor);
1237                         if (ret)
1238                                 goto out_destroy_context;
1239                 }
1240         }
1241
1242         if (ctx.compressor)
1243                 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1244         else
1245                 ctx.progress_data.progress.write_streams.num_threads = 1;
1246
1247         DEBUG("Actually using %u threads",
1248               ctx.progress_data.progress.write_streams.num_threads);
1249
1250         INIT_LIST_HEAD(&ctx.pending_streams);
1251
1252         if (ctx.progress_data.progress_func) {
1253                 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1254                                                    &ctx.progress_data.progress);
1255         }
1256
1257         if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1258                 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1259                 if (ret)
1260                         goto out_destroy_context;
1261         }
1262
1263         /* Read the list of streams needing to be compressed, using the
1264          * specified callbacks to execute processing of the data.  */
1265
1266         struct read_stream_list_callbacks cbs = {
1267                 .begin_stream           = write_stream_begin_read,
1268                 .begin_stream_ctx       = &ctx,
1269                 .consume_chunk          = write_stream_process_chunk,
1270                 .consume_chunk_ctx      = &ctx,
1271                 .end_stream             = write_stream_end_read,
1272                 .end_stream_ctx         = &ctx,
1273         };
1274
1275         ret = read_stream_list(stream_list,
1276                                offsetof(struct wim_lookup_table_entry, write_streams_list),
1277                                &cbs,
1278                                STREAM_LIST_ALREADY_SORTED |
1279                                         VERIFY_STREAM_HASHES |
1280                                         COMPUTE_MISSING_STREAM_HASHES);
1281
1282         if (ret)
1283                 goto out_destroy_context;
1284
1285         ret = finish_remaining_chunks(&ctx);
1286         if (ret)
1287                 goto out_destroy_context;
1288
1289         if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1290                 struct wim_reshdr reshdr;
1291                 struct wim_lookup_table_entry *lte;
1292                 u64 offset_in_res;
1293
1294                 ret = end_write_resource(&ctx, &reshdr);
1295                 if (ret)
1296                         goto out_destroy_context;
1297
1298                 DEBUG("Ending packed resource: %lu %lu %lu.",
1299                       reshdr.offset_in_wim,
1300                       reshdr.size_in_wim,
1301                       reshdr.uncompressed_size);
1302
1303                 offset_in_res = 0;
1304                 list_for_each_entry(lte, &ctx.pending_streams, write_streams_list) {
1305                         lte->out_reshdr.size_in_wim = lte->size;
1306                         lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1307                         lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1308                         lte->out_reshdr.uncompressed_size = 0;
1309                         lte->out_reshdr.offset_in_wim = offset_in_res;
1310                         lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1311                         lte->out_res_size_in_wim = reshdr.size_in_wim;
1312                         /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1313                         offset_in_res += lte->size;
1314                 }
1315                 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1316         }
1317
1318 out_write_raw_copy_resources:
1319         /* Copy any compressed resources for which the raw data can be reused
1320          * without decompression.  */
1321         ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd);
1322
1323 out_destroy_context:
1324         if (out_chunk_size > STACK_MAX)
1325                 FREE(ctx.chunk_buf);
1326         FREE(ctx.chunk_csizes);
1327         if (ctx.compressor)
1328                 ctx.compressor->destroy(ctx.compressor);
1329         DEBUG("Done (ret=%d)", ret);
1330         return ret;
1331 }
1332
1333 static int
1334 write_wim_resource(struct wim_lookup_table_entry *lte,
1335                    struct filedes *out_fd,
1336                    int out_ctype,
1337                    u32 out_chunk_size,
1338                    int write_resource_flags,
1339                    struct wimlib_lzx_context **comp_ctx)
1340 {
1341         LIST_HEAD(stream_list);
1342         list_add(&lte->write_streams_list, &stream_list);
1343         lte->will_be_in_output_wim = 1;
1344         return write_stream_list(&stream_list,
1345                                  out_fd,
1346                                  write_resource_flags & ~WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS,
1347                                  out_ctype,
1348                                  out_chunk_size,
1349                                  1,
1350                                  NULL,
1351                                  NULL,
1352                                  comp_ctx,
1353                                  NULL);
1354 }
1355
1356 int
1357 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1358                                int reshdr_flags, struct filedes *out_fd,
1359                                int out_ctype,
1360                                u32 out_chunk_size,
1361                                struct wim_reshdr *out_reshdr,
1362                                u8 *hash,
1363                                int write_resource_flags,
1364                                struct wimlib_lzx_context **comp_ctx)
1365 {
1366         int ret;
1367         struct wim_lookup_table_entry *lte;
1368
1369         /* Set up a temporary lookup table entry to provide to
1370          * write_wim_resource().  */
1371
1372         lte = new_lookup_table_entry();
1373         if (lte == NULL)
1374                 return WIMLIB_ERR_NOMEM;
1375
1376         lte->resource_location  = RESOURCE_IN_ATTACHED_BUFFER;
1377         lte->attached_buffer    = (void*)buf;
1378         lte->size               = buf_size;
1379         lte->flags              = reshdr_flags;
1380
1381         if (write_resource_flags & WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE) {
1382                 sha1_buffer(buf, buf_size, lte->hash);
1383                 lte->unhashed = 0;
1384         } else {
1385                 lte->unhashed = 1;
1386         }
1387
1388         ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1389                                  write_resource_flags, comp_ctx);
1390         if (ret)
1391                 goto out_free_lte;
1392
1393         copy_reshdr(out_reshdr, &lte->out_reshdr);
1394
1395         if (hash)
1396                 copy_hash(hash, lte->hash);
1397         ret = 0;
1398 out_free_lte:
1399         lte->resource_location = RESOURCE_NONEXISTENT;
1400         free_lookup_table_entry(lte);
1401         return ret;
1402 }
1403
1404 struct stream_size_table {
1405         struct hlist_head *array;
1406         size_t num_entries;
1407         size_t capacity;
1408 };
1409
1410 static int
1411 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1412 {
1413         tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1414         if (tab->array == NULL)
1415                 return WIMLIB_ERR_NOMEM;
1416         tab->num_entries = 0;
1417         tab->capacity = capacity;
1418         return 0;
1419 }
1420
1421 static void
1422 destroy_stream_size_table(struct stream_size_table *tab)
1423 {
1424         FREE(tab->array);
1425 }
1426
1427 static int
1428 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1429 {
1430         struct stream_size_table *tab = _tab;
1431         size_t pos;
1432         struct wim_lookup_table_entry *same_size_lte;
1433         struct hlist_node *tmp;
1434
1435         pos = hash_u64(lte->size) % tab->capacity;
1436         lte->unique_size = 1;
1437         hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1438                 if (same_size_lte->size == lte->size) {
1439                         lte->unique_size = 0;
1440                         same_size_lte->unique_size = 0;
1441                         break;
1442                 }
1443         }
1444
1445         hlist_add_head(&lte->hash_list_2, &tab->array[pos]);
1446         tab->num_entries++;
1447         return 0;
1448 }
1449
1450 struct find_streams_ctx {
1451         WIMStruct *wim;
1452         int write_flags;
1453         struct list_head stream_list;
1454         struct stream_size_table stream_size_tab;
1455 };
1456
1457 static void
1458 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1459                            struct list_head *stream_list, u32 nref)
1460 {
1461         if (!lte->will_be_in_output_wim) {
1462                 lte->out_refcnt = 0;
1463                 list_add_tail(&lte->write_streams_list, stream_list);
1464                 lte->will_be_in_output_wim = 1;
1465         }
1466         lte->out_refcnt += nref;
1467 }
1468
1469 static int
1470 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1471                                  void *_stream_list)
1472 {
1473         struct list_head *stream_list = _stream_list;
1474         lte->will_be_in_output_wim = 0;
1475         reference_stream_for_write(lte, stream_list, lte->refcnt);
1476         return 0;
1477 }
1478
1479 static int
1480 inode_find_streams_to_reference(const struct wim_inode *inode,
1481                                 const struct wim_lookup_table *table,
1482                                 struct list_head *stream_list)
1483 {
1484         struct wim_lookup_table_entry *lte;
1485         unsigned i;
1486
1487         wimlib_assert(inode->i_nlink > 0);
1488
1489         for (i = 0; i <= inode->i_num_ads; i++) {
1490                 lte = inode_stream_lte(inode, i, table);
1491                 if (lte)
1492                         reference_stream_for_write(lte, stream_list,
1493                                                    inode->i_nlink);
1494                 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1495                         return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1496         }
1497         return 0;
1498 }
1499
1500 static int
1501 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1502 {
1503         lte->will_be_in_output_wim = 0;
1504         return 0;
1505 }
1506
1507 static int
1508 image_find_streams_to_reference(WIMStruct *wim)
1509 {
1510         struct wim_image_metadata *imd;
1511         struct wim_inode *inode;
1512         struct wim_lookup_table_entry *lte;
1513         struct list_head *stream_list;
1514         int ret;
1515
1516         imd = wim_get_current_image_metadata(wim);
1517
1518         image_for_each_unhashed_stream(lte, imd)
1519                 lte->will_be_in_output_wim = 0;
1520
1521         stream_list = wim->private;
1522         image_for_each_inode(inode, imd) {
1523                 ret = inode_find_streams_to_reference(inode,
1524                                                       wim->lookup_table,
1525                                                       stream_list);
1526                 if (ret)
1527                         return ret;
1528         }
1529         return 0;
1530 }
1531
1532 static int
1533 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1534                                                  int image,
1535                                                  int streams_ok,
1536                                                  struct list_head *stream_list_ret)
1537 {
1538         int ret;
1539
1540         INIT_LIST_HEAD(stream_list_ret);
1541
1542         if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1543                            (image == 1 && wim->hdr.image_count == 1)))
1544         {
1545                 /* Fast case:  Assume that all streams are being written and
1546                  * that the reference counts are correct.  */
1547                 struct wim_lookup_table_entry *lte;
1548                 struct wim_image_metadata *imd;
1549                 unsigned i;
1550
1551                 for_lookup_table_entry(wim->lookup_table,
1552                                        fully_reference_stream_for_write,
1553                                        stream_list_ret);
1554
1555                 for (i = 0; i < wim->hdr.image_count; i++) {
1556                         imd = wim->image_metadata[i];
1557                         image_for_each_unhashed_stream(lte, imd)
1558                                 fully_reference_stream_for_write(lte, stream_list_ret);
1559                 }
1560         } else {
1561                 /* Slow case:  Walk through the images being written and
1562                  * determine the streams referenced.  */
1563                 for_lookup_table_entry(wim->lookup_table,
1564                                        do_stream_set_not_in_output_wim, NULL);
1565                 wim->private = stream_list_ret;
1566                 ret = for_image(wim, image, image_find_streams_to_reference);
1567                 if (ret)
1568                         return ret;
1569         }
1570
1571         return 0;
1572 }
1573
1574 struct insert_other_if_hard_filtered_ctx {
1575         struct stream_size_table *tab;
1576         struct filter_context *filter_ctx;
1577 };
1578
1579 static int
1580 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1581 {
1582         struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1583
1584         if (!lte->will_be_in_output_wim &&
1585             stream_hard_filtered(lte, ctx->filter_ctx))
1586                 stream_size_table_insert(lte, ctx->tab);
1587         return 0;
1588 }
1589
1590 static int
1591 determine_stream_size_uniquity(struct list_head *stream_list,
1592                                struct wim_lookup_table *lt,
1593                                struct filter_context *filter_ctx)
1594 {
1595         int ret;
1596         struct stream_size_table tab;
1597         struct wim_lookup_table_entry *lte;
1598
1599         ret = init_stream_size_table(&tab, lt->capacity);
1600         if (ret)
1601                 return ret;
1602
1603         if (may_hard_filter_streams(filter_ctx)) {
1604                 struct insert_other_if_hard_filtered_ctx ctx = {
1605                         .tab = &tab,
1606                         .filter_ctx = filter_ctx,
1607                 };
1608                 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1609         }
1610
1611         list_for_each_entry(lte, stream_list, write_streams_list)
1612                 stream_size_table_insert(lte, &tab);
1613
1614         destroy_stream_size_table(&tab);
1615         return 0;
1616 }
1617
1618 static void
1619 filter_stream_list_for_write(struct list_head *stream_list,
1620                              struct filter_context *filter_ctx)
1621 {
1622         struct wim_lookup_table_entry *lte, *tmp;
1623
1624         list_for_each_entry_safe(lte, tmp,
1625                                  stream_list, write_streams_list)
1626         {
1627                 int status = stream_filtered(lte, filter_ctx);
1628
1629                 if (status == 0) {
1630                         /* Not filtered.  */
1631                         continue;
1632                 } else {
1633                         if (status > 0) {
1634                                 /* Soft filtered.  */
1635                         } else {
1636                                 /* Hard filtered.  */
1637                                 lte->will_be_in_output_wim = 0;
1638                                 list_del(&lte->lookup_table_list);
1639                         }
1640                         list_del(&lte->write_streams_list);
1641                 }
1642         }
1643 }
1644
1645 /*
1646  * prepare_stream_list_for_write() -
1647  *
1648  * Prepare the list of streams to write for writing a WIM containing the
1649  * specified image(s) with the specified write flags.
1650  *
1651  * @wim
1652  *      The WIMStruct on whose behalf the write is occurring.
1653  *
1654  * @image
1655  *      Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1656  *
1657  * @write_flags
1658  *      WIMLIB_WRITE_FLAG_* flags for the write operation:
1659  *
1660  *      STREAMS_OK:  For writes of all images, assume that all streams in the
1661  *      lookup table of @wim and the per-image lists of unhashed streams should
1662  *      be taken as-is, and image metadata should not be searched for
1663  *      references.  This does not exclude filtering with OVERWRITE and
1664  *      SKIP_EXTERNAL_WIMS, below.
1665  *
1666  *      OVERWRITE:  Streams already present in @wim shall not be returned in
1667  *      @stream_list_ret.
1668  *
1669  *      SKIP_EXTERNAL_WIMS:  Streams already present in a WIM file, but not
1670  *      @wim, shall be be returned in neither @stream_list_ret nor
1671  *      @lookup_table_list_ret.
1672  *
1673  * @stream_list_ret
1674  *      List of streams, linked by write_streams_list, that need to be written
1675  *      will be returned here.
1676  *
1677  *      Note that this function assumes that unhashed streams will be written;
1678  *      it does not take into account that they may become duplicates when
1679  *      actually hashed.
1680  *
1681  * @lookup_table_list_ret
1682  *      List of streams, linked by lookup_table_list, that need to be included
1683  *      in the WIM's lookup table will be returned here.  This will be a
1684  *      superset of the streams in @stream_list_ret.
1685  *
1686  *      This list will be a proper superset of @stream_list_ret if and only if
1687  *      WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1688  *      the streams that would otherwise need to be written were already located
1689  *      in the WIM file.
1690  *
1691  *      All streams in this list will have @out_refcnt set to the number of
1692  *      references to the stream in the output WIM.  If
1693  *      WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1694  *      may be as low as 0.
1695  *
1696  * @filter_ctx_ret
1697  *      A context for queries of stream filter status with stream_filtered() is
1698  *      returned in this location.
1699  *
1700  * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1701  * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1702  * lookup table of @wim not inserted into @lookup_table_list_ret.
1703  *
1704  * Still furthermore, @unique_size will be set to 1 on all stream entries in
1705  * @stream_list_ret that have unique size among all stream entries in
1706  * @stream_list_ret and among all stream entries in the lookup table of @wim
1707  * that are ineligible for being written due to filtering.
1708  *
1709  * Returns 0 on success; nonzero on read error, memory allocation error, or
1710  * otherwise.
1711  */
1712 static int
1713 prepare_stream_list_for_write(WIMStruct *wim, int image,
1714                               int write_flags,
1715                               struct list_head *stream_list_ret,
1716                               struct list_head *lookup_table_list_ret,
1717                               struct filter_context *filter_ctx_ret)
1718 {
1719         int ret;
1720         struct wim_lookup_table_entry *lte;
1721
1722         filter_ctx_ret->write_flags = write_flags;
1723         filter_ctx_ret->wim = wim;
1724
1725         ret = prepare_unfiltered_list_of_streams_in_output_wim(
1726                                 wim,
1727                                 image,
1728                                 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1729                                 stream_list_ret);
1730         if (ret)
1731                 return ret;
1732
1733         INIT_LIST_HEAD(lookup_table_list_ret);
1734         list_for_each_entry(lte, stream_list_ret, write_streams_list)
1735                 list_add_tail(&lte->lookup_table_list, lookup_table_list_ret);
1736
1737         ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1738                                              filter_ctx_ret);
1739         if (ret)
1740                 return ret;
1741
1742         if (may_filter_streams(filter_ctx_ret))
1743                 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1744
1745         return 0;
1746 }
1747
1748 static int
1749 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1750                   unsigned num_threads,
1751                   wimlib_progress_func_t progress_func,
1752                   struct list_head *stream_list_override,
1753                   struct list_head *lookup_table_list_ret)
1754 {
1755         int ret;
1756         struct list_head _stream_list;
1757         struct list_head *stream_list;
1758         struct wim_lookup_table_entry *lte;
1759         struct filter_context _filter_ctx;
1760         struct filter_context *filter_ctx;
1761
1762         if (stream_list_override == NULL) {
1763                 /* Normal case: prepare stream list from image(s) being written.
1764                  */
1765                 stream_list = &_stream_list;
1766                 filter_ctx = &_filter_ctx;
1767                 ret = prepare_stream_list_for_write(wim, image, write_flags,
1768                                                     stream_list,
1769                                                     lookup_table_list_ret,
1770                                                     filter_ctx);
1771                 if (ret)
1772                         return ret;
1773         } else {
1774                 /* Currently only as a result of wimlib_split() being called:
1775                  * use stream list already explicitly provided.  Use existing
1776                  * reference counts.  */
1777                 stream_list = stream_list_override;
1778                 filter_ctx = NULL;
1779                 INIT_LIST_HEAD(lookup_table_list_ret);
1780                 list_for_each_entry(lte, stream_list, write_streams_list) {
1781                         lte->out_refcnt = lte->refcnt;
1782                         lte->will_be_in_output_wim = 1;
1783                         lte->unique_size = 0;
1784                         list_add_tail(&lte->lookup_table_list, lookup_table_list_ret);
1785                 }
1786         }
1787
1788         return write_stream_list(stream_list,
1789                                  &wim->out_fd,
1790                                  write_flags_to_resource_flags(write_flags),
1791                                  wim->out_compression_type,
1792                                  wim->out_chunk_size,
1793                                  num_threads,
1794                                  wim->lookup_table,
1795                                  filter_ctx,
1796                                  &wim->lzx_context,
1797                                  progress_func);
1798 }
1799
1800 static int
1801 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
1802                              wimlib_progress_func_t progress_func)
1803 {
1804         int ret;
1805         int start_image;
1806         int end_image;
1807         int write_resource_flags;
1808
1809         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
1810                 DEBUG("Not writing any metadata resources.");
1811                 return 0;
1812         }
1813
1814         write_resource_flags = write_flags_to_resource_flags(write_flags);
1815
1816         write_resource_flags &= ~WIMLIB_WRITE_RESOURCE_FLAG_PACK_STREAMS;
1817
1818         DEBUG("Writing metadata resources (offset=%"PRIu64")",
1819               wim->out_fd.offset);
1820
1821         if (progress_func)
1822                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1823
1824         if (image == WIMLIB_ALL_IMAGES) {
1825                 start_image = 1;
1826                 end_image = wim->hdr.image_count;
1827         } else {
1828                 start_image = image;
1829                 end_image = image;
1830         }
1831
1832         for (int i = start_image; i <= end_image; i++) {
1833                 struct wim_image_metadata *imd;
1834
1835                 imd = wim->image_metadata[i - 1];
1836                 /* Build a new metadata resource only if image was modified from
1837                  * the original (or was newly added).  Otherwise just copy the
1838                  * existing one.  */
1839                 if (imd->modified) {
1840                         DEBUG("Image %u was modified; building and writing new "
1841                               "metadata resource", i);
1842                         ret = write_metadata_resource(wim, i,
1843                                                       write_resource_flags);
1844                 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
1845                         DEBUG("Image %u was not modified; re-using existing "
1846                               "metadata resource.", i);
1847                         stream_set_out_reshdr_for_reuse(imd->metadata_lte);
1848                         ret = 0;
1849                 } else {
1850                         DEBUG("Image %u was not modified; copying existing "
1851                               "metadata resource.", i);
1852                         ret = write_wim_resource(imd->metadata_lte,
1853                                                  &wim->out_fd,
1854                                                  wim->out_compression_type,
1855                                                  wim->out_chunk_size,
1856                                                  write_resource_flags,
1857                                                  &wim->lzx_context);
1858                 }
1859                 if (ret)
1860                         return ret;
1861         }
1862         if (progress_func)
1863                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
1864         return 0;
1865 }
1866
1867 static int
1868 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
1869 {
1870         int raw_fd;
1871         DEBUG("Opening \"%"TS"\" for writing.", path);
1872
1873         raw_fd = topen(path, open_flags | O_BINARY, 0644);
1874         if (raw_fd < 0) {
1875                 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
1876                 return WIMLIB_ERR_OPEN;
1877         }
1878         filedes_init(&wim->out_fd, raw_fd);
1879         return 0;
1880 }
1881
1882 static int
1883 close_wim_writable(WIMStruct *wim, int write_flags)
1884 {
1885         int ret = 0;
1886
1887         if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
1888                 DEBUG("Closing WIM file.");
1889                 if (filedes_valid(&wim->out_fd))
1890                         if (filedes_close(&wim->out_fd))
1891                                 ret = WIMLIB_ERR_WRITE;
1892         }
1893         filedes_invalidate(&wim->out_fd);
1894         return ret;
1895 }
1896
1897 static int
1898 cmp_streams_by_out_rspec(const void *p1, const void *p2)
1899 {
1900         const struct wim_lookup_table_entry *lte1, *lte2;
1901
1902         lte1 = *(const struct wim_lookup_table_entry**)p1;
1903         lte2 = *(const struct wim_lookup_table_entry**)p2;
1904
1905         if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1906                 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1907                         if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
1908                                 return cmp_u64(lte1->out_res_offset_in_wim,
1909                                                lte2->out_res_offset_in_wim);
1910                 } else {
1911                         return 1;
1912                 }
1913         } else {
1914                 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1915                         return -1;
1916         }
1917         return cmp_u64(lte1->out_reshdr.offset_in_wim,
1918                        lte2->out_reshdr.offset_in_wim);
1919 }
1920
1921 static int
1922 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
1923                        struct wim_reshdr *out_reshdr,
1924                        struct list_head *lookup_table_list)
1925 {
1926         int ret;
1927
1928         /* Set output resource metadata for streams already present in WIM.  */
1929         if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
1930                 struct wim_lookup_table_entry *lte;
1931                 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
1932                 {
1933                         if (lte->resource_location == RESOURCE_IN_WIM &&
1934                             lte->rspec->wim == wim)
1935                         {
1936                                 stream_set_out_reshdr_for_reuse(lte);
1937                         }
1938                 }
1939         }
1940
1941         ret = sort_stream_list(lookup_table_list,
1942                                offsetof(struct wim_lookup_table_entry, lookup_table_list),
1943                                cmp_streams_by_out_rspec);
1944         if (ret)
1945                 return ret;
1946
1947         /* Add entries for metadata resources.  */
1948         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
1949                 int start_image;
1950                 int end_image;
1951
1952                 if (image == WIMLIB_ALL_IMAGES) {
1953                         start_image = 1;
1954                         end_image = wim->hdr.image_count;
1955                 } else {
1956                         start_image = image;
1957                         end_image = image;
1958                 }
1959
1960                 /* Push metadata resource lookup table entries onto the front of
1961                  * the list in reverse order, so that they're written in order.
1962                  */
1963                 for (int i = end_image; i >= start_image; i--) {
1964                         struct wim_lookup_table_entry *metadata_lte;
1965
1966                         metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
1967                         wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
1968                         metadata_lte->out_refcnt = 1;
1969                         list_add(&metadata_lte->lookup_table_list, lookup_table_list);
1970                 }
1971         }
1972
1973         return write_wim_lookup_table_from_stream_list(lookup_table_list,
1974                                                        &wim->out_fd,
1975                                                        wim->hdr.part_number,
1976                                                        out_reshdr,
1977                                                        write_flags_to_resource_flags(write_flags),
1978                                                        &wim->lzx_context);
1979 }
1980
1981 /*
1982  * finish_write():
1983  *
1984  * Finish writing a WIM file: write the lookup table, xml data, and integrity
1985  * table, then overwrite the WIM header.  By default, closes the WIM file
1986  * descriptor (@wim->out_fd) if successful.
1987  *
1988  * write_flags is a bitwise OR of the following:
1989  *
1990  *      (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
1991  *              Include an integrity table.
1992  *
1993  *      (public) WIMLIB_WRITE_FLAG_FSYNC:
1994  *              fsync() the output file before closing it.
1995  *
1996  *      (public) WIMLIB_WRITE_FLAG_PIPABLE:
1997  *              Writing a pipable WIM, possibly to a pipe; include pipable WIM
1998  *              stream headers before the lookup table and XML data, and also
1999  *              write the WIM header at the end instead of seeking to the
2000  *              beginning.  Can't be combined with
2001  *              WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2002  *
2003  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2004  *              Don't write the lookup table.
2005  *
2006  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2007  *              When (if) writing the integrity table, re-use entries from the
2008  *              existing integrity table, if possible.
2009  *
2010  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2011  *              After writing the XML data but before writing the integrity
2012  *              table, write a temporary WIM header and flush the stream so that
2013  *              the WIM is less likely to become corrupted upon abrupt program
2014  *              termination.
2015  *      (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2016  *              Instead of overwriting the WIM header at the beginning of the
2017  *              file, simply append it to the end of the file.  (Used when
2018  *              writing to pipe.)
2019  *      (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2020  *              Do not close the file descriptor @wim->out_fd on either success
2021  *              on failure.
2022  *      (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2023  *              Use the existing <TOTALBYTES> stored in the in-memory XML
2024  *              information, rather than setting it to the offset of the XML
2025  *              data being written.
2026  */
2027 static int
2028 finish_write(WIMStruct *wim, int image, int write_flags,
2029              wimlib_progress_func_t progress_func,
2030              struct list_head *lookup_table_list)
2031 {
2032         int ret;
2033         off_t hdr_offset;
2034         int write_resource_flags;
2035         off_t old_lookup_table_end;
2036         off_t new_lookup_table_end;
2037         u64 xml_totalbytes;
2038
2039         DEBUG("image=%d, write_flags=%08x", image, write_flags);
2040
2041         write_resource_flags = write_flags_to_resource_flags(write_flags);
2042
2043         /* In the WIM header, there is room for the resource entry for a
2044          * metadata resource labeled as the "boot metadata".  This entry should
2045          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
2046          * it should be a copy of the resource entry for the image that is
2047          * marked as bootable.  This is not well documented...  */
2048         if (wim->hdr.boot_idx == 0) {
2049                 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2050         } else {
2051                 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2052                             &wim->image_metadata[
2053                                 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2054         }
2055
2056         /* Write lookup table.  (Save old position first.)  */
2057         old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2058                                wim->hdr.lookup_table_reshdr.size_in_wim;
2059         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2060                 ret = write_wim_lookup_table(wim, image, write_flags,
2061                                              &wim->hdr.lookup_table_reshdr,
2062                                              lookup_table_list);
2063                 if (ret)
2064                         return ret;
2065         }
2066
2067         /* Write XML data.  */
2068         xml_totalbytes = wim->out_fd.offset;
2069         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2070                 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2071         ret = write_wim_xml_data(wim, image, xml_totalbytes,
2072                                  &wim->hdr.xml_data_reshdr,
2073                                  write_resource_flags);
2074         if (ret)
2075                 return ret;
2076
2077         /* Write integrity table (optional).  */
2078         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2079                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2080                         struct wim_header checkpoint_hdr;
2081                         memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2082                         zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2083                         checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2084                         ret = write_wim_header_at_offset(&checkpoint_hdr,
2085                                                          &wim->out_fd, 0);
2086                         if (ret)
2087                                 return ret;
2088                 }
2089
2090                 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2091                         old_lookup_table_end = 0;
2092
2093                 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2094                                        wim->hdr.lookup_table_reshdr.size_in_wim;
2095
2096                 ret = write_integrity_table(wim,
2097                                             new_lookup_table_end,
2098                                             old_lookup_table_end,
2099                                             progress_func);
2100                 if (ret)
2101                         return ret;
2102         } else {
2103                 /* No integrity table.  */
2104                 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2105         }
2106
2107         /* Now that all information in the WIM header has been determined, the
2108          * preliminary header written earlier can be overwritten, the header of
2109          * the existing WIM file can be overwritten, or the final header can be
2110          * written to the end of the pipable WIM.  */
2111         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2112         hdr_offset = 0;
2113         if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2114                 hdr_offset = wim->out_fd.offset;
2115         DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2116         ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2117         if (ret)
2118                 return ret;
2119
2120         /* Possibly sync file data to disk before closing.  On POSIX systems, it
2121          * is necessary to do this before using rename() to overwrite an
2122          * existing file with a new file.  Otherwise, data loss would occur if
2123          * the system is abruptly terminated when the metadata for the rename
2124          * operation has been written to disk, but the new file data has not.
2125          */
2126         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2127                 DEBUG("Syncing WIM file.");
2128                 if (fsync(wim->out_fd.fd)) {
2129                         ERROR_WITH_ERRNO("Error syncing data to WIM file");
2130                         return WIMLIB_ERR_WRITE;
2131                 }
2132         }
2133
2134         if (close_wim_writable(wim, write_flags)) {
2135                 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2136                 return WIMLIB_ERR_WRITE;
2137         }
2138
2139         return 0;
2140 }
2141
2142 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2143 int
2144 lock_wim(WIMStruct *wim, int fd)
2145 {
2146         int ret = 0;
2147         if (fd != -1 && !wim->wim_locked) {
2148                 ret = flock(fd, LOCK_EX | LOCK_NB);
2149                 if (ret != 0) {
2150                         if (errno == EWOULDBLOCK) {
2151                                 ERROR("`%"TS"' is already being modified or has been "
2152                                       "mounted read-write\n"
2153                                       "        by another process!", wim->filename);
2154                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
2155                         } else {
2156                                 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2157                                                    wim->filename);
2158                                 ret = 0;
2159                         }
2160                 } else {
2161                         wim->wim_locked = 1;
2162                 }
2163         }
2164         return ret;
2165 }
2166 #endif
2167
2168 /*
2169  * write_pipable_wim():
2170  *
2171  * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2172  * capable of being applied from a pipe).
2173  *
2174  * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2175  * images can be applied from them sequentially when the file data is sent over
2176  * a pipe.  In addition, a pipable WIM can be written sequentially to a pipe.
2177  * The modifications made to the WIM format for pipable WIMs are:
2178  *
2179  * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2180  *   of "MSWIM\0\0\0".  This lets wimlib know that the WIM is pipable and also
2181  *   stops other software from trying to read the file as a normal WIM.
2182  *
2183  * - The header at the beginning of the file does not contain all the normal
2184  *   information; in particular it will have all 0's for the lookup table and
2185  *   XML data resource entries.  This is because this information cannot be
2186  *   determined until the lookup table and XML data have been written.
2187  *   Consequently, wimlib will write the full header at the very end of the
2188  *   file.  The header at the end, however, is only used when reading the WIM
2189  *   from a seekable file (not a pipe).
2190  *
2191  * - An extra copy of the XML data is placed directly after the header.  This
2192  *   allows image names and sizes to be determined at an appropriate time when
2193  *   reading the WIM from a pipe.  This copy of the XML data is ignored if the
2194  *   WIM is read from a seekable file (not a pipe).
2195  *
2196  * - The format of resources, or streams, has been modified to allow them to be
2197  *   used before the "lookup table" has been read.  Each stream is prefixed with
2198  *   a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2199  *   wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2200  *   uncompressed stream size, and flags that indicate whether the stream is
2201  *   compressed.  The data of uncompressed streams then follows literally, while
2202  *   the data of compressed streams follows in a modified format.  Compressed
2203  *   streams do not begin with a chunk table, since the chunk table cannot be
2204  *   written until all chunks have been compressed.  Instead, each compressed
2205  *   chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2206  *   Furthermore, the chunk table is written at the end of the resource instead
2207  *   of the start.  Note: chunk offsets are given in the chunk table as if the
2208  *   `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2209  *   used if the WIM is being read from a seekable file (not a pipe).
2210  *
2211  * - Metadata resources always come before other file resources (streams).
2212  *   (This does not by itself constitute an incompatibility with normal WIMs,
2213  *   since this is valid in normal WIMs.)
2214  *
2215  * - At least up to the end of the file resources, all components must be packed
2216  *   as tightly as possible; there cannot be any "holes" in the WIM.  (This does
2217  *   not by itself consititute an incompatibility with normal WIMs, since this
2218  *   is valid in normal WIMs.)
2219  *
2220  * Note: the lookup table, XML data, and header at the end are not used when
2221  * applying from a pipe.  They exist to support functionality such as image
2222  * application and export when the WIM is *not* read from a pipe.
2223  *
2224  *   Layout of pipable WIM:
2225  *
2226  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2227  * | Header | XML data | Metadata resources | File resources | Lookup table | XML data  | Header |
2228  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2229  *
2230  *   Layout of normal WIM:
2231  *
2232  * +--------+-----------------------------+-------------------------+
2233  * | Header | File and metadata resources | Lookup table | XML data |
2234  * +--------+-----------------------------+-------------------------+
2235  *
2236  * An optional integrity table can follow the final XML data in both normal and
2237  * pipable WIMs.  However, due to implementation details, wimlib currently can
2238  * only include an integrity table in a pipable WIM when writing it to a
2239  * seekable file (not a pipe).
2240  *
2241  * Do note that since pipable WIMs are not supported by Microsoft's software,
2242  * wimlib does not create them unless explicitly requested (with
2243  * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2244  * characters to identify the file.
2245  */
2246 static int
2247 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2248                   unsigned num_threads, wimlib_progress_func_t progress_func,
2249                   struct list_head *stream_list_override,
2250                   struct list_head *lookup_table_list_ret)
2251 {
2252         int ret;
2253         struct wim_reshdr xml_reshdr;
2254
2255         WARNING("Creating a pipable WIM, which will "
2256                 "be incompatible\n"
2257                 "          with Microsoft's software (wimgapi/imagex/Dism).");
2258
2259         /* At this point, the header at the beginning of the file has already
2260          * been written.  */
2261
2262         /* For efficiency, when wimlib adds an image to the WIM with
2263          * wimlib_add_image(), the SHA1 message digests of files is not
2264          * calculated; instead, they are calculated while the files are being
2265          * written.  However, this does not work when writing a pipable WIM,
2266          * since when writing a stream to a pipable WIM, its SHA1 message digest
2267          * needs to be known before the stream data is written.  Therefore,
2268          * before getting much farther, we need to pre-calculate the SHA1
2269          * message digests of all streams that will be written.  */
2270         ret = wim_checksum_unhashed_streams(wim);
2271         if (ret)
2272                 return ret;
2273
2274         /* Write extra copy of the XML data.  */
2275         ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2276                                  &xml_reshdr,
2277                                  WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE);
2278         if (ret)
2279                 return ret;
2280
2281         /* Write metadata resources for the image(s) being included in the
2282          * output WIM.  */
2283         ret = write_wim_metadata_resources(wim, image, write_flags,
2284                                            progress_func);
2285         if (ret)
2286                 return ret;
2287
2288         /* Write streams needed for the image(s) being included in the output
2289          * WIM, or streams needed for the split WIM part.  */
2290         return write_wim_streams(wim, image, write_flags, num_threads,
2291                                  progress_func, stream_list_override,
2292                                  lookup_table_list_ret);
2293
2294         /* The lookup table, XML data, and header at end are handled by
2295          * finish_write().  */
2296 }
2297
2298 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2299  * descriptor.  */
2300 int
2301 write_wim_part(WIMStruct *wim,
2302                const void *path_or_fd,
2303                int image,
2304                int write_flags,
2305                unsigned num_threads,
2306                wimlib_progress_func_t progress_func,
2307                unsigned part_number,
2308                unsigned total_parts,
2309                struct list_head *stream_list_override,
2310                const u8 *guid)
2311 {
2312         int ret;
2313         struct wim_header hdr_save;
2314         struct list_head lookup_table_list;
2315
2316         if (total_parts == 1)
2317                 DEBUG("Writing standalone WIM.");
2318         else
2319                 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2320         if (image == WIMLIB_ALL_IMAGES)
2321                 DEBUG("Including all images.");
2322         else
2323                 DEBUG("Including image %d only.", image);
2324         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2325                 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2326         else
2327                 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2328         DEBUG("Write flags: 0x%08x", write_flags);
2329
2330         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2331                 DEBUG("\tCHECK_INTEGRITY");
2332
2333         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2334                 DEBUG("\tREBUILD");
2335
2336         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2337                 DEBUG("\tRECOMPRESS");
2338
2339         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2340                 DEBUG("\tFSYNC");
2341
2342         if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2343                 DEBUG("\tFSYNC");
2344
2345         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2346                 DEBUG("\tIGNORE_READONLY_FLAG");
2347
2348         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2349                 DEBUG("\tPIPABLE");
2350
2351         if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2352                 DEBUG("\tNOT_PIPABLE");
2353
2354         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2355                 DEBUG("\tPACK_STREAMS");
2356
2357         if (write_flags & WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)
2358                 DEBUG("\tNO_PACK_STREAMS");
2359
2360         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2361                 DEBUG("\tFILE_DESCRIPTOR");
2362
2363         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2364                 DEBUG("\tNO_METADATA");
2365
2366         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2367                 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2368
2369         if (num_threads == 0)
2370                 DEBUG("Number of threads: autodetect");
2371         else
2372                 DEBUG("Number of threads: %u", num_threads);
2373         DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2374         DEBUG("Stream list:       %s", (stream_list_override ? "specified" : "autodetect"));
2375         DEBUG("GUID:              %s", ((guid || wim->guid_set_explicitly) ?
2376                                         "specified" : "generate new"));
2377
2378         /* Internally, this is always called with a valid part number and total
2379          * parts.  */
2380         wimlib_assert(total_parts >= 1);
2381         wimlib_assert(part_number >= 1 && part_number <= total_parts);
2382
2383         /* A valid image (or all images) must be specified.  */
2384         if (image != WIMLIB_ALL_IMAGES &&
2385              (image < 1 || image > wim->hdr.image_count))
2386                 return WIMLIB_ERR_INVALID_IMAGE;
2387
2388         /* If we need to write metadata resources, make sure the ::WIMStruct has
2389          * the needed information attached (e.g. is not a resource-only WIM,
2390          * such as a non-first part of a split WIM).  */
2391         if (!wim_has_metadata(wim) &&
2392             !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2393                 return WIMLIB_ERR_METADATA_NOT_FOUND;
2394
2395         /* Check for contradictory flags.  */
2396         if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2397                             WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2398                                 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2399                                     WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2400                 return WIMLIB_ERR_INVALID_PARAM;
2401
2402         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2403                             WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2404                                 == (WIMLIB_WRITE_FLAG_PIPABLE |
2405                                     WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2406                 return WIMLIB_ERR_INVALID_PARAM;
2407
2408         if ((write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2409                             WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2410                                 == (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2411                                     WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2412                 return WIMLIB_ERR_INVALID_PARAM;
2413
2414         /* Save previous header, then start initializing the new one.  */
2415         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2416
2417         /* Set default integrity, pipable, and packed stream flags.  */
2418         if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2419                              WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2420                 if (wim_is_pipable(wim)) {
2421                         DEBUG("WIM is pipable; default to PIPABLE.");
2422                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2423                 }
2424
2425         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2426                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2427                 if (wim_has_integrity_table(wim)) {
2428                         DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2429                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2430                 }
2431
2432         if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2433                              WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2434                 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS) {
2435                         DEBUG("WIM version 3584; default to PACK_STREAMS.");
2436                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2437                 }
2438
2439         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2440                             WIMLIB_WRITE_FLAG_PACK_STREAMS))
2441                                     == (WIMLIB_WRITE_FLAG_PIPABLE |
2442                                         WIMLIB_WRITE_FLAG_PACK_STREAMS))
2443                 return WIMLIB_ERR_INVALID_PARAM;
2444
2445         /* Set appropriate magic number.  */
2446         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2447                 wim->hdr.magic = PWM_MAGIC;
2448         else
2449                 wim->hdr.magic = WIM_MAGIC;
2450
2451         /* Set appropriate version number.  */
2452         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2453                 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2454         else
2455                 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2456
2457         /* Clear header flags that will be set automatically.  */
2458         wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY          |
2459                             WIM_HDR_FLAG_RESOURCE_ONLY          |
2460                             WIM_HDR_FLAG_SPANNED                |
2461                             WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2462
2463         /* Set SPANNED header flag if writing part of a split WIM.  */
2464         if (total_parts != 1)
2465                 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2466
2467         /* Set part number and total parts of split WIM.  This will be 1 and 1
2468          * if the WIM is standalone.  */
2469         wim->hdr.part_number = part_number;
2470         wim->hdr.total_parts = total_parts;
2471
2472         /* Set compression type if different.  */
2473         if (wim->compression_type != wim->out_compression_type) {
2474                 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2475                 wimlib_assert(ret == 0);
2476         }
2477
2478         /* Set chunk size if different.  */
2479         wim->hdr.chunk_size = wim->out_chunk_size;
2480
2481         /* Use GUID if specified; otherwise generate a new one.  */
2482         if (guid)
2483                 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2484         else if (!wim->guid_set_explicitly)
2485                 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2486
2487         /* Clear references to resources that have not been written yet.  */
2488         zero_reshdr(&wim->hdr.lookup_table_reshdr);
2489         zero_reshdr(&wim->hdr.xml_data_reshdr);
2490         zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2491         zero_reshdr(&wim->hdr.integrity_table_reshdr);
2492
2493         /* Set image count and boot index correctly for single image writes.  */
2494         if (image != WIMLIB_ALL_IMAGES) {
2495                 wim->hdr.image_count = 1;
2496                 if (wim->hdr.boot_idx == image)
2497                         wim->hdr.boot_idx = 1;
2498                 else
2499                         wim->hdr.boot_idx = 0;
2500         }
2501
2502         /* Split WIMs can't be bootable.  */
2503         if (total_parts != 1)
2504                 wim->hdr.boot_idx = 0;
2505
2506         /* Initialize output file descriptor.  */
2507         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2508                 /* File descriptor was explicitly provided.  Return error if
2509                  * file descriptor is not seekable, unless writing a pipable WIM
2510                  * was requested.  */
2511                 wim->out_fd.fd = *(const int*)path_or_fd;
2512                 wim->out_fd.offset = 0;
2513                 if (!filedes_is_seekable(&wim->out_fd)) {
2514                         ret = WIMLIB_ERR_INVALID_PARAM;
2515                         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2516                                 goto out_restore_hdr;
2517                         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2518                                 ERROR("Can't include integrity check when "
2519                                       "writing pipable WIM to pipe!");
2520                                 goto out_restore_hdr;
2521                         }
2522                 }
2523
2524         } else {
2525                 /* Filename of WIM to write was provided; open file descriptor
2526                  * to it.  */
2527                 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2528                                         O_TRUNC | O_CREAT | O_RDWR);
2529                 if (ret)
2530                         goto out_restore_hdr;
2531         }
2532
2533         /* Write initial header.  This is merely a "dummy" header since it
2534          * doesn't have all the information yet, so it will be overwritten later
2535          * (unless writing a pipable WIM).  */
2536         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2537                 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2538         ret = write_wim_header(&wim->hdr, &wim->out_fd);
2539         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2540         if (ret)
2541                 goto out_restore_hdr;
2542
2543         /* Write metadata resources and streams.  */
2544         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2545                 /* Default case: create a normal (non-pipable) WIM.  */
2546                 ret = write_wim_streams(wim, image, write_flags, num_threads,
2547                                         progress_func, stream_list_override,
2548                                         &lookup_table_list);
2549                 if (ret)
2550                         goto out_restore_hdr;
2551
2552                 ret = write_wim_metadata_resources(wim, image, write_flags,
2553                                                    progress_func);
2554                 if (ret)
2555                         goto out_restore_hdr;
2556         } else {
2557                 /* Non-default case: create pipable WIM.  */
2558                 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2559                                         progress_func, stream_list_override,
2560                                         &lookup_table_list);
2561                 if (ret)
2562                         goto out_restore_hdr;
2563                 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2564         }
2565
2566
2567         /* Write lookup table, XML data, and (optional) integrity table.  */
2568         ret = finish_write(wim, image, write_flags, progress_func,
2569                            &lookup_table_list);
2570 out_restore_hdr:
2571         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2572         (void)close_wim_writable(wim, write_flags);
2573         DEBUG("ret=%d", ret);
2574         return ret;
2575 }
2576
2577 /* Write a standalone WIM to a file or file descriptor.  */
2578 static int
2579 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2580                      int image, int write_flags, unsigned num_threads,
2581                      wimlib_progress_func_t progress_func)
2582 {
2583         return write_wim_part(wim, path_or_fd, image, write_flags,
2584                               num_threads, progress_func, 1, 1, NULL, NULL);
2585 }
2586
2587 /* API function documented in wimlib.h  */
2588 WIMLIBAPI int
2589 wimlib_write(WIMStruct *wim, const tchar *path,
2590              int image, int write_flags, unsigned num_threads,
2591              wimlib_progress_func_t progress_func)
2592 {
2593         if (!path)
2594                 return WIMLIB_ERR_INVALID_PARAM;
2595
2596         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2597
2598         return write_standalone_wim(wim, path, image, write_flags,
2599                                     num_threads, progress_func);
2600 }
2601
2602 /* API function documented in wimlib.h  */
2603 WIMLIBAPI int
2604 wimlib_write_to_fd(WIMStruct *wim, int fd,
2605                    int image, int write_flags, unsigned num_threads,
2606                    wimlib_progress_func_t progress_func)
2607 {
2608         if (fd < 0)
2609                 return WIMLIB_ERR_INVALID_PARAM;
2610
2611         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2612         write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2613
2614         return write_standalone_wim(wim, &fd, image, write_flags,
2615                                     num_threads, progress_func);
2616 }
2617
2618 static bool
2619 any_images_modified(WIMStruct *wim)
2620 {
2621         for (int i = 0; i < wim->hdr.image_count; i++)
2622                 if (wim->image_metadata[i]->modified)
2623                         return true;
2624         return false;
2625 }
2626
2627 static int
2628 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2629 {
2630         const WIMStruct *wim = _wim;
2631         off_t end_offset = *(const off_t*)wim->private;
2632
2633         if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2634             lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2635                 return WIMLIB_ERR_RESOURCE_ORDER;
2636         return 0;
2637 }
2638
2639 /* Make sure no file or metadata resources are located after the XML data (or
2640  * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2641  * place and we return WIMLIB_ERR_RESOURCE_ORDER.  */
2642 static int
2643 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2644 {
2645         int ret;
2646         unsigned i;
2647
2648         wim->private = &end_offset;
2649         ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2650         if (ret)
2651                 return ret;
2652
2653         for (i = 0; i < wim->hdr.image_count; i++) {
2654                 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2655                 if (ret)
2656                         return ret;
2657         }
2658         return 0;
2659 }
2660
2661 /*
2662  * Overwrite a WIM, possibly appending streams to it.
2663  *
2664  * A WIM looks like (or is supposed to look like) the following:
2665  *
2666  *                   Header (212 bytes)
2667  *                   Streams and metadata resources (variable size)
2668  *                   Lookup table (variable size)
2669  *                   XML data (variable size)
2670  *                   Integrity table (optional) (variable size)
2671  *
2672  * If we are not adding any streams or metadata resources, the lookup table is
2673  * unchanged--- so we only need to overwrite the XML data, integrity table, and
2674  * header.  This operation is potentially unsafe if the program is abruptly
2675  * terminated while the XML data or integrity table are being overwritten, but
2676  * before the new header has been written.  To partially alleviate this problem,
2677  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2678  * finish_write() to cause a temporary WIM header to be written after the XML
2679  * data has been written.  This may prevent the WIM from becoming corrupted if
2680  * the program is terminated while the integrity table is being calculated (but
2681  * no guarantees, due to write re-ordering...).
2682  *
2683  * If we are adding new streams or images (metadata resources), the lookup table
2684  * needs to be changed, and those streams need to be written.  In this case, we
2685  * try to perform a safe update of the WIM file by writing the streams *after*
2686  * the end of the previous WIM, then writing the new lookup table, XML data, and
2687  * (optionally) integrity table following the new streams.  This will produce a
2688  * layout like the following:
2689  *
2690  *                   Header (212 bytes)
2691  *                   (OLD) Streams and metadata resources (variable size)
2692  *                   (OLD) Lookup table (variable size)
2693  *                   (OLD) XML data (variable size)
2694  *                   (OLD) Integrity table (optional) (variable size)
2695  *                   (NEW) Streams and metadata resources (variable size)
2696  *                   (NEW) Lookup table (variable size)
2697  *                   (NEW) XML data (variable size)
2698  *                   (NEW) Integrity table (optional) (variable size)
2699  *
2700  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
2701  * the header is overwritten to point to the new lookup table, XML data, and
2702  * integrity table, to produce the following layout:
2703  *
2704  *                   Header (212 bytes)
2705  *                   Streams and metadata resources (variable size)
2706  *                   Nothing (variable size)
2707  *                   More Streams and metadata resources (variable size)
2708  *                   Lookup table (variable size)
2709  *                   XML data (variable size)
2710  *                   Integrity table (optional) (variable size)
2711  *
2712  * This method allows an image to be appended to a large WIM very quickly, and
2713  * is is crash-safe except in the case of write re-ordering, but the
2714  * disadvantage is that a small hole is left in the WIM where the old lookup
2715  * table, xml data, and integrity table were.  (These usually only take up a
2716  * small amount of space compared to the streams, however.)
2717  */
2718 static int
2719 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2720                       unsigned num_threads,
2721                       wimlib_progress_func_t progress_func)
2722 {
2723         int ret;
2724         off_t old_wim_end;
2725         u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2726         struct wim_header hdr_save;
2727         struct list_head stream_list;
2728         struct list_head lookup_table_list;
2729         struct filter_context filter_ctx;
2730
2731         DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2732
2733         /* Set default integrity flag.  */
2734         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2735                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2736                 if (wim_has_integrity_table(wim))
2737                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2738
2739         /* Set default packed flag.  */
2740         if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2741                              WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2742                 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
2743                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2744
2745         /* Set additional flags for overwrite.  */
2746         write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2747                        WIMLIB_WRITE_FLAG_STREAMS_OK;
2748
2749         /* Make sure that the integrity table (if present) is after the XML
2750          * data, and that there are no stream resources, metadata resources, or
2751          * lookup tables after the XML data.  Otherwise, these data would be
2752          * overwritten. */
2753         old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2754         old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2755         old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2756                                wim->hdr.lookup_table_reshdr.size_in_wim;
2757         if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2758             wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2759                 WARNING("Didn't expect the integrity table to be before the XML data");
2760                 return WIMLIB_ERR_RESOURCE_ORDER;
2761         }
2762
2763         if (old_lookup_table_end > old_xml_begin) {
2764                 WARNING("Didn't expect the lookup table to be after the XML data");
2765                 return WIMLIB_ERR_RESOURCE_ORDER;
2766         }
2767
2768         /* Set @old_wim_end, which indicates the point beyond which we don't
2769          * allow any file and metadata resources to appear without returning
2770          * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2771          * overwrite these resources). */
2772         if (!wim->deletion_occurred && !any_images_modified(wim)) {
2773                 /* If no images have been modified and no images have been
2774                  * deleted, a new lookup table does not need to be written.  We
2775                  * shall write the new XML data and optional integrity table
2776                  * immediately after the lookup table.  Note that this may
2777                  * overwrite an existing integrity table. */
2778                 DEBUG("Skipping writing lookup table "
2779                       "(no images modified or deleted)");
2780                 old_wim_end = old_lookup_table_end;
2781                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2782                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2783         } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2784                 /* Old WIM has an integrity table; begin writing new streams
2785                  * after it. */
2786                 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2787                               wim->hdr.integrity_table_reshdr.size_in_wim;
2788         } else {
2789                 /* No existing integrity table; begin writing new streams after
2790                  * the old XML data. */
2791                 old_wim_end = old_xml_end;
2792         }
2793
2794         ret = check_resource_offsets(wim, old_wim_end);
2795         if (ret)
2796                 return ret;
2797
2798         ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2799                                             &stream_list, &lookup_table_list,
2800                                             &filter_ctx);
2801         if (ret)
2802                 return ret;
2803
2804         ret = open_wim_writable(wim, wim->filename, O_RDWR);
2805         if (ret)
2806                 return ret;
2807
2808         ret = lock_wim(wim, wim->out_fd.fd);
2809         if (ret)
2810                 goto out_close_wim;
2811
2812         /* Save original header so it can be restored in case of error  */
2813         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2814
2815         /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2816         wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2817         ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2818         if (ret) {
2819                 ERROR_WITH_ERRNO("Error updating WIM header flags");
2820                 goto out_restore_memory_hdr;
2821         }
2822
2823         if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2824                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2825                 ret = WIMLIB_ERR_WRITE;
2826                 goto out_restore_physical_hdr;
2827         }
2828
2829         ret = write_stream_list(&stream_list,
2830                                 &wim->out_fd,
2831                                 write_flags_to_resource_flags(write_flags),
2832                                 wim->compression_type,
2833                                 wim->chunk_size,
2834                                 num_threads,
2835                                 wim->lookup_table,
2836                                 &filter_ctx,
2837                                 &wim->lzx_context,
2838                                 progress_func);
2839         if (ret)
2840                 goto out_truncate;
2841
2842         ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
2843                                            write_flags, progress_func);
2844         if (ret)
2845                 goto out_truncate;
2846
2847         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
2848         ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2849                            progress_func, &lookup_table_list);
2850         if (ret)
2851                 goto out_truncate;
2852
2853         goto out_unlock_wim;
2854
2855 out_truncate:
2856         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2857                 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
2858                         wim->filename, old_wim_end);
2859                 /* Return value of ftruncate() is ignored because this is
2860                  * already an error path.  */
2861                 (void)ftruncate(wim->out_fd.fd, old_wim_end);
2862         }
2863 out_restore_physical_hdr:
2864         (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
2865 out_restore_memory_hdr:
2866         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2867 out_close_wim:
2868         (void)close_wim_writable(wim, write_flags);
2869 out_unlock_wim:
2870         wim->wim_locked = 0;
2871         return ret;
2872 }
2873
2874 static int
2875 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
2876                           unsigned num_threads,
2877                           wimlib_progress_func_t progress_func)
2878 {
2879         size_t wim_name_len;
2880         int ret;
2881
2882         DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
2883
2884         /* Write the WIM to a temporary file in the same directory as the
2885          * original WIM. */
2886         wim_name_len = tstrlen(wim->filename);
2887         tchar tmpfile[wim_name_len + 10];
2888         tmemcpy(tmpfile, wim->filename, wim_name_len);
2889         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
2890         tmpfile[wim_name_len + 9] = T('\0');
2891
2892         ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
2893                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
2894                            num_threads, progress_func);
2895         if (ret) {
2896                 tunlink(tmpfile);
2897                 return ret;
2898         }
2899
2900         close_wim(wim);
2901
2902         /* Rename the new WIM file to the original WIM file.  Note: on Windows
2903          * this actually calls win32_rename_replacement(), not _wrename(), so
2904          * that removing the existing destination file can be handled.  */
2905         DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
2906         ret = trename(tmpfile, wim->filename);
2907         if (ret) {
2908                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
2909                                  tmpfile, wim->filename);
2910         #ifdef __WIN32__
2911                 if (ret < 0)
2912         #endif
2913                 {
2914                         tunlink(tmpfile);
2915                 }
2916                 return WIMLIB_ERR_RENAME;
2917         }
2918
2919         if (progress_func) {
2920                 union wimlib_progress_info progress;
2921                 progress.rename.from = tmpfile;
2922                 progress.rename.to = wim->filename;
2923                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
2924         }
2925         return 0;
2926 }
2927
2928 static bool
2929 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
2930 {
2931         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2932                 return false;
2933
2934         if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
2935                 return false;
2936
2937         if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2938                 return false;
2939
2940         if (wim->hdr.wim_version != WIM_VERSION_PACKED_STREAMS) {
2941                 if (wim->compression_type != wim->out_compression_type)
2942                         return false;
2943                 if (wim->chunk_size != wim->out_chunk_size)
2944                         return false;
2945         } else {
2946                 if (write_flags & WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)
2947                         return false;
2948         }
2949
2950         return true;
2951 }
2952
2953 /* API function documented in wimlib.h  */
2954 WIMLIBAPI int
2955 wimlib_overwrite(WIMStruct *wim, int write_flags,
2956                  unsigned num_threads,
2957                  wimlib_progress_func_t progress_func)
2958 {
2959         int ret;
2960         u32 orig_hdr_flags;
2961
2962         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2963
2964         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2965                 return WIMLIB_ERR_INVALID_PARAM;
2966
2967         if (!wim->filename)
2968                 return WIMLIB_ERR_NO_FILENAME;
2969
2970         orig_hdr_flags = wim->hdr.flags;
2971         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2972                 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
2973         ret = can_modify_wim(wim);
2974         wim->hdr.flags = orig_hdr_flags;
2975         if (ret)
2976                 return ret;
2977
2978         if (can_overwrite_wim_inplace(wim, write_flags)) {
2979                 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
2980                                             progress_func);
2981                 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
2982                         return ret;
2983                 WARNING("Falling back to re-building entire WIM");
2984         }
2985         return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,
2986                                          progress_func);
2987 }