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