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