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