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