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