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