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