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