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