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