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