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