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