]> wimlib.net Git - wimlib/blob - src/write.c
wimlib_overwrite(): Don't create multiple packs per WIM
[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/compress_chunks.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  * @comp_ctx
1203  *      A location in which to allocate the pointer to the default LZX
1204  *      compression context.  This will only be used if @out_ctype is
1205  *      WIMLIB_COMPRESSION_TYPE_LZX.
1206  *
1207  * @progress_func
1208  *      If non-NULL, a progress function that will be called periodically with
1209  *      WIMLIB_PROGRESS_MSG_WRITE_STREAMS messages.  Note that on-the-fly
1210  *      deduplication of unhashed streams may result in the total bytes provided
1211  *      in the progress data to decrease from one message to the next.
1212  *
1213  * This function will write the streams in @stream_list to resources in
1214  * consecutive positions in the output WIM file, or to a single packed resource
1215  * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1216  * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1217  * each stream written will be updated to specify its location, size, and flags
1218  * in the output WIM.  In the packed resource case,
1219  * WIM_RESHDR_FLAG_PACKED_STREAMS shall be set in the @flags field of the
1220  * @out_reshdr, and @out_res_offset_in_wim and @out_res_size_in_wim will also
1221  * be set to the offset and size, respectively, in the output WIM of the full
1222  * packed resource containing the corresponding stream.
1223  *
1224  * Each of the streams to write may be in any location supported by the
1225  * resource-handling code (specifically, read_stream_list()), such as the
1226  * contents of external file that has been logically added to the output WIM, or
1227  * a stream in another WIM file that has been imported, or even stream in the
1228  * "same" WIM file of which a modified copy is being written.  In the case that
1229  * a stream is already in a WIM file and uses compatible compression parameters,
1230  * by default this function will re-use the raw data instead of decompressing
1231  * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1232  * specified in @write_resource_flags, this is not done.
1233  *
1234  * As a further requirement, this function requires that the
1235  * @will_be_in_output_wim member be set on all streams in @stream_list as well
1236  * as any other streams not in @stream_list that will be in the output WIM file,
1237  * but not on any other streams in the output WIM's lookup table or sharing a
1238  * packed resource with a stream in @stream_list.  Still furthermore, if
1239  * on-the-fly deduplication of streams is possible, then all streams in
1240  * @stream_list must also be linked by @lookup_table_list along with any other
1241  * streams that have @will_be_in_output_wim set.
1242  *
1243  * This function handles on-the-fly deduplication of streams for which SHA1
1244  * message digests have not yet been calculated and it is therefore known
1245  * whether such streams are already in @stream_list or in the WIM's lookup table
1246  * at all.  If @lookup_table is non-NULL, then each stream in @stream_list that
1247  * has @unhashed set but not @unique_size set is checksummed immediately before
1248  * it would otherwise be read for writing in order to determine if it is
1249  * identical to another stream already being written or one that would be
1250  * filtered out of the output WIM using stream_filtered() with the context
1251  * @filter_ctx.  Each such duplicate stream will be removed from @stream_list, its
1252  * reference count transfered to the pre-existing duplicate stream, its memory
1253  * freed, and will not be written.  Alternatively, if a stream in @stream_list
1254  * is a duplicate with any stream in @lookup_table that has not been marked for
1255  * writing or would not be hard-filtered, it is freed and the pre-existing
1256  * duplicate is written instead, taking ownership of the reference count and
1257  * slot in the @lookup_table_list.
1258  *
1259  * Returns 0 if all streams were written successfully (or did not need to be
1260  * written); otherwise a non-zero error code.
1261  */
1262 static int
1263 write_stream_list(struct list_head *stream_list,
1264                   struct filedes *out_fd,
1265                   int write_resource_flags,
1266                   int out_ctype,
1267                   u32 out_chunk_size,
1268                   unsigned num_threads,
1269                   struct wim_lookup_table *lookup_table,
1270                   struct filter_context *filter_ctx,
1271                   struct wimlib_lzx_context **comp_ctx,
1272                   wimlib_progress_func_t progress_func)
1273 {
1274         int ret;
1275         struct write_streams_ctx ctx;
1276         struct list_head raw_copy_resources;
1277
1278         wimlib_assert((write_resource_flags &
1279                        (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1280                         WRITE_RESOURCE_FLAG_PIPABLE)) !=
1281                                 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1282                                  WRITE_RESOURCE_FLAG_PIPABLE));
1283
1284         remove_zero_length_streams(stream_list);
1285
1286         if (list_empty(stream_list)) {
1287                 DEBUG("No streams to write.");
1288                 return 0;
1289         }
1290
1291         memset(&ctx, 0, sizeof(ctx));
1292
1293         /* Pre-sorting the streams is required for compute_stream_list_stats().
1294          * Afterwards, read_stream_list() need not sort them again.  */
1295         ret = sort_stream_list_by_sequential_order(stream_list,
1296                                                    offsetof(struct wim_lookup_table_entry,
1297                                                             write_streams_list));
1298         if (ret)
1299                 return ret;
1300
1301         ctx.out_fd = out_fd;
1302         ctx.lookup_table = lookup_table;
1303         ctx.out_ctype = out_ctype;
1304         ctx.out_chunk_size = out_chunk_size;
1305         ctx.write_resource_flags = write_resource_flags;
1306         ctx.filter_ctx = filter_ctx;
1307
1308         if (out_chunk_size != 0) {
1309                 if (out_chunk_size <= STACK_MAX) {
1310                         ctx.chunk_buf = alloca(out_chunk_size);
1311                 } else {
1312                         ctx.chunk_buf = MALLOC(out_chunk_size);
1313                         if (ctx.chunk_buf == NULL) {
1314                                 ret = WIMLIB_ERR_NOMEM;
1315                                 goto out_destroy_context;
1316                         }
1317                 }
1318         }
1319         ctx.chunk_buf_filled = 0;
1320
1321         compute_stream_list_stats(stream_list, &ctx);
1322
1323         ctx.progress_data.progress_func = progress_func;
1324
1325         ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1326                                                             write_resource_flags,
1327                                                             out_ctype,
1328                                                             out_chunk_size,
1329                                                             &raw_copy_resources);
1330
1331         DEBUG("Writing stream list "
1332               "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1333               "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1334               "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1335               out_fd->offset, write_resource_flags,
1336               out_ctype, out_chunk_size, num_threads,
1337               ctx.progress_data.progress.write_streams.total_bytes,
1338               ctx.num_bytes_to_compress);
1339
1340         if (ctx.num_bytes_to_compress == 0) {
1341                 DEBUG("No compression needed; skipping to raw copy!");
1342                 goto out_write_raw_copy_resources;
1343         }
1344
1345         /* Unless uncompressed output was required, allocate a chunk_compressor
1346          * to do compression.  There are serial and parallel implementations of
1347          * the chunk_compressor interface.  We default to parallel using the
1348          * specified number of threads, unless the upper bound on the number
1349          * bytes needing to be compressed is less 2000000 (heuristic value).  */
1350         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1351
1352                 if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZMS &&
1353                     ctx.lookup_table != NULL) {
1354                         WARNING("LZMS compression not implemented; data will "
1355                                 "actually be written uncompressed.");
1356                 }
1357
1358                 if (ctx.num_bytes_to_compress >= 2000000) {
1359                         ret = new_parallel_chunk_compressor(out_ctype,
1360                                                             out_chunk_size,
1361                                                             num_threads, 0,
1362                                                             &ctx.compressor);
1363                         if (ret) {
1364                                 DEBUG("Couldn't create parallel chunk compressor "
1365                                       "(status %d)", ret);
1366                         }
1367                 }
1368
1369                 if (ctx.compressor == NULL) {
1370                         if (out_ctype == WIMLIB_COMPRESSION_TYPE_LZX) {
1371                                 ret = wimlib_lzx_alloc_context(out_chunk_size,
1372                                                                NULL,
1373                                                                comp_ctx);
1374                                 if (ret)
1375                                         goto out_destroy_context;
1376                         }
1377                         ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1378                                                           *comp_ctx, &ctx.compressor);
1379                         if (ret)
1380                                 goto out_destroy_context;
1381                 }
1382         }
1383
1384         if (ctx.compressor)
1385                 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1386         else
1387                 ctx.progress_data.progress.write_streams.num_threads = 1;
1388
1389         DEBUG("Actually using %u threads",
1390               ctx.progress_data.progress.write_streams.num_threads);
1391
1392         INIT_LIST_HEAD(&ctx.pending_streams);
1393
1394         if (ctx.progress_data.progress_func) {
1395                 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1396                                                    &ctx.progress_data.progress);
1397         }
1398
1399         if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1400                 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1401                 if (ret)
1402                         goto out_destroy_context;
1403         }
1404
1405         /* Read the list of streams needing to be compressed, using the
1406          * specified callbacks to execute processing of the data.  */
1407
1408         struct read_stream_list_callbacks cbs = {
1409                 .begin_stream           = write_stream_begin_read,
1410                 .begin_stream_ctx       = &ctx,
1411                 .consume_chunk          = write_stream_process_chunk,
1412                 .consume_chunk_ctx      = &ctx,
1413                 .end_stream             = write_stream_end_read,
1414                 .end_stream_ctx         = &ctx,
1415         };
1416
1417         ret = read_stream_list(stream_list,
1418                                offsetof(struct wim_lookup_table_entry, write_streams_list),
1419                                &cbs,
1420                                STREAM_LIST_ALREADY_SORTED |
1421                                         VERIFY_STREAM_HASHES |
1422                                         COMPUTE_MISSING_STREAM_HASHES);
1423
1424         if (ret)
1425                 goto out_destroy_context;
1426
1427         ret = finish_remaining_chunks(&ctx);
1428         if (ret)
1429                 goto out_destroy_context;
1430
1431         if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1432                 struct wim_reshdr reshdr;
1433                 struct wim_lookup_table_entry *lte;
1434                 u64 offset_in_res;
1435
1436                 ret = end_write_resource(&ctx, &reshdr);
1437                 if (ret)
1438                         goto out_destroy_context;
1439
1440                 DEBUG("Ending packed resource: %lu %lu %lu.",
1441                       reshdr.offset_in_wim,
1442                       reshdr.size_in_wim,
1443                       reshdr.uncompressed_size);
1444
1445                 offset_in_res = 0;
1446                 list_for_each_entry(lte, &ctx.pending_streams, write_streams_list) {
1447                         lte->out_reshdr.size_in_wim = lte->size;
1448                         lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1449                         lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1450                         lte->out_reshdr.uncompressed_size = 0;
1451                         lte->out_reshdr.offset_in_wim = offset_in_res;
1452                         lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1453                         lte->out_res_size_in_wim = reshdr.size_in_wim;
1454                         /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1455                         offset_in_res += lte->size;
1456                 }
1457                 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1458         }
1459
1460 out_write_raw_copy_resources:
1461         /* Copy any compressed resources for which the raw data can be reused
1462          * without decompression.  */
1463         ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd,
1464                                        &ctx.progress_data);
1465
1466 out_destroy_context:
1467         if (out_chunk_size > STACK_MAX)
1468                 FREE(ctx.chunk_buf);
1469         FREE(ctx.chunk_csizes);
1470         if (ctx.compressor)
1471                 ctx.compressor->destroy(ctx.compressor);
1472         DEBUG("Done (ret=%d)", ret);
1473         return ret;
1474 }
1475
1476 static int
1477 write_wim_resource(struct wim_lookup_table_entry *lte,
1478                    struct filedes *out_fd,
1479                    int out_ctype,
1480                    u32 out_chunk_size,
1481                    int write_resource_flags,
1482                    struct wimlib_lzx_context **comp_ctx)
1483 {
1484         LIST_HEAD(stream_list);
1485         list_add(&lte->write_streams_list, &stream_list);
1486         lte->will_be_in_output_wim = 1;
1487         return write_stream_list(&stream_list,
1488                                  out_fd,
1489                                  write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1490                                  out_ctype,
1491                                  out_chunk_size,
1492                                  1,
1493                                  NULL,
1494                                  NULL,
1495                                  comp_ctx,
1496                                  NULL);
1497 }
1498
1499 int
1500 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1501                                int reshdr_flags, struct filedes *out_fd,
1502                                int out_ctype,
1503                                u32 out_chunk_size,
1504                                struct wim_reshdr *out_reshdr,
1505                                u8 *hash,
1506                                int write_resource_flags,
1507                                struct wimlib_lzx_context **comp_ctx)
1508 {
1509         int ret;
1510         struct wim_lookup_table_entry *lte;
1511
1512         /* Set up a temporary lookup table entry to provide to
1513          * write_wim_resource().  */
1514
1515         lte = new_lookup_table_entry();
1516         if (lte == NULL)
1517                 return WIMLIB_ERR_NOMEM;
1518
1519         lte->resource_location  = RESOURCE_IN_ATTACHED_BUFFER;
1520         lte->attached_buffer    = (void*)buf;
1521         lte->size               = buf_size;
1522         lte->flags              = reshdr_flags;
1523
1524         if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1525                 sha1_buffer(buf, buf_size, lte->hash);
1526                 lte->unhashed = 0;
1527         } else {
1528                 lte->unhashed = 1;
1529         }
1530
1531         ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1532                                  write_resource_flags, comp_ctx);
1533         if (ret)
1534                 goto out_free_lte;
1535
1536         copy_reshdr(out_reshdr, &lte->out_reshdr);
1537
1538         if (hash)
1539                 copy_hash(hash, lte->hash);
1540         ret = 0;
1541 out_free_lte:
1542         lte->resource_location = RESOURCE_NONEXISTENT;
1543         free_lookup_table_entry(lte);
1544         return ret;
1545 }
1546
1547 struct stream_size_table {
1548         struct hlist_head *array;
1549         size_t num_entries;
1550         size_t capacity;
1551 };
1552
1553 static int
1554 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1555 {
1556         tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1557         if (tab->array == NULL)
1558                 return WIMLIB_ERR_NOMEM;
1559         tab->num_entries = 0;
1560         tab->capacity = capacity;
1561         return 0;
1562 }
1563
1564 static void
1565 destroy_stream_size_table(struct stream_size_table *tab)
1566 {
1567         FREE(tab->array);
1568 }
1569
1570 static int
1571 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1572 {
1573         struct stream_size_table *tab = _tab;
1574         size_t pos;
1575         struct wim_lookup_table_entry *same_size_lte;
1576         struct hlist_node *tmp;
1577
1578         pos = hash_u64(lte->size) % tab->capacity;
1579         lte->unique_size = 1;
1580         hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1581                 if (same_size_lte->size == lte->size) {
1582                         lte->unique_size = 0;
1583                         same_size_lte->unique_size = 0;
1584                         break;
1585                 }
1586         }
1587
1588         hlist_add_head(&lte->hash_list_2, &tab->array[pos]);
1589         tab->num_entries++;
1590         return 0;
1591 }
1592
1593 struct find_streams_ctx {
1594         WIMStruct *wim;
1595         int write_flags;
1596         struct list_head stream_list;
1597         struct stream_size_table stream_size_tab;
1598 };
1599
1600 static void
1601 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1602                            struct list_head *stream_list, u32 nref)
1603 {
1604         if (!lte->will_be_in_output_wim) {
1605                 lte->out_refcnt = 0;
1606                 list_add_tail(&lte->write_streams_list, stream_list);
1607                 lte->will_be_in_output_wim = 1;
1608         }
1609         lte->out_refcnt += nref;
1610 }
1611
1612 static int
1613 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1614                                  void *_stream_list)
1615 {
1616         struct list_head *stream_list = _stream_list;
1617         lte->will_be_in_output_wim = 0;
1618         reference_stream_for_write(lte, stream_list, lte->refcnt);
1619         return 0;
1620 }
1621
1622 static int
1623 inode_find_streams_to_reference(const struct wim_inode *inode,
1624                                 const struct wim_lookup_table *table,
1625                                 struct list_head *stream_list)
1626 {
1627         struct wim_lookup_table_entry *lte;
1628         unsigned i;
1629
1630         wimlib_assert(inode->i_nlink > 0);
1631
1632         for (i = 0; i <= inode->i_num_ads; i++) {
1633                 lte = inode_stream_lte(inode, i, table);
1634                 if (lte)
1635                         reference_stream_for_write(lte, stream_list,
1636                                                    inode->i_nlink);
1637                 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1638                         return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1639         }
1640         return 0;
1641 }
1642
1643 static int
1644 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1645 {
1646         lte->will_be_in_output_wim = 0;
1647         return 0;
1648 }
1649
1650 static int
1651 image_find_streams_to_reference(WIMStruct *wim)
1652 {
1653         struct wim_image_metadata *imd;
1654         struct wim_inode *inode;
1655         struct wim_lookup_table_entry *lte;
1656         struct list_head *stream_list;
1657         int ret;
1658
1659         imd = wim_get_current_image_metadata(wim);
1660
1661         image_for_each_unhashed_stream(lte, imd)
1662                 lte->will_be_in_output_wim = 0;
1663
1664         stream_list = wim->private;
1665         image_for_each_inode(inode, imd) {
1666                 ret = inode_find_streams_to_reference(inode,
1667                                                       wim->lookup_table,
1668                                                       stream_list);
1669                 if (ret)
1670                         return ret;
1671         }
1672         return 0;
1673 }
1674
1675 static int
1676 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1677                                                  int image,
1678                                                  int streams_ok,
1679                                                  struct list_head *stream_list_ret)
1680 {
1681         int ret;
1682
1683         INIT_LIST_HEAD(stream_list_ret);
1684
1685         if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1686                            (image == 1 && wim->hdr.image_count == 1)))
1687         {
1688                 /* Fast case:  Assume that all streams are being written and
1689                  * that the reference counts are correct.  */
1690                 struct wim_lookup_table_entry *lte;
1691                 struct wim_image_metadata *imd;
1692                 unsigned i;
1693
1694                 for_lookup_table_entry(wim->lookup_table,
1695                                        fully_reference_stream_for_write,
1696                                        stream_list_ret);
1697
1698                 for (i = 0; i < wim->hdr.image_count; i++) {
1699                         imd = wim->image_metadata[i];
1700                         image_for_each_unhashed_stream(lte, imd)
1701                                 fully_reference_stream_for_write(lte, stream_list_ret);
1702                 }
1703         } else {
1704                 /* Slow case:  Walk through the images being written and
1705                  * determine the streams referenced.  */
1706                 for_lookup_table_entry(wim->lookup_table,
1707                                        do_stream_set_not_in_output_wim, NULL);
1708                 wim->private = stream_list_ret;
1709                 ret = for_image(wim, image, image_find_streams_to_reference);
1710                 if (ret)
1711                         return ret;
1712         }
1713
1714         return 0;
1715 }
1716
1717 struct insert_other_if_hard_filtered_ctx {
1718         struct stream_size_table *tab;
1719         struct filter_context *filter_ctx;
1720 };
1721
1722 static int
1723 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1724 {
1725         struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1726
1727         if (!lte->will_be_in_output_wim &&
1728             stream_hard_filtered(lte, ctx->filter_ctx))
1729                 stream_size_table_insert(lte, ctx->tab);
1730         return 0;
1731 }
1732
1733 static int
1734 determine_stream_size_uniquity(struct list_head *stream_list,
1735                                struct wim_lookup_table *lt,
1736                                struct filter_context *filter_ctx)
1737 {
1738         int ret;
1739         struct stream_size_table tab;
1740         struct wim_lookup_table_entry *lte;
1741
1742         ret = init_stream_size_table(&tab, lt->capacity);
1743         if (ret)
1744                 return ret;
1745
1746         if (may_hard_filter_streams(filter_ctx)) {
1747                 struct insert_other_if_hard_filtered_ctx ctx = {
1748                         .tab = &tab,
1749                         .filter_ctx = filter_ctx,
1750                 };
1751                 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1752         }
1753
1754         list_for_each_entry(lte, stream_list, write_streams_list)
1755                 stream_size_table_insert(lte, &tab);
1756
1757         destroy_stream_size_table(&tab);
1758         return 0;
1759 }
1760
1761 static void
1762 filter_stream_list_for_write(struct list_head *stream_list,
1763                              struct filter_context *filter_ctx)
1764 {
1765         struct wim_lookup_table_entry *lte, *tmp;
1766
1767         list_for_each_entry_safe(lte, tmp,
1768                                  stream_list, write_streams_list)
1769         {
1770                 int status = stream_filtered(lte, filter_ctx);
1771
1772                 if (status == 0) {
1773                         /* Not filtered.  */
1774                         continue;
1775                 } else {
1776                         if (status > 0) {
1777                                 /* Soft filtered.  */
1778                         } else {
1779                                 /* Hard filtered.  */
1780                                 lte->will_be_in_output_wim = 0;
1781                                 list_del(&lte->lookup_table_list);
1782                         }
1783                         list_del(&lte->write_streams_list);
1784                 }
1785         }
1786 }
1787
1788 /*
1789  * prepare_stream_list_for_write() -
1790  *
1791  * Prepare the list of streams to write for writing a WIM containing the
1792  * specified image(s) with the specified write flags.
1793  *
1794  * @wim
1795  *      The WIMStruct on whose behalf the write is occurring.
1796  *
1797  * @image
1798  *      Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1799  *
1800  * @write_flags
1801  *      WIMLIB_WRITE_FLAG_* flags for the write operation:
1802  *
1803  *      STREAMS_OK:  For writes of all images, assume that all streams in the
1804  *      lookup table of @wim and the per-image lists of unhashed streams should
1805  *      be taken as-is, and image metadata should not be searched for
1806  *      references.  This does not exclude filtering with OVERWRITE and
1807  *      SKIP_EXTERNAL_WIMS, below.
1808  *
1809  *      OVERWRITE:  Streams already present in @wim shall not be returned in
1810  *      @stream_list_ret.
1811  *
1812  *      SKIP_EXTERNAL_WIMS:  Streams already present in a WIM file, but not
1813  *      @wim, shall be be returned in neither @stream_list_ret nor
1814  *      @lookup_table_list_ret.
1815  *
1816  * @stream_list_ret
1817  *      List of streams, linked by write_streams_list, that need to be written
1818  *      will be returned here.
1819  *
1820  *      Note that this function assumes that unhashed streams will be written;
1821  *      it does not take into account that they may become duplicates when
1822  *      actually hashed.
1823  *
1824  * @lookup_table_list_ret
1825  *      List of streams, linked by lookup_table_list, that need to be included
1826  *      in the WIM's lookup table will be returned here.  This will be a
1827  *      superset of the streams in @stream_list_ret.
1828  *
1829  *      This list will be a proper superset of @stream_list_ret if and only if
1830  *      WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1831  *      the streams that would otherwise need to be written were already located
1832  *      in the WIM file.
1833  *
1834  *      All streams in this list will have @out_refcnt set to the number of
1835  *      references to the stream in the output WIM.  If
1836  *      WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1837  *      may be as low as 0.
1838  *
1839  * @filter_ctx_ret
1840  *      A context for queries of stream filter status with stream_filtered() is
1841  *      returned in this location.
1842  *
1843  * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1844  * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1845  * lookup table of @wim not inserted into @lookup_table_list_ret.
1846  *
1847  * Still furthermore, @unique_size will be set to 1 on all stream entries in
1848  * @stream_list_ret that have unique size among all stream entries in
1849  * @stream_list_ret and among all stream entries in the lookup table of @wim
1850  * that are ineligible for being written due to filtering.
1851  *
1852  * Returns 0 on success; nonzero on read error, memory allocation error, or
1853  * otherwise.
1854  */
1855 static int
1856 prepare_stream_list_for_write(WIMStruct *wim, int image,
1857                               int write_flags,
1858                               struct list_head *stream_list_ret,
1859                               struct list_head *lookup_table_list_ret,
1860                               struct filter_context *filter_ctx_ret)
1861 {
1862         int ret;
1863         struct wim_lookup_table_entry *lte;
1864
1865         filter_ctx_ret->write_flags = write_flags;
1866         filter_ctx_ret->wim = wim;
1867
1868         ret = prepare_unfiltered_list_of_streams_in_output_wim(
1869                                 wim,
1870                                 image,
1871                                 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1872                                 stream_list_ret);
1873         if (ret)
1874                 return ret;
1875
1876         INIT_LIST_HEAD(lookup_table_list_ret);
1877         list_for_each_entry(lte, stream_list_ret, write_streams_list)
1878                 list_add_tail(&lte->lookup_table_list, lookup_table_list_ret);
1879
1880         ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1881                                              filter_ctx_ret);
1882         if (ret)
1883                 return ret;
1884
1885         if (may_filter_streams(filter_ctx_ret))
1886                 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1887
1888         return 0;
1889 }
1890
1891 static int
1892 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1893                   unsigned num_threads,
1894                   wimlib_progress_func_t progress_func,
1895                   struct list_head *stream_list_override,
1896                   struct list_head *lookup_table_list_ret)
1897 {
1898         int ret;
1899         struct list_head _stream_list;
1900         struct list_head *stream_list;
1901         struct wim_lookup_table_entry *lte;
1902         struct filter_context _filter_ctx;
1903         struct filter_context *filter_ctx;
1904
1905         if (stream_list_override == NULL) {
1906                 /* Normal case: prepare stream list from image(s) being written.
1907                  */
1908                 stream_list = &_stream_list;
1909                 filter_ctx = &_filter_ctx;
1910                 ret = prepare_stream_list_for_write(wim, image, write_flags,
1911                                                     stream_list,
1912                                                     lookup_table_list_ret,
1913                                                     filter_ctx);
1914                 if (ret)
1915                         return ret;
1916         } else {
1917                 /* Currently only as a result of wimlib_split() being called:
1918                  * use stream list already explicitly provided.  Use existing
1919                  * reference counts.  */
1920                 stream_list = stream_list_override;
1921                 filter_ctx = NULL;
1922                 INIT_LIST_HEAD(lookup_table_list_ret);
1923                 list_for_each_entry(lte, stream_list, write_streams_list) {
1924                         lte->out_refcnt = lte->refcnt;
1925                         lte->will_be_in_output_wim = 1;
1926                         lte->unique_size = 0;
1927                         list_add_tail(&lte->lookup_table_list, lookup_table_list_ret);
1928                 }
1929         }
1930
1931         return write_stream_list(stream_list,
1932                                  &wim->out_fd,
1933                                  write_flags_to_resource_flags(write_flags),
1934                                  wim->out_compression_type,
1935                                  wim->out_chunk_size,
1936                                  num_threads,
1937                                  wim->lookup_table,
1938                                  filter_ctx,
1939                                  &wim->lzx_context,
1940                                  progress_func);
1941 }
1942
1943 static int
1944 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
1945                              wimlib_progress_func_t progress_func)
1946 {
1947         int ret;
1948         int start_image;
1949         int end_image;
1950         int write_resource_flags;
1951
1952         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
1953                 DEBUG("Not writing any metadata resources.");
1954                 return 0;
1955         }
1956
1957         write_resource_flags = write_flags_to_resource_flags(write_flags);
1958
1959         write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
1960
1961         DEBUG("Writing metadata resources (offset=%"PRIu64")",
1962               wim->out_fd.offset);
1963
1964         if (progress_func)
1965                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
1966
1967         if (image == WIMLIB_ALL_IMAGES) {
1968                 start_image = 1;
1969                 end_image = wim->hdr.image_count;
1970         } else {
1971                 start_image = image;
1972                 end_image = image;
1973         }
1974
1975         for (int i = start_image; i <= end_image; i++) {
1976                 struct wim_image_metadata *imd;
1977
1978                 imd = wim->image_metadata[i - 1];
1979                 /* Build a new metadata resource only if image was modified from
1980                  * the original (or was newly added).  Otherwise just copy the
1981                  * existing one.  */
1982                 if (imd->modified) {
1983                         DEBUG("Image %u was modified; building and writing new "
1984                               "metadata resource", i);
1985                         ret = write_metadata_resource(wim, i,
1986                                                       write_resource_flags);
1987                 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
1988                         DEBUG("Image %u was not modified; re-using existing "
1989                               "metadata resource.", i);
1990                         stream_set_out_reshdr_for_reuse(imd->metadata_lte);
1991                         ret = 0;
1992                 } else {
1993                         DEBUG("Image %u was not modified; copying existing "
1994                               "metadata resource.", i);
1995                         ret = write_wim_resource(imd->metadata_lte,
1996                                                  &wim->out_fd,
1997                                                  wim->out_compression_type,
1998                                                  wim->out_chunk_size,
1999                                                  write_resource_flags,
2000                                                  &wim->lzx_context);
2001                 }
2002                 if (ret)
2003                         return ret;
2004         }
2005         if (progress_func)
2006                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2007         return 0;
2008 }
2009
2010 static int
2011 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2012 {
2013         int raw_fd;
2014         DEBUG("Opening \"%"TS"\" for writing.", path);
2015
2016         raw_fd = topen(path, open_flags | O_BINARY, 0644);
2017         if (raw_fd < 0) {
2018                 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2019                 return WIMLIB_ERR_OPEN;
2020         }
2021         filedes_init(&wim->out_fd, raw_fd);
2022         return 0;
2023 }
2024
2025 static int
2026 close_wim_writable(WIMStruct *wim, int write_flags)
2027 {
2028         int ret = 0;
2029
2030         if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2031                 DEBUG("Closing WIM file.");
2032                 if (filedes_valid(&wim->out_fd))
2033                         if (filedes_close(&wim->out_fd))
2034                                 ret = WIMLIB_ERR_WRITE;
2035         }
2036         filedes_invalidate(&wim->out_fd);
2037         return ret;
2038 }
2039
2040 static int
2041 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2042 {
2043         const struct wim_lookup_table_entry *lte1, *lte2;
2044
2045         lte1 = *(const struct wim_lookup_table_entry**)p1;
2046         lte2 = *(const struct wim_lookup_table_entry**)p2;
2047
2048         if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2049                 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2050                         if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2051                                 return cmp_u64(lte1->out_res_offset_in_wim,
2052                                                lte2->out_res_offset_in_wim);
2053                 } else {
2054                         return 1;
2055                 }
2056         } else {
2057                 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2058                         return -1;
2059         }
2060         return cmp_u64(lte1->out_reshdr.offset_in_wim,
2061                        lte2->out_reshdr.offset_in_wim);
2062 }
2063
2064 static int
2065 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2066                        struct wim_reshdr *out_reshdr,
2067                        struct list_head *lookup_table_list)
2068 {
2069         int ret;
2070
2071         /* Set output resource metadata for streams already present in WIM.  */
2072         if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2073                 struct wim_lookup_table_entry *lte;
2074                 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2075                 {
2076                         if (lte->resource_location == RESOURCE_IN_WIM &&
2077                             lte->rspec->wim == wim)
2078                         {
2079                                 stream_set_out_reshdr_for_reuse(lte);
2080                         }
2081                 }
2082         }
2083
2084         ret = sort_stream_list(lookup_table_list,
2085                                offsetof(struct wim_lookup_table_entry, lookup_table_list),
2086                                cmp_streams_by_out_rspec);
2087         if (ret)
2088                 return ret;
2089
2090         /* Add entries for metadata resources.  */
2091         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2092                 int start_image;
2093                 int end_image;
2094
2095                 if (image == WIMLIB_ALL_IMAGES) {
2096                         start_image = 1;
2097                         end_image = wim->hdr.image_count;
2098                 } else {
2099                         start_image = image;
2100                         end_image = image;
2101                 }
2102
2103                 /* Push metadata resource lookup table entries onto the front of
2104                  * the list in reverse order, so that they're written in order.
2105                  */
2106                 for (int i = end_image; i >= start_image; i--) {
2107                         struct wim_lookup_table_entry *metadata_lte;
2108
2109                         metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2110                         wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2111                         metadata_lte->out_refcnt = 1;
2112                         list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2113                 }
2114         }
2115
2116         return write_wim_lookup_table_from_stream_list(lookup_table_list,
2117                                                        &wim->out_fd,
2118                                                        wim->hdr.part_number,
2119                                                        out_reshdr,
2120                                                        write_flags_to_resource_flags(write_flags),
2121                                                        &wim->lzx_context);
2122 }
2123
2124 /*
2125  * finish_write():
2126  *
2127  * Finish writing a WIM file: write the lookup table, xml data, and integrity
2128  * table, then overwrite the WIM header.  By default, closes the WIM file
2129  * descriptor (@wim->out_fd) if successful.
2130  *
2131  * write_flags is a bitwise OR of the following:
2132  *
2133  *      (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2134  *              Include an integrity table.
2135  *
2136  *      (public) WIMLIB_WRITE_FLAG_FSYNC:
2137  *              fsync() the output file before closing it.
2138  *
2139  *      (public) WIMLIB_WRITE_FLAG_PIPABLE:
2140  *              Writing a pipable WIM, possibly to a pipe; include pipable WIM
2141  *              stream headers before the lookup table and XML data, and also
2142  *              write the WIM header at the end instead of seeking to the
2143  *              beginning.  Can't be combined with
2144  *              WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2145  *
2146  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2147  *              Don't write the lookup table.
2148  *
2149  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2150  *              When (if) writing the integrity table, re-use entries from the
2151  *              existing integrity table, if possible.
2152  *
2153  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2154  *              After writing the XML data but before writing the integrity
2155  *              table, write a temporary WIM header and flush the stream so that
2156  *              the WIM is less likely to become corrupted upon abrupt program
2157  *              termination.
2158  *      (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2159  *              Instead of overwriting the WIM header at the beginning of the
2160  *              file, simply append it to the end of the file.  (Used when
2161  *              writing to pipe.)
2162  *      (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2163  *              Do not close the file descriptor @wim->out_fd on either success
2164  *              on failure.
2165  *      (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2166  *              Use the existing <TOTALBYTES> stored in the in-memory XML
2167  *              information, rather than setting it to the offset of the XML
2168  *              data being written.
2169  */
2170 static int
2171 finish_write(WIMStruct *wim, int image, int write_flags,
2172              wimlib_progress_func_t progress_func,
2173              struct list_head *lookup_table_list)
2174 {
2175         int ret;
2176         off_t hdr_offset;
2177         int write_resource_flags;
2178         off_t old_lookup_table_end;
2179         off_t new_lookup_table_end;
2180         u64 xml_totalbytes;
2181
2182         DEBUG("image=%d, write_flags=%08x", image, write_flags);
2183
2184         write_resource_flags = write_flags_to_resource_flags(write_flags);
2185
2186         /* In the WIM header, there is room for the resource entry for a
2187          * metadata resource labeled as the "boot metadata".  This entry should
2188          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
2189          * it should be a copy of the resource entry for the image that is
2190          * marked as bootable.  This is not well documented...  */
2191         if (wim->hdr.boot_idx == 0) {
2192                 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2193         } else {
2194                 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2195                             &wim->image_metadata[
2196                                 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2197         }
2198
2199         /* Write lookup table.  (Save old position first.)  */
2200         old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2201                                wim->hdr.lookup_table_reshdr.size_in_wim;
2202         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2203                 ret = write_wim_lookup_table(wim, image, write_flags,
2204                                              &wim->hdr.lookup_table_reshdr,
2205                                              lookup_table_list);
2206                 if (ret)
2207                         return ret;
2208         }
2209
2210         /* Write XML data.  */
2211         xml_totalbytes = wim->out_fd.offset;
2212         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2213                 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2214         ret = write_wim_xml_data(wim, image, xml_totalbytes,
2215                                  &wim->hdr.xml_data_reshdr,
2216                                  write_resource_flags);
2217         if (ret)
2218                 return ret;
2219
2220         /* Write integrity table (optional).  */
2221         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2222                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2223                         struct wim_header checkpoint_hdr;
2224                         memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2225                         zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2226                         checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2227                         ret = write_wim_header_at_offset(&checkpoint_hdr,
2228                                                          &wim->out_fd, 0);
2229                         if (ret)
2230                                 return ret;
2231                 }
2232
2233                 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2234                         old_lookup_table_end = 0;
2235
2236                 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2237                                        wim->hdr.lookup_table_reshdr.size_in_wim;
2238
2239                 ret = write_integrity_table(wim,
2240                                             new_lookup_table_end,
2241                                             old_lookup_table_end,
2242                                             progress_func);
2243                 if (ret)
2244                         return ret;
2245         } else {
2246                 /* No integrity table.  */
2247                 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2248         }
2249
2250         /* Now that all information in the WIM header has been determined, the
2251          * preliminary header written earlier can be overwritten, the header of
2252          * the existing WIM file can be overwritten, or the final header can be
2253          * written to the end of the pipable WIM.  */
2254         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2255         hdr_offset = 0;
2256         if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2257                 hdr_offset = wim->out_fd.offset;
2258         DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2259         ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2260         if (ret)
2261                 return ret;
2262
2263         /* Possibly sync file data to disk before closing.  On POSIX systems, it
2264          * is necessary to do this before using rename() to overwrite an
2265          * existing file with a new file.  Otherwise, data loss would occur if
2266          * the system is abruptly terminated when the metadata for the rename
2267          * operation has been written to disk, but the new file data has not.
2268          */
2269         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2270                 DEBUG("Syncing WIM file.");
2271                 if (fsync(wim->out_fd.fd)) {
2272                         ERROR_WITH_ERRNO("Error syncing data to WIM file");
2273                         return WIMLIB_ERR_WRITE;
2274                 }
2275         }
2276
2277         if (close_wim_writable(wim, write_flags)) {
2278                 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2279                 return WIMLIB_ERR_WRITE;
2280         }
2281
2282         return 0;
2283 }
2284
2285 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2286 int
2287 lock_wim(WIMStruct *wim, int fd)
2288 {
2289         int ret = 0;
2290         if (fd != -1 && !wim->wim_locked) {
2291                 ret = flock(fd, LOCK_EX | LOCK_NB);
2292                 if (ret != 0) {
2293                         if (errno == EWOULDBLOCK) {
2294                                 ERROR("`%"TS"' is already being modified or has been "
2295                                       "mounted read-write\n"
2296                                       "        by another process!", wim->filename);
2297                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
2298                         } else {
2299                                 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2300                                                    wim->filename);
2301                                 ret = 0;
2302                         }
2303                 } else {
2304                         wim->wim_locked = 1;
2305                 }
2306         }
2307         return ret;
2308 }
2309 #endif
2310
2311 /*
2312  * write_pipable_wim():
2313  *
2314  * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2315  * capable of being applied from a pipe).
2316  *
2317  * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2318  * images can be applied from them sequentially when the file data is sent over
2319  * a pipe.  In addition, a pipable WIM can be written sequentially to a pipe.
2320  * The modifications made to the WIM format for pipable WIMs are:
2321  *
2322  * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2323  *   of "MSWIM\0\0\0".  This lets wimlib know that the WIM is pipable and also
2324  *   stops other software from trying to read the file as a normal WIM.
2325  *
2326  * - The header at the beginning of the file does not contain all the normal
2327  *   information; in particular it will have all 0's for the lookup table and
2328  *   XML data resource entries.  This is because this information cannot be
2329  *   determined until the lookup table and XML data have been written.
2330  *   Consequently, wimlib will write the full header at the very end of the
2331  *   file.  The header at the end, however, is only used when reading the WIM
2332  *   from a seekable file (not a pipe).
2333  *
2334  * - An extra copy of the XML data is placed directly after the header.  This
2335  *   allows image names and sizes to be determined at an appropriate time when
2336  *   reading the WIM from a pipe.  This copy of the XML data is ignored if the
2337  *   WIM is read from a seekable file (not a pipe).
2338  *
2339  * - The format of resources, or streams, has been modified to allow them to be
2340  *   used before the "lookup table" has been read.  Each stream is prefixed with
2341  *   a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2342  *   wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2343  *   uncompressed stream size, and flags that indicate whether the stream is
2344  *   compressed.  The data of uncompressed streams then follows literally, while
2345  *   the data of compressed streams follows in a modified format.  Compressed
2346  *   streams do not begin with a chunk table, since the chunk table cannot be
2347  *   written until all chunks have been compressed.  Instead, each compressed
2348  *   chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2349  *   Furthermore, the chunk table is written at the end of the resource instead
2350  *   of the start.  Note: chunk offsets are given in the chunk table as if the
2351  *   `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2352  *   used if the WIM is being read from a seekable file (not a pipe).
2353  *
2354  * - Metadata resources always come before other file resources (streams).
2355  *   (This does not by itself constitute an incompatibility with normal WIMs,
2356  *   since this is valid in normal WIMs.)
2357  *
2358  * - At least up to the end of the file resources, all components must be packed
2359  *   as tightly as possible; there cannot be any "holes" in the WIM.  (This does
2360  *   not by itself consititute an incompatibility with normal WIMs, since this
2361  *   is valid in normal WIMs.)
2362  *
2363  * Note: the lookup table, XML data, and header at the end are not used when
2364  * applying from a pipe.  They exist to support functionality such as image
2365  * application and export when the WIM is *not* read from a pipe.
2366  *
2367  *   Layout of pipable WIM:
2368  *
2369  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2370  * | Header | XML data | Metadata resources | File resources | Lookup table | XML data  | Header |
2371  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2372  *
2373  *   Layout of normal WIM:
2374  *
2375  * +--------+-----------------------------+-------------------------+
2376  * | Header | File and metadata resources | Lookup table | XML data |
2377  * +--------+-----------------------------+-------------------------+
2378  *
2379  * An optional integrity table can follow the final XML data in both normal and
2380  * pipable WIMs.  However, due to implementation details, wimlib currently can
2381  * only include an integrity table in a pipable WIM when writing it to a
2382  * seekable file (not a pipe).
2383  *
2384  * Do note that since pipable WIMs are not supported by Microsoft's software,
2385  * wimlib does not create them unless explicitly requested (with
2386  * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2387  * characters to identify the file.
2388  */
2389 static int
2390 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2391                   unsigned num_threads, wimlib_progress_func_t progress_func,
2392                   struct list_head *stream_list_override,
2393                   struct list_head *lookup_table_list_ret)
2394 {
2395         int ret;
2396         struct wim_reshdr xml_reshdr;
2397
2398         WARNING("Creating a pipable WIM, which will "
2399                 "be incompatible\n"
2400                 "          with Microsoft's software (wimgapi/imagex/Dism).");
2401
2402         /* At this point, the header at the beginning of the file has already
2403          * been written.  */
2404
2405         /* For efficiency, when wimlib adds an image to the WIM with
2406          * wimlib_add_image(), the SHA1 message digests of files is not
2407          * calculated; instead, they are calculated while the files are being
2408          * written.  However, this does not work when writing a pipable WIM,
2409          * since when writing a stream to a pipable WIM, its SHA1 message digest
2410          * needs to be known before the stream data is written.  Therefore,
2411          * before getting much farther, we need to pre-calculate the SHA1
2412          * message digests of all streams that will be written.  */
2413         ret = wim_checksum_unhashed_streams(wim);
2414         if (ret)
2415                 return ret;
2416
2417         /* Write extra copy of the XML data.  */
2418         ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2419                                  &xml_reshdr,
2420                                  WRITE_RESOURCE_FLAG_PIPABLE);
2421         if (ret)
2422                 return ret;
2423
2424         /* Write metadata resources for the image(s) being included in the
2425          * output WIM.  */
2426         ret = write_wim_metadata_resources(wim, image, write_flags,
2427                                            progress_func);
2428         if (ret)
2429                 return ret;
2430
2431         /* Write streams needed for the image(s) being included in the output
2432          * WIM, or streams needed for the split WIM part.  */
2433         return write_wim_streams(wim, image, write_flags, num_threads,
2434                                  progress_func, stream_list_override,
2435                                  lookup_table_list_ret);
2436
2437         /* The lookup table, XML data, and header at end are handled by
2438          * finish_write().  */
2439 }
2440
2441 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2442  * descriptor.  */
2443 int
2444 write_wim_part(WIMStruct *wim,
2445                const void *path_or_fd,
2446                int image,
2447                int write_flags,
2448                unsigned num_threads,
2449                wimlib_progress_func_t progress_func,
2450                unsigned part_number,
2451                unsigned total_parts,
2452                struct list_head *stream_list_override,
2453                const u8 *guid)
2454 {
2455         int ret;
2456         struct wim_header hdr_save;
2457         struct list_head lookup_table_list;
2458
2459         if (total_parts == 1)
2460                 DEBUG("Writing standalone WIM.");
2461         else
2462                 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2463         if (image == WIMLIB_ALL_IMAGES)
2464                 DEBUG("Including all images.");
2465         else
2466                 DEBUG("Including image %d only.", image);
2467         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2468                 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2469         else
2470                 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2471         DEBUG("Write flags: 0x%08x", write_flags);
2472
2473         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2474                 DEBUG("\tCHECK_INTEGRITY");
2475
2476         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2477                 DEBUG("\tREBUILD");
2478
2479         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2480                 DEBUG("\tRECOMPRESS");
2481
2482         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2483                 DEBUG("\tFSYNC");
2484
2485         if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2486                 DEBUG("\tFSYNC");
2487
2488         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2489                 DEBUG("\tIGNORE_READONLY_FLAG");
2490
2491         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2492                 DEBUG("\tPIPABLE");
2493
2494         if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2495                 DEBUG("\tNOT_PIPABLE");
2496
2497         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2498                 DEBUG("\tPACK_STREAMS");
2499
2500         if (write_flags & WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)
2501                 DEBUG("\tNO_PACK_STREAMS");
2502
2503         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2504                 DEBUG("\tFILE_DESCRIPTOR");
2505
2506         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2507                 DEBUG("\tNO_METADATA");
2508
2509         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2510                 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2511
2512         if (num_threads == 0)
2513                 DEBUG("Number of threads: autodetect");
2514         else
2515                 DEBUG("Number of threads: %u", num_threads);
2516         DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2517         DEBUG("Stream list:       %s", (stream_list_override ? "specified" : "autodetect"));
2518         DEBUG("GUID:              %s", ((guid || wim->guid_set_explicitly) ?
2519                                         "specified" : "generate new"));
2520
2521         /* Internally, this is always called with a valid part number and total
2522          * parts.  */
2523         wimlib_assert(total_parts >= 1);
2524         wimlib_assert(part_number >= 1 && part_number <= total_parts);
2525
2526         /* A valid image (or all images) must be specified.  */
2527         if (image != WIMLIB_ALL_IMAGES &&
2528              (image < 1 || image > wim->hdr.image_count))
2529                 return WIMLIB_ERR_INVALID_IMAGE;
2530
2531         /* If we need to write metadata resources, make sure the ::WIMStruct has
2532          * the needed information attached (e.g. is not a resource-only WIM,
2533          * such as a non-first part of a split WIM).  */
2534         if (!wim_has_metadata(wim) &&
2535             !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2536                 return WIMLIB_ERR_METADATA_NOT_FOUND;
2537
2538         /* Check for contradictory flags.  */
2539         if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2540                             WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2541                                 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2542                                     WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2543                 return WIMLIB_ERR_INVALID_PARAM;
2544
2545         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2546                             WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2547                                 == (WIMLIB_WRITE_FLAG_PIPABLE |
2548                                     WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2549                 return WIMLIB_ERR_INVALID_PARAM;
2550
2551         if ((write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2552                             WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2553                                 == (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2554                                     WIMLIB_WRITE_FLAG_NO_PACK_STREAMS))
2555                 return WIMLIB_ERR_INVALID_PARAM;
2556
2557         /* Save previous header, then start initializing the new one.  */
2558         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2559
2560         /* Set default integrity, pipable, and packed stream flags.  */
2561         if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2562                              WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2563                 if (wim_is_pipable(wim)) {
2564                         DEBUG("WIM is pipable; default to PIPABLE.");
2565                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2566                 }
2567
2568         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2569                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2570                 if (wim_has_integrity_table(wim)) {
2571                         DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2572                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2573                 }
2574
2575         if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2576                              WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2577                 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS) {
2578                         DEBUG("WIM version 3584; default to PACK_STREAMS.");
2579                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2580                 }
2581
2582         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2583                             WIMLIB_WRITE_FLAG_PACK_STREAMS))
2584                                     == (WIMLIB_WRITE_FLAG_PIPABLE |
2585                                         WIMLIB_WRITE_FLAG_PACK_STREAMS))
2586         {
2587                 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2588                 return WIMLIB_ERR_INVALID_PARAM;
2589         }
2590
2591         /* Set appropriate magic number.  */
2592         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2593                 wim->hdr.magic = PWM_MAGIC;
2594         else
2595                 wim->hdr.magic = WIM_MAGIC;
2596
2597         /* Set appropriate version number.  */
2598         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2599                 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2600         else
2601                 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2602
2603         /* Clear header flags that will be set automatically.  */
2604         wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY          |
2605                             WIM_HDR_FLAG_RESOURCE_ONLY          |
2606                             WIM_HDR_FLAG_SPANNED                |
2607                             WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2608
2609         /* Set SPANNED header flag if writing part of a split WIM.  */
2610         if (total_parts != 1)
2611                 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2612
2613         /* Set part number and total parts of split WIM.  This will be 1 and 1
2614          * if the WIM is standalone.  */
2615         wim->hdr.part_number = part_number;
2616         wim->hdr.total_parts = total_parts;
2617
2618         /* Set compression type if different.  */
2619         if (wim->compression_type != wim->out_compression_type) {
2620                 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2621                 wimlib_assert(ret == 0);
2622         }
2623
2624         /* Set chunk size if different.  */
2625         wim->hdr.chunk_size = wim->out_chunk_size;
2626
2627         /* Use GUID if specified; otherwise generate a new one.  */
2628         if (guid)
2629                 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2630         else if (!wim->guid_set_explicitly)
2631                 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2632
2633         /* Clear references to resources that have not been written yet.  */
2634         zero_reshdr(&wim->hdr.lookup_table_reshdr);
2635         zero_reshdr(&wim->hdr.xml_data_reshdr);
2636         zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2637         zero_reshdr(&wim->hdr.integrity_table_reshdr);
2638
2639         /* Set image count and boot index correctly for single image writes.  */
2640         if (image != WIMLIB_ALL_IMAGES) {
2641                 wim->hdr.image_count = 1;
2642                 if (wim->hdr.boot_idx == image)
2643                         wim->hdr.boot_idx = 1;
2644                 else
2645                         wim->hdr.boot_idx = 0;
2646         }
2647
2648         /* Split WIMs can't be bootable.  */
2649         if (total_parts != 1)
2650                 wim->hdr.boot_idx = 0;
2651
2652         /* Initialize output file descriptor.  */
2653         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2654                 /* File descriptor was explicitly provided.  Return error if
2655                  * file descriptor is not seekable, unless writing a pipable WIM
2656                  * was requested.  */
2657                 wim->out_fd.fd = *(const int*)path_or_fd;
2658                 wim->out_fd.offset = 0;
2659                 if (!filedes_is_seekable(&wim->out_fd)) {
2660                         ret = WIMLIB_ERR_INVALID_PARAM;
2661                         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2662                                 goto out_restore_hdr;
2663                         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2664                                 ERROR("Can't include integrity check when "
2665                                       "writing pipable WIM to pipe!");
2666                                 goto out_restore_hdr;
2667                         }
2668                 }
2669
2670         } else {
2671                 /* Filename of WIM to write was provided; open file descriptor
2672                  * to it.  */
2673                 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2674                                         O_TRUNC | O_CREAT | O_RDWR);
2675                 if (ret)
2676                         goto out_restore_hdr;
2677         }
2678
2679         /* Write initial header.  This is merely a "dummy" header since it
2680          * doesn't have all the information yet, so it will be overwritten later
2681          * (unless writing a pipable WIM).  */
2682         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2683                 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2684         ret = write_wim_header(&wim->hdr, &wim->out_fd);
2685         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2686         if (ret)
2687                 goto out_restore_hdr;
2688
2689         /* Write metadata resources and streams.  */
2690         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2691                 /* Default case: create a normal (non-pipable) WIM.  */
2692                 ret = write_wim_streams(wim, image, write_flags, num_threads,
2693                                         progress_func, stream_list_override,
2694                                         &lookup_table_list);
2695                 if (ret)
2696                         goto out_restore_hdr;
2697
2698                 ret = write_wim_metadata_resources(wim, image, write_flags,
2699                                                    progress_func);
2700                 if (ret)
2701                         goto out_restore_hdr;
2702         } else {
2703                 /* Non-default case: create pipable WIM.  */
2704                 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2705                                         progress_func, stream_list_override,
2706                                         &lookup_table_list);
2707                 if (ret)
2708                         goto out_restore_hdr;
2709                 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2710         }
2711
2712
2713         /* Write lookup table, XML data, and (optional) integrity table.  */
2714         ret = finish_write(wim, image, write_flags, progress_func,
2715                            &lookup_table_list);
2716 out_restore_hdr:
2717         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2718         (void)close_wim_writable(wim, write_flags);
2719         DEBUG("ret=%d", ret);
2720         return ret;
2721 }
2722
2723 /* Write a standalone WIM to a file or file descriptor.  */
2724 static int
2725 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2726                      int image, int write_flags, unsigned num_threads,
2727                      wimlib_progress_func_t progress_func)
2728 {
2729         return write_wim_part(wim, path_or_fd, image, write_flags,
2730                               num_threads, progress_func, 1, 1, NULL, NULL);
2731 }
2732
2733 /* API function documented in wimlib.h  */
2734 WIMLIBAPI int
2735 wimlib_write(WIMStruct *wim, const tchar *path,
2736              int image, int write_flags, unsigned num_threads,
2737              wimlib_progress_func_t progress_func)
2738 {
2739         if (!path)
2740                 return WIMLIB_ERR_INVALID_PARAM;
2741
2742         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2743
2744         return write_standalone_wim(wim, path, image, write_flags,
2745                                     num_threads, progress_func);
2746 }
2747
2748 /* API function documented in wimlib.h  */
2749 WIMLIBAPI int
2750 wimlib_write_to_fd(WIMStruct *wim, int fd,
2751                    int image, int write_flags, unsigned num_threads,
2752                    wimlib_progress_func_t progress_func)
2753 {
2754         if (fd < 0)
2755                 return WIMLIB_ERR_INVALID_PARAM;
2756
2757         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2758         write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2759
2760         return write_standalone_wim(wim, &fd, image, write_flags,
2761                                     num_threads, progress_func);
2762 }
2763
2764 static bool
2765 any_images_modified(WIMStruct *wim)
2766 {
2767         for (int i = 0; i < wim->hdr.image_count; i++)
2768                 if (wim->image_metadata[i]->modified)
2769                         return true;
2770         return false;
2771 }
2772
2773 static int
2774 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2775 {
2776         const WIMStruct *wim = _wim;
2777         off_t end_offset = *(const off_t*)wim->private;
2778
2779         if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2780             lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2781                 return WIMLIB_ERR_RESOURCE_ORDER;
2782         return 0;
2783 }
2784
2785 /* Make sure no file or metadata resources are located after the XML data (or
2786  * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2787  * place and we return WIMLIB_ERR_RESOURCE_ORDER.  */
2788 static int
2789 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2790 {
2791         int ret;
2792         unsigned i;
2793
2794         wim->private = &end_offset;
2795         ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2796         if (ret)
2797                 return ret;
2798
2799         for (i = 0; i < wim->hdr.image_count; i++) {
2800                 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2801                 if (ret)
2802                         return ret;
2803         }
2804         return 0;
2805 }
2806
2807 /*
2808  * Overwrite a WIM, possibly appending streams to it.
2809  *
2810  * A WIM looks like (or is supposed to look like) the following:
2811  *
2812  *                   Header (212 bytes)
2813  *                   Streams and metadata resources (variable size)
2814  *                   Lookup table (variable size)
2815  *                   XML data (variable size)
2816  *                   Integrity table (optional) (variable size)
2817  *
2818  * If we are not adding any streams or metadata resources, the lookup table is
2819  * unchanged--- so we only need to overwrite the XML data, integrity table, and
2820  * header.  This operation is potentially unsafe if the program is abruptly
2821  * terminated while the XML data or integrity table are being overwritten, but
2822  * before the new header has been written.  To partially alleviate this problem,
2823  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2824  * finish_write() to cause a temporary WIM header to be written after the XML
2825  * data has been written.  This may prevent the WIM from becoming corrupted if
2826  * the program is terminated while the integrity table is being calculated (but
2827  * no guarantees, due to write re-ordering...).
2828  *
2829  * If we are adding new streams or images (metadata resources), the lookup table
2830  * needs to be changed, and those streams need to be written.  In this case, we
2831  * try to perform a safe update of the WIM file by writing the streams *after*
2832  * the end of the previous WIM, then writing the new lookup table, XML data, and
2833  * (optionally) integrity table following the new streams.  This will produce a
2834  * layout like the following:
2835  *
2836  *                   Header (212 bytes)
2837  *                   (OLD) Streams and metadata resources (variable size)
2838  *                   (OLD) Lookup table (variable size)
2839  *                   (OLD) XML data (variable size)
2840  *                   (OLD) Integrity table (optional) (variable size)
2841  *                   (NEW) Streams and metadata resources (variable size)
2842  *                   (NEW) Lookup table (variable size)
2843  *                   (NEW) XML data (variable size)
2844  *                   (NEW) Integrity table (optional) (variable size)
2845  *
2846  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
2847  * the header is overwritten to point to the new lookup table, XML data, and
2848  * integrity table, to produce the following layout:
2849  *
2850  *                   Header (212 bytes)
2851  *                   Streams and metadata resources (variable size)
2852  *                   Nothing (variable size)
2853  *                   More Streams and metadata resources (variable size)
2854  *                   Lookup table (variable size)
2855  *                   XML data (variable size)
2856  *                   Integrity table (optional) (variable size)
2857  *
2858  * This method allows an image to be appended to a large WIM very quickly, and
2859  * is is crash-safe except in the case of write re-ordering, but the
2860  * disadvantage is that a small hole is left in the WIM where the old lookup
2861  * table, xml data, and integrity table were.  (These usually only take up a
2862  * small amount of space compared to the streams, however.)
2863  */
2864 static int
2865 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2866                       unsigned num_threads,
2867                       wimlib_progress_func_t progress_func)
2868 {
2869         int ret;
2870         off_t old_wim_end;
2871         u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2872         struct wim_header hdr_save;
2873         struct list_head stream_list;
2874         struct list_head lookup_table_list;
2875         struct filter_context filter_ctx;
2876
2877         DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2878
2879         /* Save original header so it can be restored in case of error  */
2880         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2881
2882         /* Set default integrity flag.  */
2883         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2884                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2885                 if (wim_has_integrity_table(wim))
2886                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2887
2888         /* Set default packed flag.  */
2889         if (!(write_flags & (WIMLIB_WRITE_FLAG_PACK_STREAMS |
2890                              WIMLIB_WRITE_FLAG_NO_PACK_STREAMS)))
2891         {
2892         #if 0
2893                 if (wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
2894                         write_flags |= WIMLIB_WRITE_FLAG_PACK_STREAMS;
2895         #endif
2896                 /* wimlib allows multiple packs in a single WIM, but they don't
2897                  * seem to be compatible with WIMGAPI.  Write new streams
2898                  * unpacked.  */
2899         } else if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) {
2900                 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2901         }
2902
2903         /* Set additional flags for overwrite.  */
2904         write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2905                        WIMLIB_WRITE_FLAG_STREAMS_OK;
2906
2907         /* Make sure that the integrity table (if present) is after the XML
2908          * data, and that there are no stream resources, metadata resources, or
2909          * lookup tables after the XML data.  Otherwise, these data would be
2910          * overwritten. */
2911         old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2912         old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2913         old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2914                                wim->hdr.lookup_table_reshdr.size_in_wim;
2915         if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2916             wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2917                 WARNING("Didn't expect the integrity table to be before the XML data");
2918                 ret = WIMLIB_ERR_RESOURCE_ORDER;
2919                 goto out_restore_memory_hdr;
2920         }
2921
2922         if (old_lookup_table_end > old_xml_begin) {
2923                 WARNING("Didn't expect the lookup table to be after the XML data");
2924                 ret = WIMLIB_ERR_RESOURCE_ORDER;
2925                 goto out_restore_memory_hdr;
2926         }
2927
2928         /* Set @old_wim_end, which indicates the point beyond which we don't
2929          * allow any file and metadata resources to appear without returning
2930          * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2931          * overwrite these resources). */
2932         if (!wim->deletion_occurred && !any_images_modified(wim)) {
2933                 /* If no images have been modified and no images have been
2934                  * deleted, a new lookup table does not need to be written.  We
2935                  * shall write the new XML data and optional integrity table
2936                  * immediately after the lookup table.  Note that this may
2937                  * overwrite an existing integrity table. */
2938                 DEBUG("Skipping writing lookup table "
2939                       "(no images modified or deleted)");
2940                 old_wim_end = old_lookup_table_end;
2941                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2942                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2943         } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2944                 /* Old WIM has an integrity table; begin writing new streams
2945                  * after it. */
2946                 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2947                               wim->hdr.integrity_table_reshdr.size_in_wim;
2948         } else {
2949                 /* No existing integrity table; begin writing new streams after
2950                  * the old XML data. */
2951                 old_wim_end = old_xml_end;
2952         }
2953
2954         ret = check_resource_offsets(wim, old_wim_end);
2955         if (ret)
2956                 goto out_restore_memory_hdr;
2957
2958         ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2959                                             &stream_list, &lookup_table_list,
2960                                             &filter_ctx);
2961         if (ret)
2962                 goto out_restore_memory_hdr;
2963
2964         ret = open_wim_writable(wim, wim->filename, O_RDWR);
2965         if (ret)
2966                 goto out_restore_memory_hdr;
2967
2968         ret = lock_wim(wim, wim->out_fd.fd);
2969         if (ret)
2970                 goto out_close_wim;
2971
2972         /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
2973         wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2974         ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
2975         if (ret) {
2976                 ERROR_WITH_ERRNO("Error updating WIM header flags");
2977                 goto out_unlock_wim;
2978         }
2979
2980         if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
2981                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
2982                 ret = WIMLIB_ERR_WRITE;
2983                 goto out_restore_physical_hdr;
2984         }
2985
2986         ret = write_stream_list(&stream_list,
2987                                 &wim->out_fd,
2988                                 write_flags_to_resource_flags(write_flags),
2989                                 wim->compression_type,
2990                                 wim->chunk_size,
2991                                 num_threads,
2992                                 wim->lookup_table,
2993                                 &filter_ctx,
2994                                 &wim->lzx_context,
2995                                 progress_func);
2996         if (ret)
2997                 goto out_truncate;
2998
2999         ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3000                                            write_flags, progress_func);
3001         if (ret)
3002                 goto out_truncate;
3003
3004         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3005         ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3006                            progress_func, &lookup_table_list);
3007         if (ret)
3008                 goto out_truncate;
3009
3010         wim->wim_locked = 0;
3011         return 0;
3012
3013 out_truncate:
3014         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3015                 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3016                         wim->filename, old_wim_end);
3017                 /* Return value of ftruncate() is ignored because this is
3018                  * already an error path.  */
3019                 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3020         }
3021 out_restore_physical_hdr:
3022         (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3023 out_unlock_wim:
3024         wim->wim_locked = 0;
3025 out_close_wim:
3026         (void)close_wim_writable(wim, write_flags);
3027 out_restore_memory_hdr:
3028         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3029         return ret;
3030 }
3031
3032 static int
3033 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3034                           unsigned num_threads,
3035                           wimlib_progress_func_t progress_func)
3036 {
3037         size_t wim_name_len;
3038         int ret;
3039
3040         DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3041
3042         /* Write the WIM to a temporary file in the same directory as the
3043          * original WIM. */
3044         wim_name_len = tstrlen(wim->filename);
3045         tchar tmpfile[wim_name_len + 10];
3046         tmemcpy(tmpfile, wim->filename, wim_name_len);
3047         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3048         tmpfile[wim_name_len + 9] = T('\0');
3049
3050         ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3051                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3052                            num_threads, progress_func);
3053         if (ret) {
3054                 tunlink(tmpfile);
3055                 return ret;
3056         }
3057
3058         close_wim(wim);
3059
3060         /* Rename the new WIM file to the original WIM file.  Note: on Windows
3061          * this actually calls win32_rename_replacement(), not _wrename(), so
3062          * that removing the existing destination file can be handled.  */
3063         DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3064         ret = trename(tmpfile, wim->filename);
3065         if (ret) {
3066                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3067                                  tmpfile, wim->filename);
3068         #ifdef __WIN32__
3069                 if (ret < 0)
3070         #endif
3071                 {
3072                         tunlink(tmpfile);
3073                 }
3074                 return WIMLIB_ERR_RENAME;
3075         }
3076
3077         if (progress_func) {
3078                 union wimlib_progress_info progress;
3079                 progress.rename.from = tmpfile;
3080                 progress.rename.to = wim->filename;
3081                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3082         }
3083         return 0;
3084 }
3085
3086 /* Determine if the specified WIM file may be updated by appending in-place
3087  * rather than writing and replacing it with an entirely new file.  */
3088 static bool
3089 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3090 {
3091         /* REBUILD flag forces full rebuild.  */
3092         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3093                 return false;
3094
3095         /* Deletions cause full rebuild by default.  */
3096         if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3097                 return false;
3098
3099         /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3100          * turned into a pipable WIM in-place.  */
3101         if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3102                 return false;
3103
3104         /* wimlib allows multiple packs in a single WIM, but they don't seem to
3105          * be compatible with WIMGAPI, so force all streams to be repacked if
3106          * the WIM already may have contained a pack and PACK_STREAMS was
3107          * requested.  */
3108         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS &&
3109             wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
3110                 return false;
3111
3112         /* The default compression type and compression chunk size selected for
3113          * the output WIM must be the same as those currently used for the WIM.
3114          */
3115         if (wim->compression_type != wim->out_compression_type)
3116                 return false;
3117         if (wim->chunk_size != wim->out_chunk_size)
3118                 return false;
3119
3120         return true;
3121 }
3122
3123 /* API function documented in wimlib.h  */
3124 WIMLIBAPI int
3125 wimlib_overwrite(WIMStruct *wim, int write_flags,
3126                  unsigned num_threads,
3127                  wimlib_progress_func_t progress_func)
3128 {
3129         int ret;
3130         u32 orig_hdr_flags;
3131
3132         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3133
3134         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3135                 return WIMLIB_ERR_INVALID_PARAM;
3136
3137         if (!wim->filename)
3138                 return WIMLIB_ERR_NO_FILENAME;
3139
3140         orig_hdr_flags = wim->hdr.flags;
3141         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3142                 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3143         ret = can_modify_wim(wim);
3144         wim->hdr.flags = orig_hdr_flags;
3145         if (ret)
3146                 return ret;
3147
3148         if (can_overwrite_wim_inplace(wim, write_flags)) {
3149                 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3150                                             progress_func);
3151                 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3152                         return ret;
3153                 WARNING("Falling back to re-building entire WIM");
3154         }
3155         return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,
3156                                          progress_func);
3157 }