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