]> wimlib.net Git - wimlib/blob - src/write.c
write_stream_list(): Do not allocate chunk buffer if NONE compression
[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_stream_to_fd(lte, out_fd, lte->size);
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                         resized_chunk = ctx->chunk_buf;
957
958                         chunkptr += bytes_consumed;
959                         ctx->cur_read_res_offset += bytes_consumed;
960                         ctx->chunk_buf_filled += bytes_consumed;
961                         if (ctx->chunk_buf_filled == needed_chunk_size) {
962                                 resized_chunk = ctx->chunk_buf;
963                                 ctx->chunk_buf_filled = 0;
964                         } else {
965                                 break;
966                         }
967
968                 }
969
970                 ret = submit_chunk_for_compression(ctx, resized_chunk,
971                                                    needed_chunk_size);
972                 if (ret)
973                         return ret;
974
975         } while (chunkptr != chunkend);
976         return 0;
977 }
978
979 /* Finish processing a stream for writing.  It may not have been completely
980  * written yet, as the chunk_compressor implementation may still have chunks
981  * buffered or being compressed.  */
982 static int
983 write_stream_end_read(struct wim_lookup_table_entry *lte, int status, void *_ctx)
984 {
985         struct write_streams_ctx *ctx = _ctx;
986         if (status == 0)
987                 wimlib_assert(ctx->cur_read_res_offset == ctx->cur_read_res_size);
988         if (ctx->stream_was_duplicate) {
989                 free_lookup_table_entry(lte);
990         } else if (lte->unhashed && ctx->lookup_table != NULL) {
991                 list_del(&lte->unhashed_list);
992                 lookup_table_insert(ctx->lookup_table, lte);
993                 lte->unhashed = 0;
994         }
995         return status;
996 }
997
998 /* Compute statistics about a list of streams that will be written.
999  *
1000  * Assumes the streams are sorted such that all streams located in each distinct
1001  * WIM (specified by WIMStruct) are together.  */
1002 static void
1003 compute_stream_list_stats(struct list_head *stream_list,
1004                           struct write_streams_ctx *ctx)
1005 {
1006         struct wim_lookup_table_entry *lte;
1007         u64 total_bytes = 0;
1008         u64 num_streams = 0;
1009         u64 total_parts = 0;
1010         WIMStruct *prev_wim_part = NULL;
1011
1012         list_for_each_entry(lte, stream_list, write_streams_list) {
1013                 num_streams++;
1014                 total_bytes += lte->size;
1015                 if (lte->resource_location == RESOURCE_IN_WIM) {
1016                         if (prev_wim_part != lte->rspec->wim) {
1017                                 prev_wim_part = lte->rspec->wim;
1018                                 total_parts++;
1019                         }
1020                 }
1021         }
1022         ctx->progress_data.progress.write_streams.total_bytes       = total_bytes;
1023         ctx->progress_data.progress.write_streams.total_streams     = num_streams;
1024         ctx->progress_data.progress.write_streams.completed_bytes   = 0;
1025         ctx->progress_data.progress.write_streams.completed_streams = 0;
1026         ctx->progress_data.progress.write_streams.compression_type  = ctx->out_ctype;
1027         ctx->progress_data.progress.write_streams.total_parts       = total_parts;
1028         ctx->progress_data.progress.write_streams.completed_parts   = 0;
1029         ctx->progress_data.next_progress = 0;
1030         ctx->progress_data.prev_wim_part = NULL;
1031 }
1032
1033 /* Find streams in @stream_list that can be copied to the output WIM in raw form
1034  * rather than compressed.  Delete these streams from @stream_list, and move one
1035  * per resource to @raw_copy_resources.  Return the total uncompressed size of
1036  * the streams that need to be compressed.  */
1037 static u64
1038 find_raw_copy_resources(struct list_head *stream_list,
1039                         int write_resource_flags,
1040                         int out_ctype,
1041                         u32 out_chunk_size,
1042                         struct list_head *raw_copy_resources)
1043 {
1044         struct wim_lookup_table_entry *lte, *tmp;
1045         u64 num_bytes_to_compress = 0;
1046
1047         INIT_LIST_HEAD(raw_copy_resources);
1048
1049         /* Initialize temporary raw_copy_ok flag.  */
1050         list_for_each_entry(lte, stream_list, write_streams_list)
1051                 if (lte->resource_location == RESOURCE_IN_WIM)
1052                         lte->rspec->raw_copy_ok = 0;
1053
1054         list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1055                 if (lte->resource_location == RESOURCE_IN_WIM &&
1056                     lte->rspec->raw_copy_ok)
1057                 {
1058                         list_del(&lte->write_streams_list);
1059                 } else if (can_raw_copy(lte, write_resource_flags,
1060                                  out_ctype, out_chunk_size))
1061                 {
1062                         lte->rspec->raw_copy_ok = 1;
1063                         list_move_tail(&lte->write_streams_list,
1064                                        raw_copy_resources);
1065                 } else {
1066                         num_bytes_to_compress += lte->size;
1067                 }
1068         }
1069
1070         return num_bytes_to_compress;
1071 }
1072
1073 /* Copy a raw compressed resource located in another WIM file to the WIM file
1074  * being written.  */
1075 static int
1076 write_raw_copy_resource(struct wim_resource_spec *in_rspec,
1077                         struct filedes *out_fd)
1078 {
1079         u64 cur_read_offset;
1080         u64 end_read_offset;
1081         u8 buf[BUFFER_SIZE];
1082         size_t bytes_to_read;
1083         int ret;
1084         struct filedes *in_fd;
1085         struct wim_lookup_table_entry *lte;
1086         u64 out_offset_in_wim;
1087
1088         DEBUG("Copying raw compressed data (size_in_wim=%"PRIu64", "
1089               "uncompressed_size=%"PRIu64")",
1090               in_rspec->size_in_wim, in_rspec->uncompressed_size);
1091
1092         /* Copy the raw data.  */
1093         cur_read_offset = in_rspec->offset_in_wim;
1094         end_read_offset = cur_read_offset + in_rspec->size_in_wim;
1095
1096         out_offset_in_wim = out_fd->offset;
1097
1098         if (in_rspec->is_pipable) {
1099                 if (cur_read_offset < sizeof(struct pwm_stream_hdr))
1100                         return WIMLIB_ERR_INVALID_PIPABLE_WIM;
1101                 cur_read_offset -= sizeof(struct pwm_stream_hdr);
1102                 out_offset_in_wim += sizeof(struct pwm_stream_hdr);
1103         }
1104         in_fd = &in_rspec->wim->in_fd;
1105         wimlib_assert(cur_read_offset != end_read_offset);
1106         do {
1107
1108                 bytes_to_read = min(sizeof(buf), end_read_offset - cur_read_offset);
1109
1110                 ret = full_pread(in_fd, buf, bytes_to_read, cur_read_offset);
1111                 if (ret)
1112                         return ret;
1113
1114                 ret = full_write(out_fd, buf, bytes_to_read);
1115                 if (ret)
1116                         return ret;
1117
1118                 cur_read_offset += bytes_to_read;
1119
1120         } while (cur_read_offset != end_read_offset);
1121
1122         list_for_each_entry(lte, &in_rspec->stream_list, rspec_node) {
1123                 if (lte->will_be_in_output_wim) {
1124                         stream_set_out_reshdr_for_reuse(lte);
1125                         if (in_rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
1126                                 lte->out_res_offset_in_wim = out_offset_in_wim;
1127                         else
1128                                 lte->out_reshdr.offset_in_wim = out_offset_in_wim;
1129
1130                 }
1131         }
1132         return 0;
1133 }
1134
1135 /* Copy a list of raw compressed resources located other WIM file(s) to the WIM
1136  * file being written.  */
1137 static int
1138 write_raw_copy_resources(struct list_head *raw_copy_resources,
1139                          struct filedes *out_fd,
1140                          struct write_streams_progress_data *progress_data)
1141 {
1142         struct wim_lookup_table_entry *lte;
1143         int ret;
1144
1145         list_for_each_entry(lte, raw_copy_resources, write_streams_list) {
1146                 ret = write_raw_copy_resource(lte->rspec, out_fd);
1147                 if (ret)
1148                         return ret;
1149                 do_write_streams_progress(progress_data, lte->size, false, lte);
1150         }
1151         return 0;
1152 }
1153
1154 /* Wait for and write all chunks pending in the compressor.  */
1155 static int
1156 finish_remaining_chunks(struct write_streams_ctx *ctx)
1157 {
1158         const void *cdata;
1159         unsigned csize;
1160         unsigned usize;
1161         int ret;
1162
1163         if (ctx->compressor == NULL)
1164                 return 0;
1165
1166         if (ctx->chunk_buf_filled != 0) {
1167                 ret = submit_chunk_for_compression(ctx, ctx->chunk_buf,
1168                                                    ctx->chunk_buf_filled);
1169                 if (ret)
1170                         return ret;
1171         }
1172
1173         while (ctx->compressor->get_chunk(ctx->compressor, &cdata, &csize, &usize)) {
1174                 ret = write_chunk(ctx, cdata, csize, usize);
1175                 if (ret)
1176                         return ret;
1177         }
1178         return 0;
1179 }
1180
1181 static void
1182 remove_zero_length_streams(struct list_head *stream_list)
1183 {
1184         struct wim_lookup_table_entry *lte, *tmp;
1185
1186         list_for_each_entry_safe(lte, tmp, stream_list, write_streams_list) {
1187                 wimlib_assert(lte->will_be_in_output_wim);
1188                 if (lte->size == 0) {
1189                         list_del(&lte->write_streams_list);
1190                         lte->out_reshdr.offset_in_wim = 0;
1191                         lte->out_reshdr.size_in_wim = 0;
1192                         lte->out_reshdr.uncompressed_size = 0;
1193                         lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1194                 }
1195         }
1196 }
1197
1198 /*
1199  * Write a list of streams to the output WIM file.
1200  *
1201  * @stream_list
1202  *      The list of streams to write, specifies a list of `struct
1203  *      wim_lookup_table_entry's linked by the 'write_streams_list' member.
1204  *
1205  * @out_fd
1206  *      The file descriptor, opened for writing, to which to write the streams.
1207  *
1208  * @write_resource_flags
1209  *      Flags to modify how the streams are written:
1210  *
1211  *      WRITE_RESOURCE_FLAG_RECOMPRESS:
1212  *              Force compression of all resources, even if they could otherwise
1213  *              be re-used by caping the raw data, due to being located in a WIM
1214  *              file with compatible compression parameters.
1215  *
1216  *      WRITE_RESOURCE_FLAG_PIPABLE:
1217  *              Write the resources in the wimlib-specific pipable format, and
1218  *              furthermore do so in such a way that no seeking backwards in
1219  *              @out_fd will be performed (so it may be a pipe, contrary to the
1220  *              default behavior).
1221  *
1222  *      WRITE_RESOURCE_FLAG_PACK_STREAMS:
1223  *              Pack all the streams into a single resource rather than writing
1224  *              them in separate resources.  This format is only valid if the
1225  *              WIM version number is WIM_VERSION_PACKED_STREAMS.  This flag
1226  *              currently may not be combined with WRITE_RESOURCE_FLAG_PIPABLE.
1227  *
1228  * @out_ctype
1229  *      Compression format to use to write the output streams, specified as one
1230  *      of the WIMLIB_COMPRESSION_TYPE_* constants, excepting
1231  *      WIMLIB_COMPRESSION_TYPE_INVALID but including
1232  *      WIMLIB_COMPRESSION_TYPE_NONE.
1233  *
1234  * @out_chunk_size
1235  *      Chunk size to use to write the streams.  It must be a valid chunk size
1236  *      for the specified compression format @out_ctype, unless @out_ctype is
1237  *      WIMLIB_COMPRESSION_TYPE_NONE, in which case this parameter is ignored.
1238  *
1239  * @num_threads
1240  *      Number of threads to use to compress data.  If 0, a default number of
1241  *      threads will be chosen.  The number of threads still may be decreased
1242  *      from the specified value if insufficient memory is detected.
1243  *
1244  * @lookup_table
1245  *      If on-the-fly deduplication of unhashed streams is desired, this
1246  *      parameter must be pointer to the lookup table for the WIMStruct on whose
1247  *      behalf the streams are being written.  Otherwise, this parameter can be
1248  *      NULL.
1249  *
1250  * @filter_ctx
1251  *      If on-the-fly deduplication of unhashed streams is desired, this
1252  *      parameter can be a pointer to a context for stream filtering used to
1253  *      detect whether the duplicate stream has been hard-filtered or not.  If
1254  *      no streams are hard-filtered or no streams are unhashed, this parameter
1255  *      can be NULL.
1256  *
1257  * @progress_func
1258  *      If non-NULL, a progress function that will be called periodically with
1259  *      WIMLIB_PROGRESS_MSG_WRITE_STREAMS messages.  Note that on-the-fly
1260  *      deduplication of unhashed streams may result in the total bytes provided
1261  *      in the progress data to decrease from one message to the next.
1262  *
1263  * This function will write the streams in @stream_list to resources in
1264  * consecutive positions in the output WIM file, or to a single packed resource
1265  * if WRITE_RESOURCE_FLAG_PACK_STREAMS was specified in @write_resource_flags.
1266  * In both cases, the @out_reshdr of the `struct wim_lookup_table_entry' for
1267  * each stream written will be updated to specify its location, size, and flags
1268  * in the output WIM.  In the packed resource case,
1269  * WIM_RESHDR_FLAG_PACKED_STREAMS shall be set in the @flags field of the
1270  * @out_reshdr, and @out_res_offset_in_wim and @out_res_size_in_wim will also
1271  * be set to the offset and size, respectively, in the output WIM of the full
1272  * packed resource containing the corresponding stream.
1273  *
1274  * Each of the streams to write may be in any location supported by the
1275  * resource-handling code (specifically, read_stream_list()), such as the
1276  * contents of external file that has been logically added to the output WIM, or
1277  * a stream in another WIM file that has been imported, or even stream in the
1278  * "same" WIM file of which a modified copy is being written.  In the case that
1279  * a stream is already in a WIM file and uses compatible compression parameters,
1280  * by default this function will re-use the raw data instead of decompressing
1281  * it, then recompressing it; however, with WRITE_RESOURCE_FLAG_RECOMPRESS
1282  * specified in @write_resource_flags, this is not done.
1283  *
1284  * As a further requirement, this function requires that the
1285  * @will_be_in_output_wim member be set on all streams in @stream_list as well
1286  * as any other streams not in @stream_list that will be in the output WIM file,
1287  * but not on any other streams in the output WIM's lookup table or sharing a
1288  * packed resource with a stream in @stream_list.  Still furthermore, if
1289  * on-the-fly deduplication of streams is possible, then all streams in
1290  * @stream_list must also be linked by @lookup_table_list along with any other
1291  * streams that have @will_be_in_output_wim set.
1292  *
1293  * This function handles on-the-fly deduplication of streams for which SHA1
1294  * message digests have not yet been calculated and it is therefore known
1295  * whether such streams are already in @stream_list or in the WIM's lookup table
1296  * at all.  If @lookup_table is non-NULL, then each stream in @stream_list that
1297  * has @unhashed set but not @unique_size set is checksummed immediately before
1298  * it would otherwise be read for writing in order to determine if it is
1299  * identical to another stream already being written or one that would be
1300  * filtered out of the output WIM using stream_filtered() with the context
1301  * @filter_ctx.  Each such duplicate stream will be removed from @stream_list, its
1302  * reference count transfered to the pre-existing duplicate stream, its memory
1303  * freed, and will not be written.  Alternatively, if a stream in @stream_list
1304  * is a duplicate with any stream in @lookup_table that has not been marked for
1305  * writing or would not be hard-filtered, it is freed and the pre-existing
1306  * duplicate is written instead, taking ownership of the reference count and
1307  * slot in the @lookup_table_list.
1308  *
1309  * Returns 0 if all streams were written successfully (or did not need to be
1310  * written); otherwise a non-zero error code.
1311  */
1312 static int
1313 write_stream_list(struct list_head *stream_list,
1314                   struct filedes *out_fd,
1315                   int write_resource_flags,
1316                   int out_ctype,
1317                   u32 out_chunk_size,
1318                   unsigned num_threads,
1319                   struct wim_lookup_table *lookup_table,
1320                   struct filter_context *filter_ctx,
1321                   wimlib_progress_func_t progress_func)
1322 {
1323         int ret;
1324         struct write_streams_ctx ctx;
1325         struct list_head raw_copy_resources;
1326
1327         wimlib_assert((write_resource_flags &
1328                        (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1329                         WRITE_RESOURCE_FLAG_PIPABLE)) !=
1330                                 (WRITE_RESOURCE_FLAG_PACK_STREAMS |
1331                                  WRITE_RESOURCE_FLAG_PIPABLE));
1332
1333         remove_zero_length_streams(stream_list);
1334
1335         if (list_empty(stream_list)) {
1336                 DEBUG("No streams to write.");
1337                 return 0;
1338         }
1339
1340         memset(&ctx, 0, sizeof(ctx));
1341
1342         /* Pre-sorting the streams is required for compute_stream_list_stats().
1343          * Afterwards, read_stream_list() need not sort them again.  */
1344         ret = sort_stream_list_by_sequential_order(stream_list,
1345                                                    offsetof(struct wim_lookup_table_entry,
1346                                                             write_streams_list));
1347         if (ret)
1348                 return ret;
1349
1350         ctx.out_fd = out_fd;
1351         ctx.lookup_table = lookup_table;
1352         ctx.out_ctype = out_ctype;
1353         ctx.out_chunk_size = out_chunk_size;
1354         ctx.write_resource_flags = write_resource_flags;
1355         ctx.filter_ctx = filter_ctx;
1356
1357         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1358                 wimlib_assert(out_chunk_size != 0);
1359                 if (out_chunk_size <= STACK_MAX) {
1360                         ctx.chunk_buf = alloca(out_chunk_size);
1361                 } else {
1362                         ctx.chunk_buf = MALLOC(out_chunk_size);
1363                         if (ctx.chunk_buf == NULL) {
1364                                 ret = WIMLIB_ERR_NOMEM;
1365                                 goto out_destroy_context;
1366                         }
1367                 }
1368         }
1369         ctx.chunk_buf_filled = 0;
1370
1371         compute_stream_list_stats(stream_list, &ctx);
1372
1373         ctx.progress_data.progress_func = progress_func;
1374
1375         ctx.num_bytes_to_compress = find_raw_copy_resources(stream_list,
1376                                                             write_resource_flags,
1377                                                             out_ctype,
1378                                                             out_chunk_size,
1379                                                             &raw_copy_resources);
1380
1381         DEBUG("Writing stream list "
1382               "(offset = %"PRIu64", write_resource_flags=0x%08x, "
1383               "out_ctype=%d, out_chunk_size=%u, num_threads=%u, "
1384               "total_bytes=%"PRIu64", num_bytes_to_compress=%"PRIu64")",
1385               out_fd->offset, write_resource_flags,
1386               out_ctype, out_chunk_size, num_threads,
1387               ctx.progress_data.progress.write_streams.total_bytes,
1388               ctx.num_bytes_to_compress);
1389
1390         if (ctx.num_bytes_to_compress == 0) {
1391                 DEBUG("No compression needed; skipping to raw copy!");
1392                 goto out_write_raw_copy_resources;
1393         }
1394
1395         /* Unless uncompressed output was required, allocate a chunk_compressor
1396          * to do compression.  There are serial and parallel implementations of
1397          * the chunk_compressor interface.  We default to parallel using the
1398          * specified number of threads, unless the upper bound on the number
1399          * bytes needing to be compressed is less 2000000 (heuristic value).  */
1400         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE) {
1401
1402         #ifdef ENABLE_MULTITHREADED_COMPRESSION
1403                 if (ctx.num_bytes_to_compress >= 2000000) {
1404                         ret = new_parallel_chunk_compressor(out_ctype,
1405                                                             out_chunk_size,
1406                                                             num_threads, 0,
1407                                                             &ctx.compressor);
1408                         if (ret) {
1409                                 DEBUG("Couldn't create parallel chunk compressor "
1410                                       "(status %d)", ret);
1411                         }
1412                 }
1413         #endif
1414
1415                 if (ctx.compressor == NULL) {
1416                         ret = new_serial_chunk_compressor(out_ctype, out_chunk_size,
1417                                                           &ctx.compressor);
1418                         if (ret)
1419                                 goto out_destroy_context;
1420                 }
1421         }
1422
1423         if (ctx.compressor)
1424                 ctx.progress_data.progress.write_streams.num_threads = ctx.compressor->num_threads;
1425         else
1426                 ctx.progress_data.progress.write_streams.num_threads = 1;
1427
1428         DEBUG("Actually using %u threads",
1429               ctx.progress_data.progress.write_streams.num_threads);
1430
1431         INIT_LIST_HEAD(&ctx.pending_streams);
1432
1433         if (ctx.progress_data.progress_func) {
1434                 (*ctx.progress_data.progress_func)(WIMLIB_PROGRESS_MSG_WRITE_STREAMS,
1435                                                    &ctx.progress_data.progress);
1436         }
1437
1438         if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1439                 ret = begin_write_resource(&ctx, ctx.num_bytes_to_compress);
1440                 if (ret)
1441                         goto out_destroy_context;
1442         }
1443
1444         /* Read the list of streams needing to be compressed, using the
1445          * specified callbacks to execute processing of the data.  */
1446
1447         struct read_stream_list_callbacks cbs = {
1448                 .begin_stream           = write_stream_begin_read,
1449                 .begin_stream_ctx       = &ctx,
1450                 .consume_chunk          = write_stream_process_chunk,
1451                 .consume_chunk_ctx      = &ctx,
1452                 .end_stream             = write_stream_end_read,
1453                 .end_stream_ctx         = &ctx,
1454         };
1455
1456         ret = read_stream_list(stream_list,
1457                                offsetof(struct wim_lookup_table_entry, write_streams_list),
1458                                &cbs,
1459                                STREAM_LIST_ALREADY_SORTED |
1460                                         VERIFY_STREAM_HASHES |
1461                                         COMPUTE_MISSING_STREAM_HASHES);
1462
1463         if (ret)
1464                 goto out_destroy_context;
1465
1466         ret = finish_remaining_chunks(&ctx);
1467         if (ret)
1468                 goto out_destroy_context;
1469
1470         if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1471                 struct wim_reshdr reshdr;
1472                 struct wim_lookup_table_entry *lte;
1473                 u64 offset_in_res;
1474
1475                 ret = end_write_resource(&ctx, &reshdr);
1476                 if (ret)
1477                         goto out_destroy_context;
1478
1479                 DEBUG("Ending packed resource: %lu %lu %lu.",
1480                       reshdr.offset_in_wim,
1481                       reshdr.size_in_wim,
1482                       reshdr.uncompressed_size);
1483
1484                 offset_in_res = 0;
1485                 list_for_each_entry(lte, &ctx.pending_streams, write_streams_list) {
1486                         lte->out_reshdr.size_in_wim = lte->size;
1487                         lte->out_reshdr.flags = filter_resource_flags(lte->flags);
1488                         lte->out_reshdr.flags |= WIM_RESHDR_FLAG_PACKED_STREAMS;
1489                         lte->out_reshdr.uncompressed_size = 0;
1490                         lte->out_reshdr.offset_in_wim = offset_in_res;
1491                         lte->out_res_offset_in_wim = reshdr.offset_in_wim;
1492                         lte->out_res_size_in_wim = reshdr.size_in_wim;
1493                         /*lte->out_res_uncompressed_size = reshdr.uncompressed_size;*/
1494                         offset_in_res += lte->size;
1495                 }
1496                 wimlib_assert(offset_in_res == reshdr.uncompressed_size);
1497         }
1498
1499 out_write_raw_copy_resources:
1500         /* Copy any compressed resources for which the raw data can be reused
1501          * without decompression.  */
1502         ret = write_raw_copy_resources(&raw_copy_resources, ctx.out_fd,
1503                                        &ctx.progress_data);
1504
1505 out_destroy_context:
1506         if (out_ctype != WIMLIB_COMPRESSION_TYPE_NONE && out_chunk_size > STACK_MAX)
1507                 FREE(ctx.chunk_buf);
1508         FREE(ctx.chunk_csizes);
1509         if (ctx.compressor)
1510                 ctx.compressor->destroy(ctx.compressor);
1511         DEBUG("Done (ret=%d)", ret);
1512         return ret;
1513 }
1514
1515 static int
1516 wim_write_stream_list(WIMStruct *wim,
1517                       struct list_head *stream_list,
1518                       int write_flags,
1519                       unsigned num_threads,
1520                       struct filter_context *filter_ctx,
1521                       wimlib_progress_func_t progress_func)
1522 {
1523         int out_ctype;
1524         u32 out_chunk_size;
1525         int write_resource_flags;
1526
1527         write_resource_flags = write_flags_to_resource_flags(write_flags);
1528
1529         if (write_resource_flags & WRITE_RESOURCE_FLAG_PACK_STREAMS) {
1530                 out_chunk_size = wim->out_pack_chunk_size;
1531                 out_ctype = wim->out_pack_compression_type;
1532         } else {
1533                 out_chunk_size = wim->out_chunk_size;
1534                 out_ctype = wim->out_compression_type;
1535         }
1536
1537         return write_stream_list(stream_list,
1538                                  &wim->out_fd,
1539                                  write_resource_flags,
1540                                  out_ctype,
1541                                  out_chunk_size,
1542                                  num_threads,
1543                                  wim->lookup_table,
1544                                  filter_ctx,
1545                                  progress_func);
1546 }
1547
1548 static int
1549 write_wim_resource(struct wim_lookup_table_entry *lte,
1550                    struct filedes *out_fd,
1551                    int out_ctype,
1552                    u32 out_chunk_size,
1553                    int write_resource_flags)
1554 {
1555         LIST_HEAD(stream_list);
1556         list_add(&lte->write_streams_list, &stream_list);
1557         lte->will_be_in_output_wim = 1;
1558         return write_stream_list(&stream_list,
1559                                  out_fd,
1560                                  write_resource_flags & ~WRITE_RESOURCE_FLAG_PACK_STREAMS,
1561                                  out_ctype,
1562                                  out_chunk_size,
1563                                  1,
1564                                  NULL,
1565                                  NULL,
1566                                  NULL);
1567 }
1568
1569 int
1570 write_wim_resource_from_buffer(const void *buf, size_t buf_size,
1571                                int reshdr_flags, struct filedes *out_fd,
1572                                int out_ctype,
1573                                u32 out_chunk_size,
1574                                struct wim_reshdr *out_reshdr,
1575                                u8 *hash,
1576                                int write_resource_flags)
1577 {
1578         int ret;
1579         struct wim_lookup_table_entry *lte;
1580
1581         /* Set up a temporary lookup table entry to provide to
1582          * write_wim_resource().  */
1583
1584         lte = new_lookup_table_entry();
1585         if (lte == NULL)
1586                 return WIMLIB_ERR_NOMEM;
1587
1588         lte->resource_location  = RESOURCE_IN_ATTACHED_BUFFER;
1589         lte->attached_buffer    = (void*)buf;
1590         lte->size               = buf_size;
1591         lte->flags              = reshdr_flags;
1592
1593         if (write_resource_flags & WRITE_RESOURCE_FLAG_PIPABLE) {
1594                 sha1_buffer(buf, buf_size, lte->hash);
1595                 lte->unhashed = 0;
1596         } else {
1597                 lte->unhashed = 1;
1598         }
1599
1600         ret = write_wim_resource(lte, out_fd, out_ctype, out_chunk_size,
1601                                  write_resource_flags);
1602         if (ret)
1603                 goto out_free_lte;
1604
1605         copy_reshdr(out_reshdr, &lte->out_reshdr);
1606
1607         if (hash)
1608                 copy_hash(hash, lte->hash);
1609         ret = 0;
1610 out_free_lte:
1611         lte->resource_location = RESOURCE_NONEXISTENT;
1612         free_lookup_table_entry(lte);
1613         return ret;
1614 }
1615
1616 struct stream_size_table {
1617         struct hlist_head *array;
1618         size_t num_entries;
1619         size_t capacity;
1620 };
1621
1622 static int
1623 init_stream_size_table(struct stream_size_table *tab, size_t capacity)
1624 {
1625         tab->array = CALLOC(capacity, sizeof(tab->array[0]));
1626         if (tab->array == NULL)
1627                 return WIMLIB_ERR_NOMEM;
1628         tab->num_entries = 0;
1629         tab->capacity = capacity;
1630         return 0;
1631 }
1632
1633 static void
1634 destroy_stream_size_table(struct stream_size_table *tab)
1635 {
1636         FREE(tab->array);
1637 }
1638
1639 static int
1640 stream_size_table_insert(struct wim_lookup_table_entry *lte, void *_tab)
1641 {
1642         struct stream_size_table *tab = _tab;
1643         size_t pos;
1644         struct wim_lookup_table_entry *same_size_lte;
1645         struct hlist_node *tmp;
1646
1647         pos = hash_u64(lte->size) % tab->capacity;
1648         lte->unique_size = 1;
1649         hlist_for_each_entry(same_size_lte, tmp, &tab->array[pos], hash_list_2) {
1650                 if (same_size_lte->size == lte->size) {
1651                         lte->unique_size = 0;
1652                         same_size_lte->unique_size = 0;
1653                         break;
1654                 }
1655         }
1656
1657         hlist_add_head(&lte->hash_list_2, &tab->array[pos]);
1658         tab->num_entries++;
1659         return 0;
1660 }
1661
1662 struct find_streams_ctx {
1663         WIMStruct *wim;
1664         int write_flags;
1665         struct list_head stream_list;
1666         struct stream_size_table stream_size_tab;
1667 };
1668
1669 static void
1670 reference_stream_for_write(struct wim_lookup_table_entry *lte,
1671                            struct list_head *stream_list, u32 nref)
1672 {
1673         if (!lte->will_be_in_output_wim) {
1674                 lte->out_refcnt = 0;
1675                 list_add_tail(&lte->write_streams_list, stream_list);
1676                 lte->will_be_in_output_wim = 1;
1677         }
1678         lte->out_refcnt += nref;
1679 }
1680
1681 static int
1682 fully_reference_stream_for_write(struct wim_lookup_table_entry *lte,
1683                                  void *_stream_list)
1684 {
1685         struct list_head *stream_list = _stream_list;
1686         lte->will_be_in_output_wim = 0;
1687         reference_stream_for_write(lte, stream_list, lte->refcnt);
1688         return 0;
1689 }
1690
1691 static int
1692 inode_find_streams_to_reference(const struct wim_inode *inode,
1693                                 const struct wim_lookup_table *table,
1694                                 struct list_head *stream_list)
1695 {
1696         struct wim_lookup_table_entry *lte;
1697         unsigned i;
1698
1699         wimlib_assert(inode->i_nlink > 0);
1700
1701         for (i = 0; i <= inode->i_num_ads; i++) {
1702                 lte = inode_stream_lte(inode, i, table);
1703                 if (lte)
1704                         reference_stream_for_write(lte, stream_list,
1705                                                    inode->i_nlink);
1706                 else if (!is_zero_hash(inode_stream_hash(inode, i)))
1707                         return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1708         }
1709         return 0;
1710 }
1711
1712 static int
1713 do_stream_set_not_in_output_wim(struct wim_lookup_table_entry *lte, void *_ignore)
1714 {
1715         lte->will_be_in_output_wim = 0;
1716         return 0;
1717 }
1718
1719 static int
1720 image_find_streams_to_reference(WIMStruct *wim)
1721 {
1722         struct wim_image_metadata *imd;
1723         struct wim_inode *inode;
1724         struct wim_lookup_table_entry *lte;
1725         struct list_head *stream_list;
1726         int ret;
1727
1728         imd = wim_get_current_image_metadata(wim);
1729
1730         image_for_each_unhashed_stream(lte, imd)
1731                 lte->will_be_in_output_wim = 0;
1732
1733         stream_list = wim->private;
1734         image_for_each_inode(inode, imd) {
1735                 ret = inode_find_streams_to_reference(inode,
1736                                                       wim->lookup_table,
1737                                                       stream_list);
1738                 if (ret)
1739                         return ret;
1740         }
1741         return 0;
1742 }
1743
1744 static int
1745 prepare_unfiltered_list_of_streams_in_output_wim(WIMStruct *wim,
1746                                                  int image,
1747                                                  int streams_ok,
1748                                                  struct list_head *stream_list_ret)
1749 {
1750         int ret;
1751
1752         INIT_LIST_HEAD(stream_list_ret);
1753
1754         if (streams_ok && (image == WIMLIB_ALL_IMAGES ||
1755                            (image == 1 && wim->hdr.image_count == 1)))
1756         {
1757                 /* Fast case:  Assume that all streams are being written and
1758                  * that the reference counts are correct.  */
1759                 struct wim_lookup_table_entry *lte;
1760                 struct wim_image_metadata *imd;
1761                 unsigned i;
1762
1763                 for_lookup_table_entry(wim->lookup_table,
1764                                        fully_reference_stream_for_write,
1765                                        stream_list_ret);
1766
1767                 for (i = 0; i < wim->hdr.image_count; i++) {
1768                         imd = wim->image_metadata[i];
1769                         image_for_each_unhashed_stream(lte, imd)
1770                                 fully_reference_stream_for_write(lte, stream_list_ret);
1771                 }
1772         } else {
1773                 /* Slow case:  Walk through the images being written and
1774                  * determine the streams referenced.  */
1775                 for_lookup_table_entry(wim->lookup_table,
1776                                        do_stream_set_not_in_output_wim, NULL);
1777                 wim->private = stream_list_ret;
1778                 ret = for_image(wim, image, image_find_streams_to_reference);
1779                 if (ret)
1780                         return ret;
1781         }
1782
1783         return 0;
1784 }
1785
1786 struct insert_other_if_hard_filtered_ctx {
1787         struct stream_size_table *tab;
1788         struct filter_context *filter_ctx;
1789 };
1790
1791 static int
1792 insert_other_if_hard_filtered(struct wim_lookup_table_entry *lte, void *_ctx)
1793 {
1794         struct insert_other_if_hard_filtered_ctx *ctx = _ctx;
1795
1796         if (!lte->will_be_in_output_wim &&
1797             stream_hard_filtered(lte, ctx->filter_ctx))
1798                 stream_size_table_insert(lte, ctx->tab);
1799         return 0;
1800 }
1801
1802 static int
1803 determine_stream_size_uniquity(struct list_head *stream_list,
1804                                struct wim_lookup_table *lt,
1805                                struct filter_context *filter_ctx)
1806 {
1807         int ret;
1808         struct stream_size_table tab;
1809         struct wim_lookup_table_entry *lte;
1810
1811         ret = init_stream_size_table(&tab, lt->capacity);
1812         if (ret)
1813                 return ret;
1814
1815         if (may_hard_filter_streams(filter_ctx)) {
1816                 struct insert_other_if_hard_filtered_ctx ctx = {
1817                         .tab = &tab,
1818                         .filter_ctx = filter_ctx,
1819                 };
1820                 for_lookup_table_entry(lt, insert_other_if_hard_filtered, &ctx);
1821         }
1822
1823         list_for_each_entry(lte, stream_list, write_streams_list)
1824                 stream_size_table_insert(lte, &tab);
1825
1826         destroy_stream_size_table(&tab);
1827         return 0;
1828 }
1829
1830 static void
1831 filter_stream_list_for_write(struct list_head *stream_list,
1832                              struct filter_context *filter_ctx)
1833 {
1834         struct wim_lookup_table_entry *lte, *tmp;
1835
1836         list_for_each_entry_safe(lte, tmp,
1837                                  stream_list, write_streams_list)
1838         {
1839                 int status = stream_filtered(lte, filter_ctx);
1840
1841                 if (status == 0) {
1842                         /* Not filtered.  */
1843                         continue;
1844                 } else {
1845                         if (status > 0) {
1846                                 /* Soft filtered.  */
1847                         } else {
1848                                 /* Hard filtered.  */
1849                                 lte->will_be_in_output_wim = 0;
1850                                 list_del(&lte->lookup_table_list);
1851                         }
1852                         list_del(&lte->write_streams_list);
1853                 }
1854         }
1855 }
1856
1857 /*
1858  * prepare_stream_list_for_write() -
1859  *
1860  * Prepare the list of streams to write for writing a WIM containing the
1861  * specified image(s) with the specified write flags.
1862  *
1863  * @wim
1864  *      The WIMStruct on whose behalf the write is occurring.
1865  *
1866  * @image
1867  *      Image(s) from the WIM to write; may be WIMLIB_ALL_IMAGES.
1868  *
1869  * @write_flags
1870  *      WIMLIB_WRITE_FLAG_* flags for the write operation:
1871  *
1872  *      STREAMS_OK:  For writes of all images, assume that all streams in the
1873  *      lookup table of @wim and the per-image lists of unhashed streams should
1874  *      be taken as-is, and image metadata should not be searched for
1875  *      references.  This does not exclude filtering with OVERWRITE and
1876  *      SKIP_EXTERNAL_WIMS, below.
1877  *
1878  *      OVERWRITE:  Streams already present in @wim shall not be returned in
1879  *      @stream_list_ret.
1880  *
1881  *      SKIP_EXTERNAL_WIMS:  Streams already present in a WIM file, but not
1882  *      @wim, shall be be returned in neither @stream_list_ret nor
1883  *      @lookup_table_list_ret.
1884  *
1885  * @stream_list_ret
1886  *      List of streams, linked by write_streams_list, that need to be written
1887  *      will be returned here.
1888  *
1889  *      Note that this function assumes that unhashed streams will be written;
1890  *      it does not take into account that they may become duplicates when
1891  *      actually hashed.
1892  *
1893  * @lookup_table_list_ret
1894  *      List of streams, linked by lookup_table_list, that need to be included
1895  *      in the WIM's lookup table will be returned here.  This will be a
1896  *      superset of the streams in @stream_list_ret.
1897  *
1898  *      This list will be a proper superset of @stream_list_ret if and only if
1899  *      WIMLIB_WRITE_FLAG_OVERWRITE was specified in @write_flags and some of
1900  *      the streams that would otherwise need to be written were already located
1901  *      in the WIM file.
1902  *
1903  *      All streams in this list will have @out_refcnt set to the number of
1904  *      references to the stream in the output WIM.  If
1905  *      WIMLIB_WRITE_FLAG_STREAMS_OK was specified in @write_flags, @out_refcnt
1906  *      may be as low as 0.
1907  *
1908  * @filter_ctx_ret
1909  *      A context for queries of stream filter status with stream_filtered() is
1910  *      returned in this location.
1911  *
1912  * In addition, @will_be_in_output_wim will be set to 1 in all stream entries
1913  * inserted into @lookup_table_list_ret and to 0 in all stream entries in the
1914  * lookup table of @wim not inserted into @lookup_table_list_ret.
1915  *
1916  * Still furthermore, @unique_size will be set to 1 on all stream entries in
1917  * @stream_list_ret that have unique size among all stream entries in
1918  * @stream_list_ret and among all stream entries in the lookup table of @wim
1919  * that are ineligible for being written due to filtering.
1920  *
1921  * Returns 0 on success; nonzero on read error, memory allocation error, or
1922  * otherwise.
1923  */
1924 static int
1925 prepare_stream_list_for_write(WIMStruct *wim, int image,
1926                               int write_flags,
1927                               struct list_head *stream_list_ret,
1928                               struct list_head *lookup_table_list_ret,
1929                               struct filter_context *filter_ctx_ret)
1930 {
1931         int ret;
1932         struct wim_lookup_table_entry *lte;
1933
1934         filter_ctx_ret->write_flags = write_flags;
1935         filter_ctx_ret->wim = wim;
1936
1937         ret = prepare_unfiltered_list_of_streams_in_output_wim(
1938                                 wim,
1939                                 image,
1940                                 write_flags & WIMLIB_WRITE_FLAG_STREAMS_OK,
1941                                 stream_list_ret);
1942         if (ret)
1943                 return ret;
1944
1945         INIT_LIST_HEAD(lookup_table_list_ret);
1946         list_for_each_entry(lte, stream_list_ret, write_streams_list)
1947                 list_add_tail(&lte->lookup_table_list, lookup_table_list_ret);
1948
1949         ret = determine_stream_size_uniquity(stream_list_ret, wim->lookup_table,
1950                                              filter_ctx_ret);
1951         if (ret)
1952                 return ret;
1953
1954         if (may_filter_streams(filter_ctx_ret))
1955                 filter_stream_list_for_write(stream_list_ret, filter_ctx_ret);
1956
1957         return 0;
1958 }
1959
1960 static int
1961 write_wim_streams(WIMStruct *wim, int image, int write_flags,
1962                   unsigned num_threads,
1963                   wimlib_progress_func_t progress_func,
1964                   struct list_head *stream_list_override,
1965                   struct list_head *lookup_table_list_ret)
1966 {
1967         int ret;
1968         struct list_head _stream_list;
1969         struct list_head *stream_list;
1970         struct wim_lookup_table_entry *lte;
1971         struct filter_context _filter_ctx;
1972         struct filter_context *filter_ctx;
1973
1974         if (stream_list_override == NULL) {
1975                 /* Normal case: prepare stream list from image(s) being written.
1976                  */
1977                 stream_list = &_stream_list;
1978                 filter_ctx = &_filter_ctx;
1979                 ret = prepare_stream_list_for_write(wim, image, write_flags,
1980                                                     stream_list,
1981                                                     lookup_table_list_ret,
1982                                                     filter_ctx);
1983                 if (ret)
1984                         return ret;
1985         } else {
1986                 /* Currently only as a result of wimlib_split() being called:
1987                  * use stream list already explicitly provided.  Use existing
1988                  * reference counts.  */
1989                 stream_list = stream_list_override;
1990                 filter_ctx = NULL;
1991                 INIT_LIST_HEAD(lookup_table_list_ret);
1992                 list_for_each_entry(lte, stream_list, write_streams_list) {
1993                         lte->out_refcnt = lte->refcnt;
1994                         lte->will_be_in_output_wim = 1;
1995                         lte->unique_size = 0;
1996                         list_add_tail(&lte->lookup_table_list, lookup_table_list_ret);
1997                 }
1998         }
1999
2000         return wim_write_stream_list(wim,
2001                                      stream_list,
2002                                      write_flags,
2003                                      num_threads,
2004                                      filter_ctx,
2005                                      progress_func);
2006 }
2007
2008 static int
2009 write_wim_metadata_resources(WIMStruct *wim, int image, int write_flags,
2010                              wimlib_progress_func_t progress_func)
2011 {
2012         int ret;
2013         int start_image;
2014         int end_image;
2015         int write_resource_flags;
2016
2017         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA) {
2018                 DEBUG("Not writing any metadata resources.");
2019                 return 0;
2020         }
2021
2022         write_resource_flags = write_flags_to_resource_flags(write_flags);
2023
2024         write_resource_flags &= ~WRITE_RESOURCE_FLAG_PACK_STREAMS;
2025
2026         DEBUG("Writing metadata resources (offset=%"PRIu64")",
2027               wim->out_fd.offset);
2028
2029         if (progress_func)
2030                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_BEGIN, NULL);
2031
2032         if (image == WIMLIB_ALL_IMAGES) {
2033                 start_image = 1;
2034                 end_image = wim->hdr.image_count;
2035         } else {
2036                 start_image = image;
2037                 end_image = image;
2038         }
2039
2040         for (int i = start_image; i <= end_image; i++) {
2041                 struct wim_image_metadata *imd;
2042
2043                 imd = wim->image_metadata[i - 1];
2044                 /* Build a new metadata resource only if image was modified from
2045                  * the original (or was newly added).  Otherwise just copy the
2046                  * existing one.  */
2047                 if (imd->modified) {
2048                         DEBUG("Image %u was modified; building and writing new "
2049                               "metadata resource", i);
2050                         ret = write_metadata_resource(wim, i,
2051                                                       write_resource_flags);
2052                 } else if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2053                         DEBUG("Image %u was not modified; re-using existing "
2054                               "metadata resource.", i);
2055                         stream_set_out_reshdr_for_reuse(imd->metadata_lte);
2056                         ret = 0;
2057                 } else {
2058                         DEBUG("Image %u was not modified; copying existing "
2059                               "metadata resource.", i);
2060                         ret = write_wim_resource(imd->metadata_lte,
2061                                                  &wim->out_fd,
2062                                                  wim->out_compression_type,
2063                                                  wim->out_chunk_size,
2064                                                  write_resource_flags);
2065                 }
2066                 if (ret)
2067                         return ret;
2068         }
2069         if (progress_func)
2070                 progress_func(WIMLIB_PROGRESS_MSG_WRITE_METADATA_END, NULL);
2071         return 0;
2072 }
2073
2074 static int
2075 open_wim_writable(WIMStruct *wim, const tchar *path, int open_flags)
2076 {
2077         int raw_fd;
2078         DEBUG("Opening \"%"TS"\" for writing.", path);
2079
2080         raw_fd = topen(path, open_flags | O_BINARY, 0644);
2081         if (raw_fd < 0) {
2082                 ERROR_WITH_ERRNO("Failed to open \"%"TS"\" for writing", path);
2083                 return WIMLIB_ERR_OPEN;
2084         }
2085         filedes_init(&wim->out_fd, raw_fd);
2086         return 0;
2087 }
2088
2089 static int
2090 close_wim_writable(WIMStruct *wim, int write_flags)
2091 {
2092         int ret = 0;
2093
2094         if (!(write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)) {
2095                 DEBUG("Closing WIM file.");
2096                 if (filedes_valid(&wim->out_fd))
2097                         if (filedes_close(&wim->out_fd))
2098                                 ret = WIMLIB_ERR_WRITE;
2099         }
2100         filedes_invalidate(&wim->out_fd);
2101         return ret;
2102 }
2103
2104 static int
2105 cmp_streams_by_out_rspec(const void *p1, const void *p2)
2106 {
2107         const struct wim_lookup_table_entry *lte1, *lte2;
2108
2109         lte1 = *(const struct wim_lookup_table_entry**)p1;
2110         lte2 = *(const struct wim_lookup_table_entry**)p2;
2111
2112         if (lte1->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2113                 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
2114                         if (lte1->out_res_offset_in_wim != lte2->out_res_offset_in_wim)
2115                                 return cmp_u64(lte1->out_res_offset_in_wim,
2116                                                lte2->out_res_offset_in_wim);
2117                 } else {
2118                         return 1;
2119                 }
2120         } else {
2121                 if (lte2->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
2122                         return -1;
2123         }
2124         return cmp_u64(lte1->out_reshdr.offset_in_wim,
2125                        lte2->out_reshdr.offset_in_wim);
2126 }
2127
2128 static int
2129 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
2130                        struct wim_reshdr *out_reshdr,
2131                        struct list_head *lookup_table_list)
2132 {
2133         int ret;
2134
2135         /* Set output resource metadata for streams already present in WIM.  */
2136         if (write_flags & WIMLIB_WRITE_FLAG_OVERWRITE) {
2137                 struct wim_lookup_table_entry *lte;
2138                 list_for_each_entry(lte, lookup_table_list, lookup_table_list)
2139                 {
2140                         if (lte->resource_location == RESOURCE_IN_WIM &&
2141                             lte->rspec->wim == wim)
2142                         {
2143                                 stream_set_out_reshdr_for_reuse(lte);
2144                         }
2145                 }
2146         }
2147
2148         ret = sort_stream_list(lookup_table_list,
2149                                offsetof(struct wim_lookup_table_entry, lookup_table_list),
2150                                cmp_streams_by_out_rspec);
2151         if (ret)
2152                 return ret;
2153
2154         /* Add entries for metadata resources.  */
2155         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
2156                 int start_image;
2157                 int end_image;
2158
2159                 if (image == WIMLIB_ALL_IMAGES) {
2160                         start_image = 1;
2161                         end_image = wim->hdr.image_count;
2162                 } else {
2163                         start_image = image;
2164                         end_image = image;
2165                 }
2166
2167                 /* Push metadata resource lookup table entries onto the front of
2168                  * the list in reverse order, so that they're written in order.
2169                  */
2170                 for (int i = end_image; i >= start_image; i--) {
2171                         struct wim_lookup_table_entry *metadata_lte;
2172
2173                         metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
2174                         wimlib_assert(metadata_lte->out_reshdr.flags & WIM_RESHDR_FLAG_METADATA);
2175                         metadata_lte->out_refcnt = 1;
2176                         list_add(&metadata_lte->lookup_table_list, lookup_table_list);
2177                 }
2178         }
2179
2180         return write_wim_lookup_table_from_stream_list(lookup_table_list,
2181                                                        &wim->out_fd,
2182                                                        wim->hdr.part_number,
2183                                                        out_reshdr,
2184                                                        write_flags_to_resource_flags(write_flags));
2185 }
2186
2187 /*
2188  * finish_write():
2189  *
2190  * Finish writing a WIM file: write the lookup table, xml data, and integrity
2191  * table, then overwrite the WIM header.  By default, closes the WIM file
2192  * descriptor (@wim->out_fd) if successful.
2193  *
2194  * write_flags is a bitwise OR of the following:
2195  *
2196  *      (public) WIMLIB_WRITE_FLAG_CHECK_INTEGRITY:
2197  *              Include an integrity table.
2198  *
2199  *      (public) WIMLIB_WRITE_FLAG_FSYNC:
2200  *              fsync() the output file before closing it.
2201  *
2202  *      (public) WIMLIB_WRITE_FLAG_PIPABLE:
2203  *              Writing a pipable WIM, possibly to a pipe; include pipable WIM
2204  *              stream headers before the lookup table and XML data, and also
2205  *              write the WIM header at the end instead of seeking to the
2206  *              beginning.  Can't be combined with
2207  *              WIMLIB_WRITE_FLAG_CHECK_INTEGRITY.
2208  *
2209  *      (private) WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE:
2210  *              Don't write the lookup table.
2211  *
2212  *      (private) WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE:
2213  *              When (if) writing the integrity table, re-use entries from the
2214  *              existing integrity table, if possible.
2215  *
2216  *      (private) WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML:
2217  *              After writing the XML data but before writing the integrity
2218  *              table, write a temporary WIM header and flush the stream so that
2219  *              the WIM is less likely to become corrupted upon abrupt program
2220  *              termination.
2221  *      (private) WIMLIB_WRITE_FLAG_HEADER_AT_END:
2222  *              Instead of overwriting the WIM header at the beginning of the
2223  *              file, simply append it to the end of the file.  (Used when
2224  *              writing to pipe.)
2225  *      (private) WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR:
2226  *              Do not close the file descriptor @wim->out_fd on either success
2227  *              on failure.
2228  *      (private) WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES:
2229  *              Use the existing <TOTALBYTES> stored in the in-memory XML
2230  *              information, rather than setting it to the offset of the XML
2231  *              data being written.
2232  */
2233 static int
2234 finish_write(WIMStruct *wim, int image, int write_flags,
2235              wimlib_progress_func_t progress_func,
2236              struct list_head *lookup_table_list)
2237 {
2238         int ret;
2239         off_t hdr_offset;
2240         int write_resource_flags;
2241         off_t old_lookup_table_end;
2242         off_t new_lookup_table_end;
2243         u64 xml_totalbytes;
2244
2245         DEBUG("image=%d, write_flags=%08x", image, write_flags);
2246
2247         write_resource_flags = write_flags_to_resource_flags(write_flags);
2248
2249         /* In the WIM header, there is room for the resource entry for a
2250          * metadata resource labeled as the "boot metadata".  This entry should
2251          * be zeroed out if there is no bootable image (boot_idx 0).  Otherwise,
2252          * it should be a copy of the resource entry for the image that is
2253          * marked as bootable.  This is not well documented...  */
2254         if (wim->hdr.boot_idx == 0) {
2255                 zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2256         } else {
2257                 copy_reshdr(&wim->hdr.boot_metadata_reshdr,
2258                             &wim->image_metadata[
2259                                 wim->hdr.boot_idx - 1]->metadata_lte->out_reshdr);
2260         }
2261
2262         /* Write lookup table.  (Save old position first.)  */
2263         old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2264                                wim->hdr.lookup_table_reshdr.size_in_wim;
2265         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
2266                 ret = write_wim_lookup_table(wim, image, write_flags,
2267                                              &wim->hdr.lookup_table_reshdr,
2268                                              lookup_table_list);
2269                 if (ret)
2270                         return ret;
2271         }
2272
2273         /* Write XML data.  */
2274         xml_totalbytes = wim->out_fd.offset;
2275         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2276                 xml_totalbytes = WIM_TOTALBYTES_USE_EXISTING;
2277         ret = write_wim_xml_data(wim, image, xml_totalbytes,
2278                                  &wim->hdr.xml_data_reshdr,
2279                                  write_resource_flags);
2280         if (ret)
2281                 return ret;
2282
2283         /* Write integrity table (optional).  */
2284         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2285                 if (write_flags & WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) {
2286                         struct wim_header checkpoint_hdr;
2287                         memcpy(&checkpoint_hdr, &wim->hdr, sizeof(struct wim_header));
2288                         zero_reshdr(&checkpoint_hdr.integrity_table_reshdr);
2289                         checkpoint_hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2290                         ret = write_wim_header_at_offset(&checkpoint_hdr,
2291                                                          &wim->out_fd, 0);
2292                         if (ret)
2293                                 return ret;
2294                 }
2295
2296                 if (!(write_flags & WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE))
2297                         old_lookup_table_end = 0;
2298
2299                 new_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2300                                        wim->hdr.lookup_table_reshdr.size_in_wim;
2301
2302                 ret = write_integrity_table(wim,
2303                                             new_lookup_table_end,
2304                                             old_lookup_table_end,
2305                                             progress_func);
2306                 if (ret)
2307                         return ret;
2308         } else {
2309                 /* No integrity table.  */
2310                 zero_reshdr(&wim->hdr.integrity_table_reshdr);
2311         }
2312
2313         /* Now that all information in the WIM header has been determined, the
2314          * preliminary header written earlier can be overwritten, the header of
2315          * the existing WIM file can be overwritten, or the final header can be
2316          * written to the end of the pipable WIM.  */
2317         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2318         hdr_offset = 0;
2319         if (write_flags & WIMLIB_WRITE_FLAG_HEADER_AT_END)
2320                 hdr_offset = wim->out_fd.offset;
2321         DEBUG("Writing new header @ %"PRIu64".", hdr_offset);
2322         ret = write_wim_header_at_offset(&wim->hdr, &wim->out_fd, hdr_offset);
2323         if (ret)
2324                 return ret;
2325
2326         /* Possibly sync file data to disk before closing.  On POSIX systems, it
2327          * is necessary to do this before using rename() to overwrite an
2328          * existing file with a new file.  Otherwise, data loss would occur if
2329          * the system is abruptly terminated when the metadata for the rename
2330          * operation has been written to disk, but the new file data has not.
2331          */
2332         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC) {
2333                 DEBUG("Syncing WIM file.");
2334                 if (fsync(wim->out_fd.fd)) {
2335                         ERROR_WITH_ERRNO("Error syncing data to WIM file");
2336                         return WIMLIB_ERR_WRITE;
2337                 }
2338         }
2339
2340         if (close_wim_writable(wim, write_flags)) {
2341                 ERROR_WITH_ERRNO("Failed to close the output WIM file");
2342                 return WIMLIB_ERR_WRITE;
2343         }
2344
2345         return 0;
2346 }
2347
2348 #if defined(HAVE_SYS_FILE_H) && defined(HAVE_FLOCK)
2349 int
2350 lock_wim(WIMStruct *wim, int fd)
2351 {
2352         int ret = 0;
2353         if (fd != -1 && !wim->wim_locked) {
2354                 ret = flock(fd, LOCK_EX | LOCK_NB);
2355                 if (ret != 0) {
2356                         if (errno == EWOULDBLOCK) {
2357                                 ERROR("`%"TS"' is already being modified or has been "
2358                                       "mounted read-write\n"
2359                                       "        by another process!", wim->filename);
2360                                 ret = WIMLIB_ERR_ALREADY_LOCKED;
2361                         } else {
2362                                 WARNING_WITH_ERRNO("Failed to lock `%"TS"'",
2363                                                    wim->filename);
2364                                 ret = 0;
2365                         }
2366                 } else {
2367                         wim->wim_locked = 1;
2368                 }
2369         }
2370         return ret;
2371 }
2372 #endif
2373
2374 /*
2375  * write_pipable_wim():
2376  *
2377  * Perform the intermediate stages of creating a "pipable" WIM (i.e. a WIM
2378  * capable of being applied from a pipe).
2379  *
2380  * Pipable WIMs are a wimlib-specific modification of the WIM format such that
2381  * images can be applied from them sequentially when the file data is sent over
2382  * a pipe.  In addition, a pipable WIM can be written sequentially to a pipe.
2383  * The modifications made to the WIM format for pipable WIMs are:
2384  *
2385  * - Magic characters in header are "WLPWM\0\0\0" (wimlib pipable WIM) instead
2386  *   of "MSWIM\0\0\0".  This lets wimlib know that the WIM is pipable and also
2387  *   stops other software from trying to read the file as a normal WIM.
2388  *
2389  * - The header at the beginning of the file does not contain all the normal
2390  *   information; in particular it will have all 0's for the lookup table and
2391  *   XML data resource entries.  This is because this information cannot be
2392  *   determined until the lookup table and XML data have been written.
2393  *   Consequently, wimlib will write the full header at the very end of the
2394  *   file.  The header at the end, however, is only used when reading the WIM
2395  *   from a seekable file (not a pipe).
2396  *
2397  * - An extra copy of the XML data is placed directly after the header.  This
2398  *   allows image names and sizes to be determined at an appropriate time when
2399  *   reading the WIM from a pipe.  This copy of the XML data is ignored if the
2400  *   WIM is read from a seekable file (not a pipe).
2401  *
2402  * - The format of resources, or streams, has been modified to allow them to be
2403  *   used before the "lookup table" has been read.  Each stream is prefixed with
2404  *   a `struct pwm_stream_hdr' that is basically an abbreviated form of `struct
2405  *   wim_lookup_table_entry_disk' that only contains the SHA1 message digest,
2406  *   uncompressed stream size, and flags that indicate whether the stream is
2407  *   compressed.  The data of uncompressed streams then follows literally, while
2408  *   the data of compressed streams follows in a modified format.  Compressed
2409  *   streams do not begin with a chunk table, since the chunk table cannot be
2410  *   written until all chunks have been compressed.  Instead, each compressed
2411  *   chunk is prefixed by a `struct pwm_chunk_hdr' that gives its size.
2412  *   Furthermore, the chunk table is written at the end of the resource instead
2413  *   of the start.  Note: chunk offsets are given in the chunk table as if the
2414  *   `struct pwm_chunk_hdr's were not present; also, the chunk table is only
2415  *   used if the WIM is being read from a seekable file (not a pipe).
2416  *
2417  * - Metadata resources always come before other file resources (streams).
2418  *   (This does not by itself constitute an incompatibility with normal WIMs,
2419  *   since this is valid in normal WIMs.)
2420  *
2421  * - At least up to the end of the file resources, all components must be packed
2422  *   as tightly as possible; there cannot be any "holes" in the WIM.  (This does
2423  *   not by itself consititute an incompatibility with normal WIMs, since this
2424  *   is valid in normal WIMs.)
2425  *
2426  * Note: the lookup table, XML data, and header at the end are not used when
2427  * applying from a pipe.  They exist to support functionality such as image
2428  * application and export when the WIM is *not* read from a pipe.
2429  *
2430  *   Layout of pipable WIM:
2431  *
2432  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2433  * | Header | XML data | Metadata resources | File resources | Lookup table | XML data  | Header |
2434  * ---------+----------+--------------------+----------------+--------------+-----------+--------+
2435  *
2436  *   Layout of normal WIM:
2437  *
2438  * +--------+-----------------------------+-------------------------+
2439  * | Header | File and metadata resources | Lookup table | XML data |
2440  * +--------+-----------------------------+-------------------------+
2441  *
2442  * An optional integrity table can follow the final XML data in both normal and
2443  * pipable WIMs.  However, due to implementation details, wimlib currently can
2444  * only include an integrity table in a pipable WIM when writing it to a
2445  * seekable file (not a pipe).
2446  *
2447  * Do note that since pipable WIMs are not supported by Microsoft's software,
2448  * wimlib does not create them unless explicitly requested (with
2449  * WIMLIB_WRITE_FLAG_PIPABLE) and as stated above they use different magic
2450  * characters to identify the file.
2451  */
2452 static int
2453 write_pipable_wim(WIMStruct *wim, int image, int write_flags,
2454                   unsigned num_threads, wimlib_progress_func_t progress_func,
2455                   struct list_head *stream_list_override,
2456                   struct list_head *lookup_table_list_ret)
2457 {
2458         int ret;
2459         struct wim_reshdr xml_reshdr;
2460
2461         WARNING("Creating a pipable WIM, which will "
2462                 "be incompatible\n"
2463                 "          with Microsoft's software (wimgapi/imagex/Dism).");
2464
2465         /* At this point, the header at the beginning of the file has already
2466          * been written.  */
2467
2468         /* For efficiency, when wimlib adds an image to the WIM with
2469          * wimlib_add_image(), the SHA1 message digests of files is not
2470          * calculated; instead, they are calculated while the files are being
2471          * written.  However, this does not work when writing a pipable WIM,
2472          * since when writing a stream to a pipable WIM, its SHA1 message digest
2473          * needs to be known before the stream data is written.  Therefore,
2474          * before getting much farther, we need to pre-calculate the SHA1
2475          * message digests of all streams that will be written.  */
2476         ret = wim_checksum_unhashed_streams(wim);
2477         if (ret)
2478                 return ret;
2479
2480         /* Write extra copy of the XML data.  */
2481         ret = write_wim_xml_data(wim, image, WIM_TOTALBYTES_OMIT,
2482                                  &xml_reshdr,
2483                                  WRITE_RESOURCE_FLAG_PIPABLE);
2484         if (ret)
2485                 return ret;
2486
2487         /* Write metadata resources for the image(s) being included in the
2488          * output WIM.  */
2489         ret = write_wim_metadata_resources(wim, image, write_flags,
2490                                            progress_func);
2491         if (ret)
2492                 return ret;
2493
2494         /* Write streams needed for the image(s) being included in the output
2495          * WIM, or streams needed for the split WIM part.  */
2496         return write_wim_streams(wim, image, write_flags, num_threads,
2497                                  progress_func, stream_list_override,
2498                                  lookup_table_list_ret);
2499
2500         /* The lookup table, XML data, and header at end are handled by
2501          * finish_write().  */
2502 }
2503
2504 /* Write a standalone WIM or split WIM (SWM) part to a new file or to a file
2505  * descriptor.  */
2506 int
2507 write_wim_part(WIMStruct *wim,
2508                const void *path_or_fd,
2509                int image,
2510                int write_flags,
2511                unsigned num_threads,
2512                wimlib_progress_func_t progress_func,
2513                unsigned part_number,
2514                unsigned total_parts,
2515                struct list_head *stream_list_override,
2516                const u8 *guid)
2517 {
2518         int ret;
2519         struct wim_header hdr_save;
2520         struct list_head lookup_table_list;
2521
2522         if (total_parts == 1)
2523                 DEBUG("Writing standalone WIM.");
2524         else
2525                 DEBUG("Writing split WIM part %u/%u", part_number, total_parts);
2526         if (image == WIMLIB_ALL_IMAGES)
2527                 DEBUG("Including all images.");
2528         else
2529                 DEBUG("Including image %d only.", image);
2530         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2531                 DEBUG("File descriptor: %d", *(const int*)path_or_fd);
2532         else
2533                 DEBUG("Path: \"%"TS"\"", (const tchar*)path_or_fd);
2534         DEBUG("Write flags: 0x%08x", write_flags);
2535
2536         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY)
2537                 DEBUG("\tCHECK_INTEGRITY");
2538
2539         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
2540                 DEBUG("\tREBUILD");
2541
2542         if (write_flags & WIMLIB_WRITE_FLAG_RECOMPRESS)
2543                 DEBUG("\tRECOMPRESS");
2544
2545         if (write_flags & WIMLIB_WRITE_FLAG_FSYNC)
2546                 DEBUG("\tFSYNC");
2547
2548         if (write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE)
2549                 DEBUG("\tFSYNC");
2550
2551         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
2552                 DEBUG("\tIGNORE_READONLY_FLAG");
2553
2554         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2555                 DEBUG("\tPIPABLE");
2556
2557         if (write_flags & WIMLIB_WRITE_FLAG_NOT_PIPABLE)
2558                 DEBUG("\tNOT_PIPABLE");
2559
2560         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2561                 DEBUG("\tPACK_STREAMS");
2562
2563         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
2564                 DEBUG("\tFILE_DESCRIPTOR");
2565
2566         if (write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)
2567                 DEBUG("\tNO_METADATA");
2568
2569         if (write_flags & WIMLIB_WRITE_FLAG_USE_EXISTING_TOTALBYTES)
2570                 DEBUG("\tUSE_EXISTING_TOTALBYTES");
2571
2572         if (num_threads == 0)
2573                 DEBUG("Number of threads: autodetect");
2574         else
2575                 DEBUG("Number of threads: %u", num_threads);
2576         DEBUG("Progress function: %s", (progress_func ? "yes" : "no"));
2577         DEBUG("Stream list:       %s", (stream_list_override ? "specified" : "autodetect"));
2578         DEBUG("GUID:              %s", ((guid || wim->guid_set_explicitly) ?
2579                                         "specified" : "generate new"));
2580
2581         /* Internally, this is always called with a valid part number and total
2582          * parts.  */
2583         wimlib_assert(total_parts >= 1);
2584         wimlib_assert(part_number >= 1 && part_number <= total_parts);
2585
2586         /* A valid image (or all images) must be specified.  */
2587         if (image != WIMLIB_ALL_IMAGES &&
2588              (image < 1 || image > wim->hdr.image_count))
2589                 return WIMLIB_ERR_INVALID_IMAGE;
2590
2591         /* If we need to write metadata resources, make sure the ::WIMStruct has
2592          * the needed information attached (e.g. is not a resource-only WIM,
2593          * such as a non-first part of a split WIM).  */
2594         if (!wim_has_metadata(wim) &&
2595             !(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA))
2596                 return WIMLIB_ERR_METADATA_NOT_FOUND;
2597
2598         /* Check for contradictory flags.  */
2599         if ((write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2600                             WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2601                                 == (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2602                                     WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY))
2603                 return WIMLIB_ERR_INVALID_PARAM;
2604
2605         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2606                             WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2607                                 == (WIMLIB_WRITE_FLAG_PIPABLE |
2608                                     WIMLIB_WRITE_FLAG_NOT_PIPABLE))
2609                 return WIMLIB_ERR_INVALID_PARAM;
2610
2611         /* Save previous header, then start initializing the new one.  */
2612         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2613
2614         /* Set default integrity, pipable, and packed stream flags.  */
2615         if (!(write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2616                              WIMLIB_WRITE_FLAG_NOT_PIPABLE)))
2617                 if (wim_is_pipable(wim)) {
2618                         DEBUG("WIM is pipable; default to PIPABLE.");
2619                         write_flags |= WIMLIB_WRITE_FLAG_PIPABLE;
2620                 }
2621
2622         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2623                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2624                 if (wim_has_integrity_table(wim)) {
2625                         DEBUG("Integrity table present; default to CHECK_INTEGRITY.");
2626                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2627                 }
2628
2629         if ((write_flags & (WIMLIB_WRITE_FLAG_PIPABLE |
2630                             WIMLIB_WRITE_FLAG_PACK_STREAMS))
2631                                     == (WIMLIB_WRITE_FLAG_PIPABLE |
2632                                         WIMLIB_WRITE_FLAG_PACK_STREAMS))
2633         {
2634                 ERROR("Cannot specify both PIPABLE and PACK_STREAMS!");
2635                 return WIMLIB_ERR_INVALID_PARAM;
2636         }
2637
2638         /* Set appropriate magic number.  */
2639         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
2640                 wim->hdr.magic = PWM_MAGIC;
2641         else
2642                 wim->hdr.magic = WIM_MAGIC;
2643
2644         /* Set appropriate version number.  */
2645         if ((write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS) ||
2646             wim->out_compression_type == WIMLIB_COMPRESSION_TYPE_LZMS)
2647                 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2648         else
2649                 wim->hdr.wim_version = WIM_VERSION_DEFAULT;
2650
2651         /* Clear header flags that will be set automatically.  */
2652         wim->hdr.flags &= ~(WIM_HDR_FLAG_METADATA_ONLY          |
2653                             WIM_HDR_FLAG_RESOURCE_ONLY          |
2654                             WIM_HDR_FLAG_SPANNED                |
2655                             WIM_HDR_FLAG_WRITE_IN_PROGRESS);
2656
2657         /* Set SPANNED header flag if writing part of a split WIM.  */
2658         if (total_parts != 1)
2659                 wim->hdr.flags |= WIM_HDR_FLAG_SPANNED;
2660
2661         /* Set part number and total parts of split WIM.  This will be 1 and 1
2662          * if the WIM is standalone.  */
2663         wim->hdr.part_number = part_number;
2664         wim->hdr.total_parts = total_parts;
2665
2666         /* Set compression type if different.  */
2667         if (wim->compression_type != wim->out_compression_type) {
2668                 ret = set_wim_hdr_cflags(wim->out_compression_type, &wim->hdr);
2669                 wimlib_assert(ret == 0);
2670         }
2671
2672         /* Set chunk size if different.  */
2673         wim->hdr.chunk_size = wim->out_chunk_size;
2674
2675         /* Use GUID if specified; otherwise generate a new one.  */
2676         if (guid)
2677                 memcpy(wim->hdr.guid, guid, WIMLIB_GUID_LEN);
2678         else if (!wim->guid_set_explicitly)
2679                 randomize_byte_array(wim->hdr.guid, WIMLIB_GUID_LEN);
2680
2681         /* Clear references to resources that have not been written yet.  */
2682         zero_reshdr(&wim->hdr.lookup_table_reshdr);
2683         zero_reshdr(&wim->hdr.xml_data_reshdr);
2684         zero_reshdr(&wim->hdr.boot_metadata_reshdr);
2685         zero_reshdr(&wim->hdr.integrity_table_reshdr);
2686
2687         /* Set image count and boot index correctly for single image writes.  */
2688         if (image != WIMLIB_ALL_IMAGES) {
2689                 wim->hdr.image_count = 1;
2690                 if (wim->hdr.boot_idx == image)
2691                         wim->hdr.boot_idx = 1;
2692                 else
2693                         wim->hdr.boot_idx = 0;
2694         }
2695
2696         /* Split WIMs can't be bootable.  */
2697         if (total_parts != 1)
2698                 wim->hdr.boot_idx = 0;
2699
2700         /* Initialize output file descriptor.  */
2701         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR) {
2702                 /* File descriptor was explicitly provided.  Return error if
2703                  * file descriptor is not seekable, unless writing a pipable WIM
2704                  * was requested.  */
2705                 wim->out_fd.fd = *(const int*)path_or_fd;
2706                 wim->out_fd.offset = 0;
2707                 if (!filedes_is_seekable(&wim->out_fd)) {
2708                         ret = WIMLIB_ERR_INVALID_PARAM;
2709                         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2710                                 goto out_restore_hdr;
2711                         if (write_flags & WIMLIB_WRITE_FLAG_CHECK_INTEGRITY) {
2712                                 ERROR("Can't include integrity check when "
2713                                       "writing pipable WIM to pipe!");
2714                                 goto out_restore_hdr;
2715                         }
2716                 }
2717
2718         } else {
2719                 /* Filename of WIM to write was provided; open file descriptor
2720                  * to it.  */
2721                 ret = open_wim_writable(wim, (const tchar*)path_or_fd,
2722                                         O_TRUNC | O_CREAT | O_RDWR);
2723                 if (ret)
2724                         goto out_restore_hdr;
2725         }
2726
2727         /* Write initial header.  This is merely a "dummy" header since it
2728          * doesn't have all the information yet, so it will be overwritten later
2729          * (unless writing a pipable WIM).  */
2730         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
2731                 wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2732         ret = write_wim_header(&wim->hdr, &wim->out_fd);
2733         wim->hdr.flags &= ~WIM_HDR_FLAG_WRITE_IN_PROGRESS;
2734         if (ret)
2735                 goto out_restore_hdr;
2736
2737         /* Write metadata resources and streams.  */
2738         if (!(write_flags & WIMLIB_WRITE_FLAG_PIPABLE)) {
2739                 /* Default case: create a normal (non-pipable) WIM.  */
2740                 ret = write_wim_streams(wim, image, write_flags, num_threads,
2741                                         progress_func, stream_list_override,
2742                                         &lookup_table_list);
2743                 if (ret)
2744                         goto out_restore_hdr;
2745
2746                 ret = write_wim_metadata_resources(wim, image, write_flags,
2747                                                    progress_func);
2748                 if (ret)
2749                         goto out_restore_hdr;
2750         } else {
2751                 /* Non-default case: create pipable WIM.  */
2752                 ret = write_pipable_wim(wim, image, write_flags, num_threads,
2753                                         progress_func, stream_list_override,
2754                                         &lookup_table_list);
2755                 if (ret)
2756                         goto out_restore_hdr;
2757                 write_flags |= WIMLIB_WRITE_FLAG_HEADER_AT_END;
2758         }
2759
2760
2761         /* Write lookup table, XML data, and (optional) integrity table.  */
2762         ret = finish_write(wim, image, write_flags, progress_func,
2763                            &lookup_table_list);
2764 out_restore_hdr:
2765         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
2766         (void)close_wim_writable(wim, write_flags);
2767         DEBUG("ret=%d", ret);
2768         return ret;
2769 }
2770
2771 /* Write a standalone WIM to a file or file descriptor.  */
2772 static int
2773 write_standalone_wim(WIMStruct *wim, const void *path_or_fd,
2774                      int image, int write_flags, unsigned num_threads,
2775                      wimlib_progress_func_t progress_func)
2776 {
2777         return write_wim_part(wim, path_or_fd, image, write_flags,
2778                               num_threads, progress_func, 1, 1, NULL, NULL);
2779 }
2780
2781 /* API function documented in wimlib.h  */
2782 WIMLIBAPI int
2783 wimlib_write(WIMStruct *wim, const tchar *path,
2784              int image, int write_flags, unsigned num_threads,
2785              wimlib_progress_func_t progress_func)
2786 {
2787         if (!path)
2788                 return WIMLIB_ERR_INVALID_PARAM;
2789
2790         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2791
2792         return write_standalone_wim(wim, path, image, write_flags,
2793                                     num_threads, progress_func);
2794 }
2795
2796 /* API function documented in wimlib.h  */
2797 WIMLIBAPI int
2798 wimlib_write_to_fd(WIMStruct *wim, int fd,
2799                    int image, int write_flags, unsigned num_threads,
2800                    wimlib_progress_func_t progress_func)
2801 {
2802         if (fd < 0)
2803                 return WIMLIB_ERR_INVALID_PARAM;
2804
2805         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
2806         write_flags |= WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR;
2807
2808         return write_standalone_wim(wim, &fd, image, write_flags,
2809                                     num_threads, progress_func);
2810 }
2811
2812 static bool
2813 any_images_modified(WIMStruct *wim)
2814 {
2815         for (int i = 0; i < wim->hdr.image_count; i++)
2816                 if (wim->image_metadata[i]->modified)
2817                         return true;
2818         return false;
2819 }
2820
2821 static int
2822 check_resource_offset(struct wim_lookup_table_entry *lte, void *_wim)
2823 {
2824         const WIMStruct *wim = _wim;
2825         off_t end_offset = *(const off_t*)wim->private;
2826
2827         if (lte->resource_location == RESOURCE_IN_WIM && lte->rspec->wim == wim &&
2828             lte->rspec->offset_in_wim + lte->rspec->size_in_wim > end_offset)
2829                 return WIMLIB_ERR_RESOURCE_ORDER;
2830         return 0;
2831 }
2832
2833 /* Make sure no file or metadata resources are located after the XML data (or
2834  * integrity table if present)--- otherwise we can't safely overwrite the WIM in
2835  * place and we return WIMLIB_ERR_RESOURCE_ORDER.  */
2836 static int
2837 check_resource_offsets(WIMStruct *wim, off_t end_offset)
2838 {
2839         int ret;
2840         unsigned i;
2841
2842         wim->private = &end_offset;
2843         ret = for_lookup_table_entry(wim->lookup_table, check_resource_offset, wim);
2844         if (ret)
2845                 return ret;
2846
2847         for (i = 0; i < wim->hdr.image_count; i++) {
2848                 ret = check_resource_offset(wim->image_metadata[i]->metadata_lte, wim);
2849                 if (ret)
2850                         return ret;
2851         }
2852         return 0;
2853 }
2854
2855 /*
2856  * Overwrite a WIM, possibly appending streams to it.
2857  *
2858  * A WIM looks like (or is supposed to look like) the following:
2859  *
2860  *                   Header (212 bytes)
2861  *                   Streams and metadata resources (variable size)
2862  *                   Lookup table (variable size)
2863  *                   XML data (variable size)
2864  *                   Integrity table (optional) (variable size)
2865  *
2866  * If we are not adding any streams or metadata resources, the lookup table is
2867  * unchanged--- so we only need to overwrite the XML data, integrity table, and
2868  * header.  This operation is potentially unsafe if the program is abruptly
2869  * terminated while the XML data or integrity table are being overwritten, but
2870  * before the new header has been written.  To partially alleviate this problem,
2871  * a special flag (WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML) is passed to
2872  * finish_write() to cause a temporary WIM header to be written after the XML
2873  * data has been written.  This may prevent the WIM from becoming corrupted if
2874  * the program is terminated while the integrity table is being calculated (but
2875  * no guarantees, due to write re-ordering...).
2876  *
2877  * If we are adding new streams or images (metadata resources), the lookup table
2878  * needs to be changed, and those streams need to be written.  In this case, we
2879  * try to perform a safe update of the WIM file by writing the streams *after*
2880  * the end of the previous WIM, then writing the new lookup table, XML data, and
2881  * (optionally) integrity table following the new streams.  This will produce a
2882  * layout like the following:
2883  *
2884  *                   Header (212 bytes)
2885  *                   (OLD) Streams and metadata resources (variable size)
2886  *                   (OLD) Lookup table (variable size)
2887  *                   (OLD) XML data (variable size)
2888  *                   (OLD) Integrity table (optional) (variable size)
2889  *                   (NEW) Streams and metadata resources (variable size)
2890  *                   (NEW) Lookup table (variable size)
2891  *                   (NEW) XML data (variable size)
2892  *                   (NEW) Integrity table (optional) (variable size)
2893  *
2894  * At all points, the WIM is valid as nothing points to the new data yet.  Then,
2895  * the header is overwritten to point to the new lookup table, XML data, and
2896  * integrity table, to produce the following layout:
2897  *
2898  *                   Header (212 bytes)
2899  *                   Streams and metadata resources (variable size)
2900  *                   Nothing (variable size)
2901  *                   More Streams and metadata resources (variable size)
2902  *                   Lookup table (variable size)
2903  *                   XML data (variable size)
2904  *                   Integrity table (optional) (variable size)
2905  *
2906  * This method allows an image to be appended to a large WIM very quickly, and
2907  * is is crash-safe except in the case of write re-ordering, but the
2908  * disadvantage is that a small hole is left in the WIM where the old lookup
2909  * table, xml data, and integrity table were.  (These usually only take up a
2910  * small amount of space compared to the streams, however.)
2911  */
2912 static int
2913 overwrite_wim_inplace(WIMStruct *wim, int write_flags,
2914                       unsigned num_threads,
2915                       wimlib_progress_func_t progress_func)
2916 {
2917         int ret;
2918         off_t old_wim_end;
2919         u64 old_lookup_table_end, old_xml_begin, old_xml_end;
2920         struct wim_header hdr_save;
2921         struct list_head stream_list;
2922         struct list_head lookup_table_list;
2923         struct filter_context filter_ctx;
2924
2925         DEBUG("Overwriting `%"TS"' in-place", wim->filename);
2926
2927         /* Save original header so it can be restored in case of error  */
2928         memcpy(&hdr_save, &wim->hdr, sizeof(struct wim_header));
2929
2930         /* Set default integrity flag.  */
2931         if (!(write_flags & (WIMLIB_WRITE_FLAG_CHECK_INTEGRITY |
2932                              WIMLIB_WRITE_FLAG_NO_CHECK_INTEGRITY)))
2933                 if (wim_has_integrity_table(wim))
2934                         write_flags |= WIMLIB_WRITE_FLAG_CHECK_INTEGRITY;
2935
2936         /* Set WIM version if adding packed streams.  */
2937         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS)
2938                 wim->hdr.wim_version = WIM_VERSION_PACKED_STREAMS;
2939
2940         /* Set additional flags for overwrite.  */
2941         write_flags |= WIMLIB_WRITE_FLAG_OVERWRITE |
2942                        WIMLIB_WRITE_FLAG_STREAMS_OK;
2943
2944         /* Make sure that the integrity table (if present) is after the XML
2945          * data, and that there are no stream resources, metadata resources, or
2946          * lookup tables after the XML data.  Otherwise, these data would be
2947          * overwritten. */
2948         old_xml_begin = wim->hdr.xml_data_reshdr.offset_in_wim;
2949         old_xml_end = old_xml_begin + wim->hdr.xml_data_reshdr.size_in_wim;
2950         old_lookup_table_end = wim->hdr.lookup_table_reshdr.offset_in_wim +
2951                                wim->hdr.lookup_table_reshdr.size_in_wim;
2952         if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0 &&
2953             wim->hdr.integrity_table_reshdr.offset_in_wim < old_xml_end) {
2954                 WARNING("Didn't expect the integrity table to be before the XML data");
2955                 ret = WIMLIB_ERR_RESOURCE_ORDER;
2956                 goto out_restore_memory_hdr;
2957         }
2958
2959         if (old_lookup_table_end > old_xml_begin) {
2960                 WARNING("Didn't expect the lookup table to be after the XML data");
2961                 ret = WIMLIB_ERR_RESOURCE_ORDER;
2962                 goto out_restore_memory_hdr;
2963         }
2964
2965         /* Set @old_wim_end, which indicates the point beyond which we don't
2966          * allow any file and metadata resources to appear without returning
2967          * WIMLIB_ERR_RESOURCE_ORDER (due to the fact that we would otherwise
2968          * overwrite these resources). */
2969         if (!wim->deletion_occurred && !any_images_modified(wim)) {
2970                 /* If no images have been modified and no images have been
2971                  * deleted, a new lookup table does not need to be written.  We
2972                  * shall write the new XML data and optional integrity table
2973                  * immediately after the lookup table.  Note that this may
2974                  * overwrite an existing integrity table. */
2975                 DEBUG("Skipping writing lookup table "
2976                       "(no images modified or deleted)");
2977                 old_wim_end = old_lookup_table_end;
2978                 write_flags |= WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE |
2979                                WIMLIB_WRITE_FLAG_CHECKPOINT_AFTER_XML;
2980         } else if (wim->hdr.integrity_table_reshdr.offset_in_wim != 0) {
2981                 /* Old WIM has an integrity table; begin writing new streams
2982                  * after it. */
2983                 old_wim_end = wim->hdr.integrity_table_reshdr.offset_in_wim +
2984                               wim->hdr.integrity_table_reshdr.size_in_wim;
2985         } else {
2986                 /* No existing integrity table; begin writing new streams after
2987                  * the old XML data. */
2988                 old_wim_end = old_xml_end;
2989         }
2990
2991         ret = check_resource_offsets(wim, old_wim_end);
2992         if (ret)
2993                 goto out_restore_memory_hdr;
2994
2995         ret = prepare_stream_list_for_write(wim, WIMLIB_ALL_IMAGES, write_flags,
2996                                             &stream_list, &lookup_table_list,
2997                                             &filter_ctx);
2998         if (ret)
2999                 goto out_restore_memory_hdr;
3000
3001         ret = open_wim_writable(wim, wim->filename, O_RDWR);
3002         if (ret)
3003                 goto out_restore_memory_hdr;
3004
3005         ret = lock_wim(wim, wim->out_fd.fd);
3006         if (ret)
3007                 goto out_close_wim;
3008
3009         /* Set WIM_HDR_FLAG_WRITE_IN_PROGRESS flag in header. */
3010         wim->hdr.flags |= WIM_HDR_FLAG_WRITE_IN_PROGRESS;
3011         ret = write_wim_header_flags(wim->hdr.flags, &wim->out_fd);
3012         if (ret) {
3013                 ERROR_WITH_ERRNO("Error updating WIM header flags");
3014                 goto out_unlock_wim;
3015         }
3016
3017         if (filedes_seek(&wim->out_fd, old_wim_end) == -1) {
3018                 ERROR_WITH_ERRNO("Can't seek to end of WIM");
3019                 ret = WIMLIB_ERR_WRITE;
3020                 goto out_restore_physical_hdr;
3021         }
3022
3023         ret = wim_write_stream_list(wim,
3024                                     &stream_list,
3025                                     write_flags,
3026                                     num_threads,
3027                                     &filter_ctx,
3028                                     progress_func);
3029         if (ret)
3030                 goto out_truncate;
3031
3032         ret = write_wim_metadata_resources(wim, WIMLIB_ALL_IMAGES,
3033                                            write_flags, progress_func);
3034         if (ret)
3035                 goto out_truncate;
3036
3037         write_flags |= WIMLIB_WRITE_FLAG_REUSE_INTEGRITY_TABLE;
3038         ret = finish_write(wim, WIMLIB_ALL_IMAGES, write_flags,
3039                            progress_func, &lookup_table_list);
3040         if (ret)
3041                 goto out_truncate;
3042
3043         wim->wim_locked = 0;
3044         return 0;
3045
3046 out_truncate:
3047         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_LOOKUP_TABLE)) {
3048                 WARNING("Truncating `%"TS"' to its original size (%"PRIu64" bytes)",
3049                         wim->filename, old_wim_end);
3050                 /* Return value of ftruncate() is ignored because this is
3051                  * already an error path.  */
3052                 (void)ftruncate(wim->out_fd.fd, old_wim_end);
3053         }
3054 out_restore_physical_hdr:
3055         (void)write_wim_header_flags(hdr_save.flags, &wim->out_fd);
3056 out_unlock_wim:
3057         wim->wim_locked = 0;
3058 out_close_wim:
3059         (void)close_wim_writable(wim, write_flags);
3060 out_restore_memory_hdr:
3061         memcpy(&wim->hdr, &hdr_save, sizeof(struct wim_header));
3062         return ret;
3063 }
3064
3065 static int
3066 overwrite_wim_via_tmpfile(WIMStruct *wim, int write_flags,
3067                           unsigned num_threads,
3068                           wimlib_progress_func_t progress_func)
3069 {
3070         size_t wim_name_len;
3071         int ret;
3072
3073         DEBUG("Overwriting `%"TS"' via a temporary file", wim->filename);
3074
3075         /* Write the WIM to a temporary file in the same directory as the
3076          * original WIM. */
3077         wim_name_len = tstrlen(wim->filename);
3078         tchar tmpfile[wim_name_len + 10];
3079         tmemcpy(tmpfile, wim->filename, wim_name_len);
3080         randomize_char_array_with_alnum(tmpfile + wim_name_len, 9);
3081         tmpfile[wim_name_len + 9] = T('\0');
3082
3083         ret = wimlib_write(wim, tmpfile, WIMLIB_ALL_IMAGES,
3084                            write_flags | WIMLIB_WRITE_FLAG_FSYNC,
3085                            num_threads, progress_func);
3086         if (ret) {
3087                 tunlink(tmpfile);
3088                 return ret;
3089         }
3090
3091         close_wim(wim);
3092
3093         /* Rename the new WIM file to the original WIM file.  Note: on Windows
3094          * this actually calls win32_rename_replacement(), not _wrename(), so
3095          * that removing the existing destination file can be handled.  */
3096         DEBUG("Renaming `%"TS"' to `%"TS"'", tmpfile, wim->filename);
3097         ret = trename(tmpfile, wim->filename);
3098         if (ret) {
3099                 ERROR_WITH_ERRNO("Failed to rename `%"TS"' to `%"TS"'",
3100                                  tmpfile, wim->filename);
3101         #ifdef __WIN32__
3102                 if (ret < 0)
3103         #endif
3104                 {
3105                         tunlink(tmpfile);
3106                 }
3107                 return WIMLIB_ERR_RENAME;
3108         }
3109
3110         if (progress_func) {
3111                 union wimlib_progress_info progress;
3112                 progress.rename.from = tmpfile;
3113                 progress.rename.to = wim->filename;
3114                 progress_func(WIMLIB_PROGRESS_MSG_RENAME, &progress);
3115         }
3116         return 0;
3117 }
3118
3119 /* Determine if the specified WIM file may be updated by appending in-place
3120  * rather than writing and replacing it with an entirely new file.  */
3121 static bool
3122 can_overwrite_wim_inplace(const WIMStruct *wim, int write_flags)
3123 {
3124         /* REBUILD flag forces full rebuild.  */
3125         if (write_flags & WIMLIB_WRITE_FLAG_REBUILD)
3126                 return false;
3127
3128         /* Deletions cause full rebuild by default.  */
3129         if (wim->deletion_occurred && !(write_flags & WIMLIB_WRITE_FLAG_SOFT_DELETE))
3130                 return false;
3131
3132         /* Pipable WIMs cannot be updated in place, nor can a non-pipable WIM be
3133          * turned into a pipable WIM in-place.  */
3134         if (wim_is_pipable(wim) || (write_flags & WIMLIB_WRITE_FLAG_PIPABLE))
3135                 return false;
3136
3137         /* wimlib allows multiple packs in a single WIM, but they don't seem to
3138          * be compatible with WIMGAPI, so force all streams to be repacked if
3139          * the WIM already may have contained a pack and PACK_STREAMS was
3140          * requested.  */
3141         if (write_flags & WIMLIB_WRITE_FLAG_PACK_STREAMS &&
3142             wim->hdr.wim_version == WIM_VERSION_PACKED_STREAMS)
3143                 return false;
3144
3145         /* The default compression type and compression chunk size selected for
3146          * the output WIM must be the same as those currently used for the WIM.
3147          */
3148         if (wim->compression_type != wim->out_compression_type)
3149                 return false;
3150         if (wim->chunk_size != wim->out_chunk_size)
3151                 return false;
3152
3153         return true;
3154 }
3155
3156 /* API function documented in wimlib.h  */
3157 WIMLIBAPI int
3158 wimlib_overwrite(WIMStruct *wim, int write_flags,
3159                  unsigned num_threads,
3160                  wimlib_progress_func_t progress_func)
3161 {
3162         int ret;
3163         u32 orig_hdr_flags;
3164
3165         write_flags &= WIMLIB_WRITE_MASK_PUBLIC;
3166
3167         if (write_flags & WIMLIB_WRITE_FLAG_FILE_DESCRIPTOR)
3168                 return WIMLIB_ERR_INVALID_PARAM;
3169
3170         if (!wim->filename)
3171                 return WIMLIB_ERR_NO_FILENAME;
3172
3173         orig_hdr_flags = wim->hdr.flags;
3174         if (write_flags & WIMLIB_WRITE_FLAG_IGNORE_READONLY_FLAG)
3175                 wim->hdr.flags &= ~WIM_HDR_FLAG_READONLY;
3176         ret = can_modify_wim(wim);
3177         wim->hdr.flags = orig_hdr_flags;
3178         if (ret)
3179                 return ret;
3180
3181         if (can_overwrite_wim_inplace(wim, write_flags)) {
3182                 ret = overwrite_wim_inplace(wim, write_flags, num_threads,
3183                                             progress_func);
3184                 if (ret != WIMLIB_ERR_RESOURCE_ORDER)
3185                         return ret;
3186                 WARNING("Falling back to re-building entire WIM");
3187         }
3188         return overwrite_wim_via_tmpfile(wim, write_flags, num_threads,
3189                                          progress_func);
3190 }