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