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