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