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