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