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