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