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