]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - SQUASHFS/squashfs-tools-4.4/squashfs-tools/mksquashfs.c
1.0.72 release
[Ventoy.git] / SQUASHFS / squashfs-tools-4.4 / squashfs-tools / mksquashfs.c
1 /*
2 * Create a squashfs filesystem. This is a highly compressed read only
3 * filesystem.
4 *
5 * Copyright (c) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011,
6 * 2012, 2013, 2014, 2017, 2019
7 * Phillip Lougher <phillip@squashfs.org.uk>
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2,
12 * or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 *
23 * mksquashfs.c
24 */
25
26 #define FALSE 0
27 #define TRUE 1
28 #define MAX_LINE 16384
29
30 #include <pwd.h>
31 #include <grp.h>
32 #include <time.h>
33 #include <unistd.h>
34 #include <stdio.h>
35 #include <stddef.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/sysmacros.h>
39 #include <fcntl.h>
40 #include <errno.h>
41 #include <dirent.h>
42 #include <string.h>
43 #include <stdlib.h>
44 #include <signal.h>
45 #include <setjmp.h>
46 #include <sys/types.h>
47 #include <sys/mman.h>
48 #include <pthread.h>
49 #include <regex.h>
50 #include <sys/wait.h>
51 #include <limits.h>
52 #include <ctype.h>
53 #include <sys/sysinfo.h>
54
55 #ifndef linux
56 #define __BYTE_ORDER BYTE_ORDER
57 #define __BIG_ENDIAN BIG_ENDIAN
58 #define __LITTLE_ENDIAN LITTLE_ENDIAN
59 #include <sys/sysctl.h>
60 #else
61 #include <endian.h>
62 #include <sys/sysinfo.h>
63 #endif
64
65 #include "squashfs_fs.h"
66 #include "squashfs_swap.h"
67 #include "mksquashfs.h"
68 #include "sort.h"
69 #include "pseudo.h"
70 #include "compressor.h"
71 #include "xattr.h"
72 #include "action.h"
73 #include "error.h"
74 #include "progressbar.h"
75 #include "info.h"
76 #include "caches-queues-lists.h"
77 #include "read_fs.h"
78 #include "restore.h"
79 #include "process_fragments.h"
80 #include "fnmatch_compat.h"
81
82 int delete = FALSE;
83 int quiet = FALSE;
84 int fd;
85 struct squashfs_super_block sBlk;
86
87 /* filesystem flags for building */
88 int comp_opts = FALSE;
89 int no_xattrs = XATTR_DEF;
90 int noX = FALSE;
91 int duplicate_checking = TRUE;
92 int noF = FALSE;
93 int no_fragments = FALSE;
94 int always_use_fragments = FALSE;
95 int noI = FALSE;
96 int noId = FALSE;
97 int noD = FALSE;
98 int silent = TRUE;
99 int exportable = TRUE;
100 int sparse_files = TRUE;
101 int old_exclude = TRUE;
102 int use_regex = FALSE;
103 int nopad = FALSE;
104 int exit_on_error = FALSE;
105 long long start_offset = 0;
106
107 long long global_uid = -1, global_gid = -1;
108
109 /* superblock attributes */
110 int block_size = SQUASHFS_FILE_SIZE, block_log;
111 unsigned int id_count = 0;
112 int file_count = 0, sym_count = 0, dev_count = 0, dir_count = 0, fifo_count = 0,
113 sock_count = 0;
114
115 /* write position within data section */
116 long long bytes = 0, total_bytes = 0;
117
118 /* in memory directory table - possibly compressed */
119 char *directory_table = NULL;
120 unsigned int directory_bytes = 0, directory_size = 0, total_directory_bytes = 0;
121
122 /* cached directory table */
123 char *directory_data_cache = NULL;
124 unsigned int directory_cache_bytes = 0, directory_cache_size = 0;
125
126 /* in memory inode table - possibly compressed */
127 char *inode_table = NULL;
128 unsigned int inode_bytes = 0, inode_size = 0, total_inode_bytes = 0;
129
130 /* cached inode table */
131 char *data_cache = NULL;
132 unsigned int cache_bytes = 0, cache_size = 0, inode_count = 0;
133
134 /* inode lookup table */
135 squashfs_inode *inode_lookup_table = NULL;
136
137 /* in memory directory data */
138 #define I_COUNT_SIZE 128
139 #define DIR_ENTRIES 32
140 #define INODE_HASH_SIZE 65536
141 #define INODE_HASH_MASK (INODE_HASH_SIZE - 1)
142 #define INODE_HASH(dev, ino) (ino & INODE_HASH_MASK)
143
144 struct cached_dir_index {
145 struct squashfs_dir_index index;
146 char *name;
147 };
148
149 struct directory {
150 unsigned int start_block;
151 unsigned int size;
152 unsigned char *buff;
153 unsigned char *p;
154 unsigned int entry_count;
155 unsigned char *entry_count_p;
156 unsigned int i_count;
157 unsigned int i_size;
158 struct cached_dir_index *index;
159 unsigned char *index_count_p;
160 unsigned int inode_number;
161 };
162
163 struct inode_info *inode_info[INODE_HASH_SIZE];
164
165 /* hash tables used to do fast duplicate searches in duplicate check */
166 struct file_info *dupl[65536];
167 int dup_files = 0;
168
169 /* exclude file handling */
170 /* list of exclude dirs/files */
171 struct exclude_info {
172 dev_t st_dev;
173 ino_t st_ino;
174 };
175
176 #define EXCLUDE_SIZE 8192
177 int exclude = 0;
178 struct exclude_info *exclude_paths = NULL;
179 int old_excluded(char *filename, struct stat *buf);
180
181 struct path_entry {
182 char *name;
183 regex_t *preg;
184 struct pathname *paths;
185 };
186
187 struct pathname {
188 int names;
189 struct path_entry *name;
190 };
191
192 struct pathnames {
193 int count;
194 struct pathname *path[0];
195 };
196 #define PATHS_ALLOC_SIZE 10
197
198 struct pathnames *paths = NULL;
199 struct pathname *path = NULL;
200 struct pathname *stickypath = NULL;
201 int excluded(char *name, struct pathnames *paths, struct pathnames **new);
202
203 int fragments = 0;
204
205 #define FRAG_SIZE 32768
206
207 struct squashfs_fragment_entry *fragment_table = NULL;
208 int fragments_outstanding = 0;
209
210 int fragments_locked = FALSE;
211
212 /* current inode number for directories and non directories */
213 unsigned int inode_no = 1;
214 unsigned int root_inode_number = 0;
215
216 /* list of source dirs/files */
217 int source = 0;
218 char **source_path;
219
220 /* list of root directory entries read from original filesystem */
221 int old_root_entries = 0;
222 struct old_root_entry_info {
223 char *name;
224 struct inode_info inode;
225 };
226 struct old_root_entry_info *old_root_entry;
227
228 /* restore orignal filesystem state if appending to existing filesystem is
229 * cancelled */
230 int appending = FALSE;
231 char *sdata_cache, *sdirectory_data_cache, *sdirectory_compressed;
232
233 long long sbytes, stotal_bytes;
234
235 unsigned int sinode_bytes, scache_bytes, sdirectory_bytes,
236 sdirectory_cache_bytes, sdirectory_compressed_bytes,
237 stotal_inode_bytes, stotal_directory_bytes,
238 sinode_count = 0, sfile_count, ssym_count, sdev_count,
239 sdir_count, sfifo_count, ssock_count, sdup_files;
240 int sfragments;
241 int threads;
242
243 /* flag whether destination file is a block device */
244 int block_device = FALSE;
245
246 /* flag indicating whether files are sorted using sort list(s) */
247 int sorted = FALSE;
248
249 /* save destination file name for deleting on error */
250 char *destination_file = NULL;
251
252 /* recovery file for abnormal exit on appending */
253 char *recovery_file = NULL;
254 int recover = TRUE;
255
256 struct id *id_hash_table[ID_ENTRIES];
257 struct id *id_table[SQUASHFS_IDS], *sid_table[SQUASHFS_IDS];
258 unsigned int uid_count = 0, guid_count = 0;
259 unsigned int sid_count = 0, suid_count = 0, sguid_count = 0;
260
261 struct cache *reader_buffer, *fragment_buffer, *reserve_cache;
262 struct cache *bwriter_buffer, *fwriter_buffer;
263 struct queue *to_reader, *to_deflate, *to_writer, *from_writer,
264 *to_frag, *locked_fragment, *to_process_frag;
265 struct seq_queue *to_main;
266 pthread_t reader_thread, writer_thread, main_thread;
267 pthread_t *deflator_thread, *frag_deflator_thread, *frag_thread;
268 pthread_t *restore_thread = NULL;
269 pthread_mutex_t fragment_mutex = PTHREAD_MUTEX_INITIALIZER;
270 pthread_mutex_t pos_mutex = PTHREAD_MUTEX_INITIALIZER;
271 pthread_mutex_t dup_mutex = PTHREAD_MUTEX_INITIALIZER;
272
273 /* reproducible image queues and threads */
274 struct seq_queue *to_order;
275 pthread_t order_thread;
276 pthread_cond_t fragment_waiting = PTHREAD_COND_INITIALIZER;
277
278 int reproducible = REP_DEF;
279
280 /* Root mode option */
281 int root_mode_opt = FALSE;
282 mode_t root_mode;
283
284 /* Time value over-ride options */
285 unsigned int mkfs_time;
286 int mkfs_time_opt = FALSE;
287
288 unsigned int all_time;
289 int all_time_opt = FALSE;
290 int clamping = TRUE;
291
292 /* user options that control parallelisation */
293 int processors = -1;
294 int bwriter_size;
295
296 /* compression operations */
297 struct compressor *comp = NULL;
298 int compressor_opt_parsed = FALSE;
299 void *stream = NULL;
300
301 /* xattr stats */
302 unsigned int xattr_bytes = 0, total_xattr_bytes = 0;
303
304 /* fragment to file mapping used when appending */
305 int append_fragments = 0;
306 struct append_file **file_mapping;
307
308 /* root of the in-core directory structure */
309 struct dir_info *root_dir;
310
311 /* log file */
312 FILE *log_fd;
313 int logging=FALSE;
314
315 static char *read_from_disk(long long start, unsigned int avail_bytes);
316 void add_old_root_entry(char *name, squashfs_inode inode, int inode_number,
317 int type);
318 struct file_info *duplicate(long long file_size, long long bytes,
319 unsigned int **block_list, long long *start, struct fragment **fragment,
320 struct file_buffer *file_buffer, int blocks, unsigned short checksum,
321 int checksum_flag);
322 struct dir_info *dir_scan1(char *, char *, struct pathnames *,
323 struct dir_ent *(_readdir)(struct dir_info *), int);
324 void dir_scan2(struct dir_info *dir, struct pseudo *pseudo);
325 void dir_scan3(struct dir_info *dir);
326 void dir_scan4(struct dir_info *dir);
327 void dir_scan5(struct dir_info *dir);
328 void dir_scan6(struct dir_info *dir);
329 void dir_scan7(squashfs_inode *inode, struct dir_info *dir_info);
330 struct file_info *add_non_dup(long long file_size, long long bytes,
331 unsigned int *block_list, long long start, struct fragment *fragment,
332 unsigned short checksum, unsigned short fragment_checksum,
333 int checksum_flag, int checksum_frag_flag);
334 long long generic_write_table(int, void *, int, void *, int);
335 void restorefs();
336 struct dir_info *scan1_opendir(char *pathname, char *subpath, int depth);
337 void write_filesystem_tables(struct squashfs_super_block *sBlk, int nopad);
338 unsigned short get_checksum_mem(char *buff, int bytes);
339 void check_usable_phys_mem(int total_mem);
340
341
342 void prep_exit()
343 {
344 if(restore_thread) {
345 if(pthread_self() == *restore_thread) {
346 /*
347 * Recursive failure when trying to restore filesystem!
348 * Nothing to do except to exit, otherwise we'll just
349 * appear to hang. The user should be able to restore
350 * from the recovery file (which is why it was added, in
351 * case of catastrophic failure in Mksquashfs)
352 */
353 exit(1);
354 } else {
355 /* signal the restore thread to restore */
356 pthread_kill(*restore_thread, SIGUSR1);
357 pthread_exit(NULL);
358 }
359 } else if(delete) {
360 if(destination_file && !block_device)
361 unlink(destination_file);
362 } else if(recovery_file)
363 unlink(recovery_file);
364 }
365
366
367 int add_overflow(int a, int b)
368 {
369 return (INT_MAX - a) < b;
370 }
371
372
373 int shift_overflow(int a, int shift)
374 {
375 return (INT_MAX >> shift) < a;
376 }
377
378
379 int multiply_overflow(int a, int multiplier)
380 {
381 return (INT_MAX / multiplier) < a;
382 }
383
384
385 int multiply_overflowll(long long a, int multiplier)
386 {
387 return (LLONG_MAX / multiplier) < a;
388 }
389
390
391 #define MKINODE(A) ((squashfs_inode)(((squashfs_inode) inode_bytes << 16) \
392 + (((char *)A) - data_cache)))
393
394
395 void restorefs()
396 {
397 ERROR("Exiting - restoring original filesystem!\n\n");
398
399 bytes = sbytes;
400 memcpy(data_cache, sdata_cache, cache_bytes = scache_bytes);
401 memcpy(directory_data_cache, sdirectory_data_cache,
402 sdirectory_cache_bytes);
403 directory_cache_bytes = sdirectory_cache_bytes;
404 inode_bytes = sinode_bytes;
405 directory_bytes = sdirectory_bytes;
406 memcpy(directory_table + directory_bytes, sdirectory_compressed,
407 sdirectory_compressed_bytes);
408 directory_bytes += sdirectory_compressed_bytes;
409 total_bytes = stotal_bytes;
410 total_inode_bytes = stotal_inode_bytes;
411 total_directory_bytes = stotal_directory_bytes;
412 inode_count = sinode_count;
413 file_count = sfile_count;
414 sym_count = ssym_count;
415 dev_count = sdev_count;
416 dir_count = sdir_count;
417 fifo_count = sfifo_count;
418 sock_count = ssock_count;
419 dup_files = sdup_files;
420 fragments = sfragments;
421 id_count = sid_count;
422 restore_xattrs();
423 write_filesystem_tables(&sBlk, nopad);
424 exit(1);
425 }
426
427
428 void sighandler()
429 {
430 EXIT_MKSQUASHFS();
431 }
432
433
434 int mangle2(void *strm, char *d, char *s, int size,
435 int block_size, int uncompressed, int data_block)
436 {
437 int error, c_byte = 0;
438
439 if(!uncompressed) {
440 c_byte = compressor_compress(comp, strm, d, s, size, block_size,
441 &error);
442 if(c_byte == -1)
443 BAD_ERROR("mangle2:: %s compress failed with error "
444 "code %d\n", comp->name, error);
445 }
446
447 if(c_byte == 0 || c_byte >= size) {
448 memcpy(d, s, size);
449 return size | (data_block ? SQUASHFS_COMPRESSED_BIT_BLOCK :
450 SQUASHFS_COMPRESSED_BIT);
451 }
452
453 return c_byte;
454 }
455
456
457 int mangle(char *d, char *s, int size, int block_size,
458 int uncompressed, int data_block)
459 {
460 return mangle2(stream, d, s, size, block_size, uncompressed,
461 data_block);
462 }
463
464
465 void *get_inode(int req_size)
466 {
467 int data_space;
468 unsigned short c_byte;
469
470 while(cache_bytes >= SQUASHFS_METADATA_SIZE) {
471 if((inode_size - inode_bytes) <
472 ((SQUASHFS_METADATA_SIZE << 1)) + 2) {
473 void *it = realloc(inode_table, inode_size +
474 (SQUASHFS_METADATA_SIZE << 1) + 2);
475 if(it == NULL)
476 MEM_ERROR();
477 inode_table = it;
478 inode_size += (SQUASHFS_METADATA_SIZE << 1) + 2;
479 }
480
481 c_byte = mangle(inode_table + inode_bytes + BLOCK_OFFSET,
482 data_cache, SQUASHFS_METADATA_SIZE,
483 SQUASHFS_METADATA_SIZE, noI, 0);
484 TRACE("Inode block @ 0x%x, size %d\n", inode_bytes, c_byte);
485 SQUASHFS_SWAP_SHORTS(&c_byte, inode_table + inode_bytes, 1);
486 inode_bytes += SQUASHFS_COMPRESSED_SIZE(c_byte) + BLOCK_OFFSET;
487 total_inode_bytes += SQUASHFS_METADATA_SIZE + BLOCK_OFFSET;
488 memmove(data_cache, data_cache + SQUASHFS_METADATA_SIZE,
489 cache_bytes - SQUASHFS_METADATA_SIZE);
490 cache_bytes -= SQUASHFS_METADATA_SIZE;
491 }
492
493 data_space = (cache_size - cache_bytes);
494 if(data_space < req_size) {
495 int realloc_size = cache_size == 0 ?
496 ((req_size + SQUASHFS_METADATA_SIZE) &
497 ~(SQUASHFS_METADATA_SIZE - 1)) : req_size -
498 data_space;
499
500 void *dc = realloc(data_cache, cache_size +
501 realloc_size);
502 if(dc == NULL)
503 MEM_ERROR();
504 cache_size += realloc_size;
505 data_cache = dc;
506 }
507
508 cache_bytes += req_size;
509
510 return data_cache + cache_bytes - req_size;
511 }
512
513
514 int read_bytes(int fd, void *buff, int bytes)
515 {
516 int res, count;
517
518 for(count = 0; count < bytes; count += res) {
519 res = read(fd, buff + count, bytes - count);
520 if(res < 1) {
521 if(res == 0)
522 goto bytes_read;
523 else if(errno != EINTR) {
524 ERROR("Read failed because %s\n",
525 strerror(errno));
526 return -1;
527 } else
528 res = 0;
529 }
530 }
531
532 bytes_read:
533 return count;
534 }
535
536
537 int read_fs_bytes(int fd, long long byte, int bytes, void *buff)
538 {
539 off_t off = byte;
540 int res = 1;
541
542 TRACE("read_fs_bytes: reading from position 0x%llx, bytes %d\n",
543 byte, bytes);
544
545 pthread_cleanup_push((void *) pthread_mutex_unlock, &pos_mutex);
546 pthread_mutex_lock(&pos_mutex);
547 if(lseek(fd, start_offset + off, SEEK_SET) == -1) {
548 ERROR("read_fs_bytes: Lseek on destination failed because %s, "
549 "offset=0x%llx\n", strerror(errno), start_offset + off);
550 res = 0;
551 } else if(read_bytes(fd, buff, bytes) < bytes) {
552 ERROR("Read on destination failed\n");
553 res = 0;
554 }
555
556 pthread_cleanup_pop(1);
557 return res;
558 }
559
560
561 int write_bytes(int fd, void *buff, int bytes)
562 {
563 int res, count;
564
565 for(count = 0; count < bytes; count += res) {
566 res = write(fd, buff + count, bytes - count);
567 if(res == -1) {
568 if(errno != EINTR) {
569 ERROR("Write failed because %s\n",
570 strerror(errno));
571 return -1;
572 }
573 res = 0;
574 }
575 }
576
577 return 0;
578 }
579
580
581 void write_destination(int fd, long long byte, int bytes, void *buff)
582 {
583 off_t off = byte;
584
585 pthread_cleanup_push((void *) pthread_mutex_unlock, &pos_mutex);
586 pthread_mutex_lock(&pos_mutex);
587
588 if(lseek(fd, start_offset + off, SEEK_SET) == -1) {
589 ERROR("write_destination: Lseek on destination "
590 "failed because %s, offset=0x%llx\n", strerror(errno),
591 start_offset + off);
592 BAD_ERROR("Probably out of space on output %s\n",
593 block_device ? "block device" : "filesystem");
594 }
595
596 if(write_bytes(fd, buff, bytes) == -1)
597 BAD_ERROR("Failed to write to output %s\n",
598 block_device ? "block device" : "filesystem");
599
600 pthread_cleanup_pop(1);
601 }
602
603
604 long long write_inodes()
605 {
606 unsigned short c_byte;
607 int avail_bytes;
608 char *datap = data_cache;
609 long long start_bytes = bytes;
610
611 while(cache_bytes) {
612 if(inode_size - inode_bytes <
613 ((SQUASHFS_METADATA_SIZE << 1) + 2)) {
614 void *it = realloc(inode_table, inode_size +
615 ((SQUASHFS_METADATA_SIZE << 1) + 2));
616 if(it == NULL)
617 MEM_ERROR();
618 inode_size += (SQUASHFS_METADATA_SIZE << 1) + 2;
619 inode_table = it;
620 }
621 avail_bytes = cache_bytes > SQUASHFS_METADATA_SIZE ?
622 SQUASHFS_METADATA_SIZE : cache_bytes;
623 c_byte = mangle(inode_table + inode_bytes + BLOCK_OFFSET, datap,
624 avail_bytes, SQUASHFS_METADATA_SIZE, noI, 0);
625 TRACE("Inode block @ 0x%x, size %d\n", inode_bytes, c_byte);
626 SQUASHFS_SWAP_SHORTS(&c_byte, inode_table + inode_bytes, 1);
627 inode_bytes += SQUASHFS_COMPRESSED_SIZE(c_byte) + BLOCK_OFFSET;
628 total_inode_bytes += avail_bytes + BLOCK_OFFSET;
629 datap += avail_bytes;
630 cache_bytes -= avail_bytes;
631 }
632
633 write_destination(fd, bytes, inode_bytes, inode_table);
634 bytes += inode_bytes;
635
636 return start_bytes;
637 }
638
639
640 long long write_directories()
641 {
642 unsigned short c_byte;
643 int avail_bytes;
644 char *directoryp = directory_data_cache;
645 long long start_bytes = bytes;
646
647 while(directory_cache_bytes) {
648 if(directory_size - directory_bytes <
649 ((SQUASHFS_METADATA_SIZE << 1) + 2)) {
650 void *dt = realloc(directory_table,
651 directory_size + ((SQUASHFS_METADATA_SIZE << 1)
652 + 2));
653 if(dt == NULL)
654 MEM_ERROR();
655 directory_size += (SQUASHFS_METADATA_SIZE << 1) + 2;
656 directory_table = dt;
657 }
658 avail_bytes = directory_cache_bytes > SQUASHFS_METADATA_SIZE ?
659 SQUASHFS_METADATA_SIZE : directory_cache_bytes;
660 c_byte = mangle(directory_table + directory_bytes +
661 BLOCK_OFFSET, directoryp, avail_bytes,
662 SQUASHFS_METADATA_SIZE, noI, 0);
663 TRACE("Directory block @ 0x%x, size %d\n", directory_bytes,
664 c_byte);
665 SQUASHFS_SWAP_SHORTS(&c_byte,
666 directory_table + directory_bytes, 1);
667 directory_bytes += SQUASHFS_COMPRESSED_SIZE(c_byte) +
668 BLOCK_OFFSET;
669 total_directory_bytes += avail_bytes + BLOCK_OFFSET;
670 directoryp += avail_bytes;
671 directory_cache_bytes -= avail_bytes;
672 }
673 write_destination(fd, bytes, directory_bytes, directory_table);
674 bytes += directory_bytes;
675
676 return start_bytes;
677 }
678
679
680 long long write_id_table()
681 {
682 unsigned int id_bytes = SQUASHFS_ID_BYTES(id_count);
683 unsigned int p[id_count];
684 int i;
685
686 TRACE("write_id_table: ids %d, id_bytes %d\n", id_count, id_bytes);
687 for(i = 0; i < id_count; i++) {
688 TRACE("write_id_table: id index %d, id %d", i, id_table[i]->id);
689 SQUASHFS_SWAP_INTS(&id_table[i]->id, p + i, 1);
690 }
691
692 return generic_write_table(id_bytes, p, 0, NULL, noI || noId);
693 }
694
695
696 struct id *get_id(unsigned int id)
697 {
698 int hash = ID_HASH(id);
699 struct id *entry = id_hash_table[hash];
700
701 for(; entry; entry = entry->next)
702 if(entry->id == id)
703 break;
704
705 return entry;
706 }
707
708
709 struct id *create_id(unsigned int id)
710 {
711 int hash = ID_HASH(id);
712 struct id *entry = malloc(sizeof(struct id));
713 if(entry == NULL)
714 MEM_ERROR();
715 entry->id = id;
716 entry->index = id_count ++;
717 entry->flags = 0;
718 entry->next = id_hash_table[hash];
719 id_hash_table[hash] = entry;
720 id_table[entry->index] = entry;
721 return entry;
722 }
723
724
725 unsigned int get_uid(unsigned int uid)
726 {
727 struct id *entry = get_id(uid);
728
729 if(entry == NULL) {
730 if(id_count == SQUASHFS_IDS)
731 BAD_ERROR("Out of uids!\n");
732 entry = create_id(uid);
733 }
734
735 if((entry->flags & ISA_UID) == 0) {
736 entry->flags |= ISA_UID;
737 uid_count ++;
738 }
739
740 return entry->index;
741 }
742
743
744 unsigned int get_guid(unsigned int guid)
745 {
746 struct id *entry = get_id(guid);
747
748 if(entry == NULL) {
749 if(id_count == SQUASHFS_IDS)
750 BAD_ERROR("Out of gids!\n");
751 entry = create_id(guid);
752 }
753
754 if((entry->flags & ISA_GID) == 0) {
755 entry->flags |= ISA_GID;
756 guid_count ++;
757 }
758
759 return entry->index;
760 }
761
762
763 #define ALLOC_SIZE 128
764
765 char *_pathname(struct dir_ent *dir_ent, char *pathname, int *size)
766 {
767 if(pathname == NULL) {
768 pathname = malloc(ALLOC_SIZE);
769 if(pathname == NULL)
770 MEM_ERROR();
771 }
772
773 for(;;) {
774 int res = snprintf(pathname, *size, "%s/%s",
775 dir_ent->our_dir->pathname,
776 dir_ent->source_name ? : dir_ent->name);
777
778 if(res < 0)
779 BAD_ERROR("snprintf failed in pathname\n");
780 else if(res >= *size) {
781 /*
782 * pathname is too small to contain the result, so
783 * increase it and try again
784 */
785 *size = (res + ALLOC_SIZE) & ~(ALLOC_SIZE - 1);
786 pathname = realloc(pathname, *size);
787 if(pathname == NULL)
788 MEM_ERROR();
789 } else
790 break;
791 }
792
793 return pathname;
794 }
795
796
797 char *pathname(struct dir_ent *dir_ent)
798 {
799 static char *pathname = NULL;
800 static int size = ALLOC_SIZE;
801
802 if (dir_ent->nonstandard_pathname)
803 return dir_ent->nonstandard_pathname;
804
805 return pathname = _pathname(dir_ent, pathname, &size);
806 }
807
808
809 char *pathname_reader(struct dir_ent *dir_ent)
810 {
811 static char *pathname = NULL;
812 static int size = ALLOC_SIZE;
813
814 if (dir_ent->nonstandard_pathname)
815 return dir_ent->nonstandard_pathname;
816
817 return pathname = _pathname(dir_ent, pathname, &size);
818 }
819
820
821 char *subpathname(struct dir_ent *dir_ent)
822 {
823 static char *subpath = NULL;
824 static int size = ALLOC_SIZE;
825 int res;
826
827 if(subpath == NULL) {
828 subpath = malloc(ALLOC_SIZE);
829 if(subpath == NULL)
830 MEM_ERROR();
831 }
832
833 for(;;) {
834 if(dir_ent->our_dir->subpath[0] != '\0')
835 res = snprintf(subpath, size, "%s/%s",
836 dir_ent->our_dir->subpath, dir_ent->name);
837 else
838 res = snprintf(subpath, size, "/%s", dir_ent->name);
839
840 if(res < 0)
841 BAD_ERROR("snprintf failed in subpathname\n");
842 else if(res >= size) {
843 /*
844 * subpath is too small to contain the result, so
845 * increase it and try again
846 */
847 size = (res + ALLOC_SIZE) & ~(ALLOC_SIZE - 1);
848 subpath = realloc(subpath, size);
849 if(subpath == NULL)
850 MEM_ERROR();
851 } else
852 break;
853 }
854
855 return subpath;
856 }
857
858
859 static inline unsigned int get_inode_no(struct inode_info *inode)
860 {
861 return inode->inode_number;
862 }
863
864
865 static inline unsigned int get_parent_no(struct dir_info *dir)
866 {
867 return dir->depth ? get_inode_no(dir->dir_ent->inode) : inode_no;
868 }
869
870
871 static inline time_t get_time(time_t time)
872 {
873 if(all_time_opt) {
874 if(clamping)
875 return time > all_time ? all_time : time;
876 else
877 return all_time;
878 }
879
880 return time;
881 }
882
883
884 int create_inode(squashfs_inode *i_no, struct dir_info *dir_info,
885 struct dir_ent *dir_ent, int type, long long byte_size,
886 long long start_block, unsigned int offset, unsigned int *block_list,
887 struct fragment *fragment, struct directory *dir_in, long long sparse)
888 {
889 struct stat *buf = &dir_ent->inode->buf;
890 union squashfs_inode_header inode_header;
891 struct squashfs_base_inode_header *base = &inode_header.base;
892 void *inode;
893 char *filename = pathname(dir_ent);
894 int nlink = dir_ent->inode->nlink;
895 int xattr = read_xattrs(dir_ent);
896
897 switch(type) {
898 case SQUASHFS_FILE_TYPE:
899 if(dir_ent->inode->nlink > 1 ||
900 byte_size >= (1LL << 32) ||
901 start_block >= (1LL << 32) ||
902 sparse || IS_XATTR(xattr))
903 type = SQUASHFS_LREG_TYPE;
904 break;
905 case SQUASHFS_DIR_TYPE:
906 if(dir_info->dir_is_ldir || IS_XATTR(xattr))
907 type = SQUASHFS_LDIR_TYPE;
908 break;
909 case SQUASHFS_SYMLINK_TYPE:
910 if(IS_XATTR(xattr))
911 type = SQUASHFS_LSYMLINK_TYPE;
912 break;
913 case SQUASHFS_BLKDEV_TYPE:
914 if(IS_XATTR(xattr))
915 type = SQUASHFS_LBLKDEV_TYPE;
916 break;
917 case SQUASHFS_CHRDEV_TYPE:
918 if(IS_XATTR(xattr))
919 type = SQUASHFS_LCHRDEV_TYPE;
920 break;
921 case SQUASHFS_FIFO_TYPE:
922 if(IS_XATTR(xattr))
923 type = SQUASHFS_LFIFO_TYPE;
924 break;
925 case SQUASHFS_SOCKET_TYPE:
926 if(IS_XATTR(xattr))
927 type = SQUASHFS_LSOCKET_TYPE;
928 break;
929 }
930
931 base->mode = SQUASHFS_MODE(buf->st_mode);
932 base->uid = get_uid((unsigned int) global_uid == -1 ?
933 buf->st_uid : global_uid);
934 base->inode_type = type;
935 base->guid = get_guid((unsigned int) global_gid == -1 ?
936 buf->st_gid : global_gid);
937 base->mtime = get_time(buf->st_mtime);
938 base->inode_number = get_inode_no(dir_ent->inode);
939
940 if(type == SQUASHFS_FILE_TYPE) {
941 int i;
942 struct squashfs_reg_inode_header *reg = &inode_header.reg;
943 size_t off = offsetof(struct squashfs_reg_inode_header, block_list);
944
945 inode = get_inode(sizeof(*reg) + offset * sizeof(unsigned int));
946 reg->file_size = byte_size;
947 reg->start_block = start_block;
948 reg->fragment = fragment->index;
949 reg->offset = fragment->offset;
950 SQUASHFS_SWAP_REG_INODE_HEADER(reg, inode);
951 SQUASHFS_SWAP_INTS(block_list, inode + off, offset);
952 TRACE("File inode, file_size %lld, start_block 0x%llx, blocks "
953 "%d, fragment %d, offset %d, size %d\n", byte_size,
954 start_block, offset, fragment->index, fragment->offset,
955 fragment->size);
956 for(i = 0; i < offset; i++)
957 TRACE("Block %d, size %d\n", i, block_list[i]);
958 }
959 else if(type == SQUASHFS_LREG_TYPE) {
960 int i;
961 struct squashfs_lreg_inode_header *reg = &inode_header.lreg;
962 size_t off = offsetof(struct squashfs_lreg_inode_header, block_list);
963
964 inode = get_inode(sizeof(*reg) + offset * sizeof(unsigned int));
965 reg->nlink = nlink;
966 reg->file_size = byte_size;
967 reg->start_block = start_block;
968 reg->fragment = fragment->index;
969 reg->offset = fragment->offset;
970 if(sparse && sparse >= byte_size)
971 sparse = byte_size - 1;
972 reg->sparse = sparse;
973 reg->xattr = xattr;
974 SQUASHFS_SWAP_LREG_INODE_HEADER(reg, inode);
975 SQUASHFS_SWAP_INTS(block_list, inode + off, offset);
976 TRACE("Long file inode, file_size %lld, start_block 0x%llx, "
977 "blocks %d, fragment %d, offset %d, size %d, nlink %d"
978 "\n", byte_size, start_block, offset, fragment->index,
979 fragment->offset, fragment->size, nlink);
980 for(i = 0; i < offset; i++)
981 TRACE("Block %d, size %d\n", i, block_list[i]);
982 }
983 else if(type == SQUASHFS_LDIR_TYPE) {
984 int i;
985 unsigned char *p;
986 struct squashfs_ldir_inode_header *dir = &inode_header.ldir;
987 struct cached_dir_index *index = dir_in->index;
988 unsigned int i_count = dir_in->i_count;
989 unsigned int i_size = dir_in->i_size;
990
991 if(byte_size >= 1 << 27)
992 BAD_ERROR("directory greater than 2^27-1 bytes!\n");
993
994 inode = get_inode(sizeof(*dir) + i_size);
995 dir->inode_type = SQUASHFS_LDIR_TYPE;
996 dir->nlink = dir_ent->dir->directory_count + 2;
997 dir->file_size = byte_size;
998 dir->offset = offset;
999 dir->start_block = start_block;
1000 dir->i_count = i_count;
1001 dir->parent_inode = get_parent_no(dir_ent->our_dir);
1002 dir->xattr = xattr;
1003
1004 SQUASHFS_SWAP_LDIR_INODE_HEADER(dir, inode);
1005 p = inode + offsetof(struct squashfs_ldir_inode_header, index);
1006 for(i = 0; i < i_count; i++) {
1007 SQUASHFS_SWAP_DIR_INDEX(&index[i].index, p);
1008 p += offsetof(struct squashfs_dir_index, name);
1009 memcpy(p, index[i].name, index[i].index.size + 1);
1010 p += index[i].index.size + 1;
1011 }
1012 TRACE("Long directory inode, file_size %lld, start_block "
1013 "0x%llx, offset 0x%x, nlink %d\n", byte_size,
1014 start_block, offset, dir_ent->dir->directory_count + 2);
1015 }
1016 else if(type == SQUASHFS_DIR_TYPE) {
1017 struct squashfs_dir_inode_header *dir = &inode_header.dir;
1018
1019 inode = get_inode(sizeof(*dir));
1020 dir->nlink = dir_ent->dir->directory_count + 2;
1021 dir->file_size = byte_size;
1022 dir->offset = offset;
1023 dir->start_block = start_block;
1024 dir->parent_inode = get_parent_no(dir_ent->our_dir);
1025 SQUASHFS_SWAP_DIR_INODE_HEADER(dir, inode);
1026 TRACE("Directory inode, file_size %lld, start_block 0x%llx, "
1027 "offset 0x%x, nlink %d\n", byte_size, start_block,
1028 offset, dir_ent->dir->directory_count + 2);
1029 }
1030 else if(type == SQUASHFS_CHRDEV_TYPE || type == SQUASHFS_BLKDEV_TYPE) {
1031 struct squashfs_dev_inode_header *dev = &inode_header.dev;
1032 unsigned int major = major(buf->st_rdev);
1033 unsigned int minor = minor(buf->st_rdev);
1034
1035 if(major > 0xfff) {
1036 ERROR("Major %d out of range in device node %s, "
1037 "truncating to %d\n", major, filename,
1038 major & 0xfff);
1039 major &= 0xfff;
1040 }
1041 if(minor > 0xfffff) {
1042 ERROR("Minor %d out of range in device node %s, "
1043 "truncating to %d\n", minor, filename,
1044 minor & 0xfffff);
1045 minor &= 0xfffff;
1046 }
1047 inode = get_inode(sizeof(*dev));
1048 dev->nlink = nlink;
1049 dev->rdev = (major << 8) | (minor & 0xff) |
1050 ((minor & ~0xff) << 12);
1051 SQUASHFS_SWAP_DEV_INODE_HEADER(dev, inode);
1052 TRACE("Device inode, rdev 0x%x, nlink %d\n", dev->rdev, nlink);
1053 }
1054 else if(type == SQUASHFS_LCHRDEV_TYPE || type == SQUASHFS_LBLKDEV_TYPE) {
1055 struct squashfs_ldev_inode_header *dev = &inode_header.ldev;
1056 unsigned int major = major(buf->st_rdev);
1057 unsigned int minor = minor(buf->st_rdev);
1058
1059 if(major > 0xfff) {
1060 ERROR("Major %d out of range in device node %s, "
1061 "truncating to %d\n", major, filename,
1062 major & 0xfff);
1063 major &= 0xfff;
1064 }
1065 if(minor > 0xfffff) {
1066 ERROR("Minor %d out of range in device node %s, "
1067 "truncating to %d\n", minor, filename,
1068 minor & 0xfffff);
1069 minor &= 0xfffff;
1070 }
1071 inode = get_inode(sizeof(*dev));
1072 dev->nlink = nlink;
1073 dev->rdev = (major << 8) | (minor & 0xff) |
1074 ((minor & ~0xff) << 12);
1075 dev->xattr = xattr;
1076 SQUASHFS_SWAP_LDEV_INODE_HEADER(dev, inode);
1077 TRACE("Device inode, rdev 0x%x, nlink %d\n", dev->rdev, nlink);
1078 }
1079 else if(type == SQUASHFS_SYMLINK_TYPE) {
1080 struct squashfs_symlink_inode_header *symlink = &inode_header.symlink;
1081 int byte = strlen(dir_ent->inode->symlink);
1082 size_t off = offsetof(struct squashfs_symlink_inode_header, symlink);
1083
1084 inode = get_inode(sizeof(*symlink) + byte);
1085 symlink->nlink = nlink;
1086 symlink->symlink_size = byte;
1087 SQUASHFS_SWAP_SYMLINK_INODE_HEADER(symlink, inode);
1088 strncpy(inode + off, dir_ent->inode->symlink, byte);
1089 TRACE("Symbolic link inode, symlink_size %d, nlink %d\n", byte,
1090 nlink);
1091 }
1092 else if(type == SQUASHFS_LSYMLINK_TYPE) {
1093 struct squashfs_symlink_inode_header *symlink = &inode_header.symlink;
1094 int byte = strlen(dir_ent->inode->symlink);
1095 size_t off = offsetof(struct squashfs_symlink_inode_header, symlink);
1096
1097 inode = get_inode(sizeof(*symlink) + byte +
1098 sizeof(unsigned int));
1099 symlink->nlink = nlink;
1100 symlink->symlink_size = byte;
1101 SQUASHFS_SWAP_SYMLINK_INODE_HEADER(symlink, inode);
1102 strncpy(inode + off, dir_ent->inode->symlink, byte);
1103 SQUASHFS_SWAP_INTS(&xattr, inode + off + byte, 1);
1104 TRACE("Symbolic link inode, symlink_size %d, nlink %d\n", byte,
1105 nlink);
1106 }
1107 else if(type == SQUASHFS_FIFO_TYPE || type == SQUASHFS_SOCKET_TYPE) {
1108 struct squashfs_ipc_inode_header *ipc = &inode_header.ipc;
1109
1110 inode = get_inode(sizeof(*ipc));
1111 ipc->nlink = nlink;
1112 SQUASHFS_SWAP_IPC_INODE_HEADER(ipc, inode);
1113 TRACE("ipc inode, type %s, nlink %d\n", type ==
1114 SQUASHFS_FIFO_TYPE ? "fifo" : "socket", nlink);
1115 }
1116 else if(type == SQUASHFS_LFIFO_TYPE || type == SQUASHFS_LSOCKET_TYPE) {
1117 struct squashfs_lipc_inode_header *ipc = &inode_header.lipc;
1118
1119 inode = get_inode(sizeof(*ipc));
1120 ipc->nlink = nlink;
1121 ipc->xattr = xattr;
1122 SQUASHFS_SWAP_LIPC_INODE_HEADER(ipc, inode);
1123 TRACE("ipc inode, type %s, nlink %d\n", type ==
1124 SQUASHFS_FIFO_TYPE ? "fifo" : "socket", nlink);
1125 } else
1126 BAD_ERROR("Unrecognised inode %d in create_inode\n", type);
1127
1128 *i_no = MKINODE(inode);
1129 inode_count ++;
1130
1131 TRACE("Created inode 0x%llx, type %d, uid %d, guid %d\n", *i_no, type,
1132 base->uid, base->guid);
1133
1134 return TRUE;
1135 }
1136
1137
1138 void add_dir(squashfs_inode inode, unsigned int inode_number, char *name,
1139 int type, struct directory *dir)
1140 {
1141 unsigned char *buff;
1142 struct squashfs_dir_entry idir;
1143 unsigned int start_block = inode >> 16;
1144 unsigned int offset = inode & 0xffff;
1145 unsigned int size = strlen(name);
1146 size_t name_off = offsetof(struct squashfs_dir_entry, name);
1147
1148 if(size > SQUASHFS_NAME_LEN) {
1149 size = SQUASHFS_NAME_LEN;
1150 ERROR("Filename is greater than %d characters, truncating! ..."
1151 "\n", SQUASHFS_NAME_LEN);
1152 }
1153
1154 if(dir->p + sizeof(struct squashfs_dir_entry) + size +
1155 sizeof(struct squashfs_dir_header)
1156 >= dir->buff + dir->size) {
1157 buff = realloc(dir->buff, dir->size += SQUASHFS_METADATA_SIZE);
1158 if(buff == NULL)
1159 MEM_ERROR();
1160
1161 dir->p = (dir->p - dir->buff) + buff;
1162 if(dir->entry_count_p)
1163 dir->entry_count_p = (dir->entry_count_p - dir->buff +
1164 buff);
1165 dir->index_count_p = dir->index_count_p - dir->buff + buff;
1166 dir->buff = buff;
1167 }
1168
1169 if(dir->entry_count == 256 || start_block != dir->start_block ||
1170 ((dir->entry_count_p != NULL) &&
1171 ((dir->p + sizeof(struct squashfs_dir_entry) + size -
1172 dir->index_count_p) > SQUASHFS_METADATA_SIZE)) ||
1173 ((long long) inode_number - dir->inode_number) > 32767
1174 || ((long long) inode_number - dir->inode_number)
1175 < -32768) {
1176 if(dir->entry_count_p) {
1177 struct squashfs_dir_header dir_header;
1178
1179 if((dir->p + sizeof(struct squashfs_dir_entry) + size -
1180 dir->index_count_p) >
1181 SQUASHFS_METADATA_SIZE) {
1182 if(dir->i_count % I_COUNT_SIZE == 0) {
1183 dir->index = realloc(dir->index,
1184 (dir->i_count + I_COUNT_SIZE) *
1185 sizeof(struct cached_dir_index));
1186 if(dir->index == NULL)
1187 MEM_ERROR();
1188 }
1189 dir->index[dir->i_count].index.index =
1190 dir->p - dir->buff;
1191 dir->index[dir->i_count].index.size = size - 1;
1192 dir->index[dir->i_count++].name = name;
1193 dir->i_size += sizeof(struct squashfs_dir_index)
1194 + size;
1195 dir->index_count_p = dir->p;
1196 }
1197
1198 dir_header.count = dir->entry_count - 1;
1199 dir_header.start_block = dir->start_block;
1200 dir_header.inode_number = dir->inode_number;
1201 SQUASHFS_SWAP_DIR_HEADER(&dir_header,
1202 dir->entry_count_p);
1203
1204 }
1205
1206
1207 dir->entry_count_p = dir->p;
1208 dir->start_block = start_block;
1209 dir->entry_count = 0;
1210 dir->inode_number = inode_number;
1211 dir->p += sizeof(struct squashfs_dir_header);
1212 }
1213
1214 idir.offset = offset;
1215 idir.type = type;
1216 idir.size = size - 1;
1217 idir.inode_number = ((long long) inode_number - dir->inode_number);
1218 SQUASHFS_SWAP_DIR_ENTRY(&idir, dir->p);
1219 strncpy((char *) dir->p + name_off, name, size);
1220 dir->p += sizeof(struct squashfs_dir_entry) + size;
1221 dir->entry_count ++;
1222 }
1223
1224
1225 void write_dir(squashfs_inode *inode, struct dir_info *dir_info,
1226 struct directory *dir)
1227 {
1228 unsigned int dir_size = dir->p - dir->buff;
1229 int data_space = directory_cache_size - directory_cache_bytes;
1230 unsigned int directory_block, directory_offset, i_count, index;
1231 unsigned short c_byte;
1232
1233 if(data_space < dir_size) {
1234 int realloc_size = directory_cache_size == 0 ?
1235 ((dir_size + SQUASHFS_METADATA_SIZE) &
1236 ~(SQUASHFS_METADATA_SIZE - 1)) : dir_size - data_space;
1237
1238 void *dc = realloc(directory_data_cache,
1239 directory_cache_size + realloc_size);
1240 if(dc == NULL)
1241 MEM_ERROR();
1242 directory_cache_size += realloc_size;
1243 directory_data_cache = dc;
1244 }
1245
1246 if(dir_size) {
1247 struct squashfs_dir_header dir_header;
1248
1249 dir_header.count = dir->entry_count - 1;
1250 dir_header.start_block = dir->start_block;
1251 dir_header.inode_number = dir->inode_number;
1252 SQUASHFS_SWAP_DIR_HEADER(&dir_header, dir->entry_count_p);
1253 memcpy(directory_data_cache + directory_cache_bytes, dir->buff,
1254 dir_size);
1255 }
1256 directory_offset = directory_cache_bytes;
1257 directory_block = directory_bytes;
1258 directory_cache_bytes += dir_size;
1259 i_count = 0;
1260 index = SQUASHFS_METADATA_SIZE - directory_offset;
1261
1262 while(1) {
1263 while(i_count < dir->i_count &&
1264 dir->index[i_count].index.index < index)
1265 dir->index[i_count++].index.start_block =
1266 directory_bytes;
1267 index += SQUASHFS_METADATA_SIZE;
1268
1269 if(directory_cache_bytes < SQUASHFS_METADATA_SIZE)
1270 break;
1271
1272 if((directory_size - directory_bytes) <
1273 ((SQUASHFS_METADATA_SIZE << 1) + 2)) {
1274 void *dt = realloc(directory_table,
1275 directory_size + (SQUASHFS_METADATA_SIZE << 1)
1276 + 2);
1277 if(dt == NULL)
1278 MEM_ERROR();
1279 directory_size += SQUASHFS_METADATA_SIZE << 1;
1280 directory_table = dt;
1281 }
1282
1283 c_byte = mangle(directory_table + directory_bytes +
1284 BLOCK_OFFSET, directory_data_cache,
1285 SQUASHFS_METADATA_SIZE, SQUASHFS_METADATA_SIZE,
1286 noI, 0);
1287 TRACE("Directory block @ 0x%x, size %d\n", directory_bytes,
1288 c_byte);
1289 SQUASHFS_SWAP_SHORTS(&c_byte,
1290 directory_table + directory_bytes, 1);
1291 directory_bytes += SQUASHFS_COMPRESSED_SIZE(c_byte) +
1292 BLOCK_OFFSET;
1293 total_directory_bytes += SQUASHFS_METADATA_SIZE + BLOCK_OFFSET;
1294 memmove(directory_data_cache, directory_data_cache +
1295 SQUASHFS_METADATA_SIZE, directory_cache_bytes -
1296 SQUASHFS_METADATA_SIZE);
1297 directory_cache_bytes -= SQUASHFS_METADATA_SIZE;
1298 }
1299
1300 create_inode(inode, dir_info, dir_info->dir_ent, SQUASHFS_DIR_TYPE,
1301 dir_size + 3, directory_block, directory_offset, NULL, NULL,
1302 dir, 0);
1303
1304 #ifdef SQUASHFS_TRACE
1305 {
1306 unsigned char *dirp;
1307 int count;
1308
1309 TRACE("Directory contents of inode 0x%llx\n", *inode);
1310 dirp = dir->buff;
1311 while(dirp < dir->p) {
1312 char buffer[SQUASHFS_NAME_LEN + 1];
1313 struct squashfs_dir_entry idir, *idirp;
1314 struct squashfs_dir_header dirh;
1315 SQUASHFS_SWAP_DIR_HEADER((struct squashfs_dir_header *) dirp,
1316 &dirh);
1317 count = dirh.count + 1;
1318 dirp += sizeof(struct squashfs_dir_header);
1319
1320 TRACE("\tStart block 0x%x, count %d\n",
1321 dirh.start_block, count);
1322
1323 while(count--) {
1324 idirp = (struct squashfs_dir_entry *) dirp;
1325 SQUASHFS_SWAP_DIR_ENTRY(idirp, &idir);
1326 strncpy(buffer, idirp->name, idir.size + 1);
1327 buffer[idir.size + 1] = '\0';
1328 TRACE("\t\tname %s, inode offset 0x%x, type "
1329 "%d\n", buffer, idir.offset, idir.type);
1330 dirp += sizeof(struct squashfs_dir_entry) + idir.size +
1331 1;
1332 }
1333 }
1334 }
1335 #endif
1336 dir_count ++;
1337 }
1338
1339
1340 static struct file_buffer *get_fragment(struct fragment *fragment)
1341 {
1342 struct squashfs_fragment_entry *disk_fragment;
1343 struct file_buffer *buffer, *compressed_buffer;
1344 long long start_block;
1345 int res, size, index = fragment->index;
1346 char locked;
1347
1348 /*
1349 * Lookup fragment block in cache.
1350 * If the fragment block doesn't exist, then get the compressed version
1351 * from the writer cache or off disk, and decompress it.
1352 *
1353 * This routine has two things which complicate the code:
1354 *
1355 * 1. Multiple threads can simultaneously lookup/create the
1356 * same buffer. This means a buffer needs to be "locked"
1357 * when it is being filled in, to prevent other threads from
1358 * using it when it is not ready. This is because we now do
1359 * fragment duplicate checking in parallel.
1360 * 2. We have two caches which need to be checked for the
1361 * presence of fragment blocks: the normal fragment cache
1362 * and a "reserve" cache. The reserve cache is used to
1363 * prevent an unnecessary pipeline stall when the fragment cache
1364 * is full of fragments waiting to be compressed.
1365 */
1366
1367 if(fragment->index == SQUASHFS_INVALID_FRAG)
1368 return NULL;
1369
1370 pthread_cleanup_push((void *) pthread_mutex_unlock, &dup_mutex);
1371 pthread_mutex_lock(&dup_mutex);
1372
1373 again:
1374 buffer = cache_lookup_nowait(fragment_buffer, index, &locked);
1375 if(buffer) {
1376 pthread_mutex_unlock(&dup_mutex);
1377 if(locked)
1378 /* got a buffer being filled in. Wait for it */
1379 cache_wait_unlock(buffer);
1380 goto finished;
1381 }
1382
1383 /* not in fragment cache, is it in the reserve cache? */
1384 buffer = cache_lookup_nowait(reserve_cache, index, &locked);
1385 if(buffer) {
1386 pthread_mutex_unlock(&dup_mutex);
1387 if(locked)
1388 /* got a buffer being filled in. Wait for it */
1389 cache_wait_unlock(buffer);
1390 goto finished;
1391 }
1392
1393 /* in neither cache, try to get it from the fragment cache */
1394 buffer = cache_get_nowait(fragment_buffer, index);
1395 if(!buffer) {
1396 /*
1397 * no room, get it from the reserve cache, this is
1398 * dimensioned so it will always have space (no more than
1399 * processors + 1 can have an outstanding reserve buffer)
1400 */
1401 buffer = cache_get_nowait(reserve_cache, index);
1402 if(!buffer) {
1403 /* failsafe */
1404 ERROR("no space in reserve cache\n");
1405 goto again;
1406 }
1407 }
1408
1409 pthread_mutex_unlock(&dup_mutex);
1410
1411 compressed_buffer = cache_lookup(fwriter_buffer, index);
1412
1413 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
1414 pthread_mutex_lock(&fragment_mutex);
1415 disk_fragment = &fragment_table[index];
1416 size = SQUASHFS_COMPRESSED_SIZE_BLOCK(disk_fragment->size);
1417 start_block = disk_fragment->start_block;
1418 pthread_cleanup_pop(1);
1419
1420 if(SQUASHFS_COMPRESSED_BLOCK(disk_fragment->size)) {
1421 int error;
1422 char *data;
1423
1424 if(compressed_buffer)
1425 data = compressed_buffer->data;
1426 else {
1427 data = read_from_disk(start_block, size);
1428 if(data == NULL) {
1429 ERROR("Failed to read fragment from output"
1430 " filesystem\n");
1431 BAD_ERROR("Output filesystem corrupted?\n");
1432 }
1433 }
1434
1435 res = compressor_uncompress(comp, buffer->data, data, size,
1436 block_size, &error);
1437 if(res == -1)
1438 BAD_ERROR("%s uncompress failed with error code %d\n",
1439 comp->name, error);
1440 } else if(compressed_buffer)
1441 memcpy(buffer->data, compressed_buffer->data, size);
1442 else {
1443 res = read_fs_bytes(fd, start_block, size, buffer->data);
1444 if(res == 0) {
1445 ERROR("Failed to read fragment from output "
1446 "filesystem\n");
1447 BAD_ERROR("Output filesystem corrupted?\n");
1448 }
1449 }
1450
1451 cache_unlock(buffer);
1452 cache_block_put(compressed_buffer);
1453
1454 finished:
1455 pthread_cleanup_pop(0);
1456
1457 return buffer;
1458 }
1459
1460
1461 unsigned short get_fragment_checksum(struct file_info *file)
1462 {
1463 struct file_buffer *frag_buffer;
1464 struct append_file *append;
1465 int res, index = file->fragment->index;
1466 unsigned short checksum;
1467
1468 if(index == SQUASHFS_INVALID_FRAG)
1469 return 0;
1470
1471 pthread_cleanup_push((void *) pthread_mutex_unlock, &dup_mutex);
1472 pthread_mutex_lock(&dup_mutex);
1473 res = file->have_frag_checksum;
1474 checksum = file->fragment_checksum;
1475 pthread_cleanup_pop(1);
1476
1477 if(res)
1478 return checksum;
1479
1480 frag_buffer = get_fragment(file->fragment);
1481
1482 pthread_cleanup_push((void *) pthread_mutex_unlock, &dup_mutex);
1483
1484 for(append = file_mapping[index]; append; append = append->next) {
1485 int offset = append->file->fragment->offset;
1486 int size = append->file->fragment->size;
1487 unsigned short cksum =
1488 get_checksum_mem(frag_buffer->data + offset, size);
1489
1490 if(file == append->file)
1491 checksum = cksum;
1492
1493 pthread_mutex_lock(&dup_mutex);
1494 append->file->fragment_checksum = cksum;
1495 append->file->have_frag_checksum = TRUE;
1496 pthread_mutex_unlock(&dup_mutex);
1497 }
1498
1499 cache_block_put(frag_buffer);
1500 pthread_cleanup_pop(0);
1501
1502 return checksum;
1503 }
1504
1505
1506 void ensure_fragments_flushed()
1507 {
1508 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
1509 pthread_mutex_lock(&fragment_mutex);
1510
1511 while(fragments_outstanding)
1512 pthread_cond_wait(&fragment_waiting, &fragment_mutex);
1513
1514 pthread_cleanup_pop(1);
1515 }
1516
1517
1518 void lock_fragments()
1519 {
1520 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
1521 pthread_mutex_lock(&fragment_mutex);
1522 fragments_locked = TRUE;
1523 pthread_cleanup_pop(1);
1524 }
1525
1526
1527 void log_fragment(unsigned int fragment, long long start)
1528 {
1529 if(logging)
1530 fprintf(log_fd, "Fragment %u, %lld\n", fragment, start);
1531 }
1532
1533
1534 void unlock_fragments()
1535 {
1536 int frg, size;
1537 struct file_buffer *write_buffer;
1538
1539 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
1540 pthread_mutex_lock(&fragment_mutex);
1541
1542 /*
1543 * Note queue_empty() is inherently racy with respect to concurrent
1544 * queue get and pushes. We avoid this because we're holding the
1545 * fragment_mutex which ensures no other threads can be using the
1546 * queue at this time.
1547 */
1548 while(!queue_empty(locked_fragment)) {
1549 write_buffer = queue_get(locked_fragment);
1550 frg = write_buffer->block;
1551 size = SQUASHFS_COMPRESSED_SIZE_BLOCK(fragment_table[frg].size);
1552 fragment_table[frg].start_block = bytes;
1553 write_buffer->block = bytes;
1554 bytes += size;
1555 fragments_outstanding --;
1556 queue_put(to_writer, write_buffer);
1557 log_fragment(frg, fragment_table[frg].start_block);
1558 TRACE("fragment_locked writing fragment %d, compressed size %d"
1559 "\n", frg, size);
1560 }
1561 fragments_locked = FALSE;
1562 pthread_cleanup_pop(1);
1563 }
1564
1565 /* Called with the fragment_mutex locked */
1566 void add_pending_fragment(struct file_buffer *write_buffer, int c_byte,
1567 int fragment)
1568 {
1569 fragment_table[fragment].size = c_byte;
1570 write_buffer->block = fragment;
1571
1572 queue_put(locked_fragment, write_buffer);
1573 }
1574
1575
1576 void write_fragment(struct file_buffer *fragment)
1577 {
1578 static long long sequence = 0;
1579
1580 if(fragment == NULL)
1581 return;
1582
1583 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
1584 pthread_mutex_lock(&fragment_mutex);
1585 fragment_table[fragment->block].unused = 0;
1586 fragment->sequence = sequence ++;
1587 fragments_outstanding ++;
1588 queue_put(to_frag, fragment);
1589 pthread_cleanup_pop(1);
1590 }
1591
1592
1593 struct file_buffer *allocate_fragment()
1594 {
1595 struct file_buffer *fragment = cache_get(fragment_buffer, fragments);
1596
1597 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
1598 pthread_mutex_lock(&fragment_mutex);
1599
1600 if(fragments % FRAG_SIZE == 0) {
1601 void *ft = realloc(fragment_table, (fragments +
1602 FRAG_SIZE) * sizeof(struct squashfs_fragment_entry));
1603 if(ft == NULL)
1604 MEM_ERROR();
1605 fragment_table = ft;
1606 }
1607
1608 fragment->size = 0;
1609 fragment->block = fragments ++;
1610
1611 pthread_cleanup_pop(1);
1612
1613 return fragment;
1614 }
1615
1616
1617 static struct fragment empty_fragment = {SQUASHFS_INVALID_FRAG, 0, 0};
1618
1619
1620 void free_fragment(struct fragment *fragment)
1621 {
1622 if(fragment != &empty_fragment)
1623 free(fragment);
1624 }
1625
1626
1627 struct fragment *get_and_fill_fragment(struct file_buffer *file_buffer,
1628 struct dir_ent *dir_ent)
1629 {
1630 struct fragment *ffrg;
1631 struct file_buffer **fragment;
1632
1633 if(file_buffer == NULL || file_buffer->size == 0)
1634 return &empty_fragment;
1635
1636 fragment = eval_frag_actions(root_dir, dir_ent);
1637
1638 if((*fragment) && (*fragment)->size + file_buffer->size > block_size) {
1639 write_fragment(*fragment);
1640 *fragment = NULL;
1641 }
1642
1643 ffrg = malloc(sizeof(struct fragment));
1644 if(ffrg == NULL)
1645 MEM_ERROR();
1646
1647 if(*fragment == NULL)
1648 *fragment = allocate_fragment();
1649
1650 ffrg->index = (*fragment)->block;
1651 ffrg->offset = (*fragment)->size;
1652 ffrg->size = file_buffer->size;
1653 memcpy((*fragment)->data + (*fragment)->size, file_buffer->data,
1654 file_buffer->size);
1655 (*fragment)->size += file_buffer->size;
1656
1657 return ffrg;
1658 }
1659
1660
1661 long long generic_write_table(int length, void *buffer, int length2,
1662 void *buffer2, int uncompressed)
1663 {
1664 int meta_blocks = (length + SQUASHFS_METADATA_SIZE - 1) /
1665 SQUASHFS_METADATA_SIZE;
1666 long long *list, start_bytes;
1667 int compressed_size, i, list_size = meta_blocks * sizeof(long long);
1668 unsigned short c_byte;
1669 char cbuffer[(SQUASHFS_METADATA_SIZE << 2) + 2];
1670
1671 #ifdef SQUASHFS_TRACE
1672 long long obytes = bytes;
1673 int olength = length;
1674 #endif
1675
1676 list = malloc(list_size);
1677 if(list == NULL)
1678 MEM_ERROR();
1679
1680 for(i = 0; i < meta_blocks; i++) {
1681 int avail_bytes = length > SQUASHFS_METADATA_SIZE ?
1682 SQUASHFS_METADATA_SIZE : length;
1683 c_byte = mangle(cbuffer + BLOCK_OFFSET, buffer + i *
1684 SQUASHFS_METADATA_SIZE , avail_bytes,
1685 SQUASHFS_METADATA_SIZE, uncompressed, 0);
1686 SQUASHFS_SWAP_SHORTS(&c_byte, cbuffer, 1);
1687 list[i] = bytes;
1688 compressed_size = SQUASHFS_COMPRESSED_SIZE(c_byte) +
1689 BLOCK_OFFSET;
1690 TRACE("block %d @ 0x%llx, compressed size %d\n", i, bytes,
1691 compressed_size);
1692 write_destination(fd, bytes, compressed_size, cbuffer);
1693 bytes += compressed_size;
1694 total_bytes += avail_bytes;
1695 length -= avail_bytes;
1696 }
1697
1698 start_bytes = bytes;
1699 if(length2) {
1700 write_destination(fd, bytes, length2, buffer2);
1701 bytes += length2;
1702 total_bytes += length2;
1703 }
1704
1705 SQUASHFS_INSWAP_LONG_LONGS(list, meta_blocks);
1706 write_destination(fd, bytes, list_size, list);
1707 bytes += list_size;
1708 total_bytes += list_size;
1709
1710 TRACE("generic_write_table: total uncompressed %d compressed %lld\n",
1711 olength, bytes - obytes);
1712
1713 free(list);
1714
1715 return start_bytes;
1716 }
1717
1718
1719 long long write_fragment_table()
1720 {
1721 unsigned int frag_bytes = SQUASHFS_FRAGMENT_BYTES(fragments);
1722 int i;
1723
1724 TRACE("write_fragment_table: fragments %d, frag_bytes %d\n", fragments,
1725 frag_bytes);
1726 for(i = 0; i < fragments; i++) {
1727 TRACE("write_fragment_table: fragment %d, start_block 0x%llx, "
1728 "size %d\n", i, fragment_table[i].start_block,
1729 fragment_table[i].size);
1730 SQUASHFS_INSWAP_FRAGMENT_ENTRY(&fragment_table[i]);
1731 }
1732
1733 return generic_write_table(frag_bytes, fragment_table, 0, NULL, noF);
1734 }
1735
1736
1737 char read_from_file_buffer[SQUASHFS_FILE_MAX_SIZE];
1738 static char *read_from_disk(long long start, unsigned int avail_bytes)
1739 {
1740 int res;
1741
1742 res = read_fs_bytes(fd, start, avail_bytes, read_from_file_buffer);
1743 if(res == 0)
1744 return NULL;
1745
1746 return read_from_file_buffer;
1747 }
1748
1749
1750 char read_from_file_buffer2[SQUASHFS_FILE_MAX_SIZE];
1751 char *read_from_disk2(long long start, unsigned int avail_bytes)
1752 {
1753 int res;
1754
1755 res = read_fs_bytes(fd, start, avail_bytes, read_from_file_buffer2);
1756 if(res == 0)
1757 return NULL;
1758
1759 return read_from_file_buffer2;
1760 }
1761
1762
1763 /*
1764 * Compute 16 bit BSD checksum over the data
1765 */
1766 unsigned short get_checksum(char *buff, int bytes, unsigned short chksum)
1767 {
1768 unsigned char *b = (unsigned char *) buff;
1769
1770 while(bytes --) {
1771 chksum = (chksum & 1) ? (chksum >> 1) | 0x8000 : chksum >> 1;
1772 chksum += *b++;
1773 }
1774
1775 return chksum;
1776 }
1777
1778
1779 unsigned short get_checksum_disk(long long start, long long l,
1780 unsigned int *blocks)
1781 {
1782 unsigned short chksum = 0;
1783 unsigned int bytes;
1784 struct file_buffer *write_buffer;
1785 int i;
1786
1787 for(i = 0; l; i++) {
1788 bytes = SQUASHFS_COMPRESSED_SIZE_BLOCK(blocks[i]);
1789 if(bytes == 0) /* sparse block */
1790 continue;
1791 write_buffer = cache_lookup(bwriter_buffer, start);
1792 if(write_buffer) {
1793 chksum = get_checksum(write_buffer->data, bytes,
1794 chksum);
1795 cache_block_put(write_buffer);
1796 } else {
1797 void *data = read_from_disk(start, bytes);
1798 if(data == NULL) {
1799 ERROR("Failed to checksum data from output"
1800 " filesystem\n");
1801 BAD_ERROR("Output filesystem corrupted?\n");
1802 }
1803
1804 chksum = get_checksum(data, bytes, chksum);
1805 }
1806
1807 l -= bytes;
1808 start += bytes;
1809 }
1810
1811 return chksum;
1812 }
1813
1814
1815 unsigned short get_checksum_mem(char *buff, int bytes)
1816 {
1817 return get_checksum(buff, bytes, 0);
1818 }
1819
1820
1821 unsigned short get_checksum_mem_buffer(struct file_buffer *file_buffer)
1822 {
1823 if(file_buffer == NULL)
1824 return 0;
1825 else
1826 return get_checksum(file_buffer->data, file_buffer->size, 0);
1827 }
1828
1829
1830 #define DUP_HASH(a) (a & 0xffff)
1831 void add_file(long long start, long long file_size, long long file_bytes,
1832 unsigned int *block_listp, int blocks, unsigned int fragment,
1833 int offset, int bytes)
1834 {
1835 struct fragment *frg;
1836 unsigned int *block_list = block_listp;
1837 struct file_info *dupl_ptr = dupl[DUP_HASH(file_size)];
1838 struct append_file *append_file;
1839 struct file_info *file;
1840
1841 if(!duplicate_checking || file_size == 0)
1842 return;
1843
1844 for(; dupl_ptr; dupl_ptr = dupl_ptr->next) {
1845 if(file_size != dupl_ptr->file_size)
1846 continue;
1847 if(blocks != 0 && start != dupl_ptr->start)
1848 continue;
1849 if(fragment != dupl_ptr->fragment->index)
1850 continue;
1851 if(fragment != SQUASHFS_INVALID_FRAG && (offset !=
1852 dupl_ptr->fragment->offset || bytes !=
1853 dupl_ptr->fragment->size))
1854 continue;
1855 return;
1856 }
1857
1858 frg = malloc(sizeof(struct fragment));
1859 if(frg == NULL)
1860 MEM_ERROR();
1861
1862 frg->index = fragment;
1863 frg->offset = offset;
1864 frg->size = bytes;
1865
1866 file = add_non_dup(file_size, file_bytes, block_list, start, frg, 0, 0,
1867 FALSE, FALSE);
1868
1869 if(fragment == SQUASHFS_INVALID_FRAG)
1870 return;
1871
1872 append_file = malloc(sizeof(struct append_file));
1873 if(append_file == NULL)
1874 MEM_ERROR();
1875
1876 append_file->file = file;
1877 append_file->next = file_mapping[fragment];
1878 file_mapping[fragment] = append_file;
1879 }
1880
1881
1882 int pre_duplicate(long long file_size)
1883 {
1884 struct file_info *dupl_ptr = dupl[DUP_HASH(file_size)];
1885
1886 for(; dupl_ptr; dupl_ptr = dupl_ptr->next)
1887 if(dupl_ptr->file_size == file_size)
1888 return TRUE;
1889
1890 return FALSE;
1891 }
1892
1893
1894 struct file_info *add_non_dup(long long file_size, long long bytes,
1895 unsigned int *block_list, long long start, struct fragment *fragment,
1896 unsigned short checksum, unsigned short fragment_checksum,
1897 int checksum_flag, int checksum_frag_flag)
1898 {
1899 struct file_info *dupl_ptr = malloc(sizeof(struct file_info));
1900
1901 if(dupl_ptr == NULL)
1902 MEM_ERROR();
1903
1904 dupl_ptr->file_size = file_size;
1905 dupl_ptr->bytes = bytes;
1906 dupl_ptr->block_list = block_list;
1907 dupl_ptr->start = start;
1908 dupl_ptr->fragment = fragment;
1909 dupl_ptr->checksum = checksum;
1910 dupl_ptr->fragment_checksum = fragment_checksum;
1911 dupl_ptr->have_frag_checksum = checksum_frag_flag;
1912 dupl_ptr->have_checksum = checksum_flag;
1913
1914 pthread_cleanup_push((void *) pthread_mutex_unlock, &dup_mutex);
1915 pthread_mutex_lock(&dup_mutex);
1916 dupl_ptr->next = dupl[DUP_HASH(file_size)];
1917 dupl[DUP_HASH(file_size)] = dupl_ptr;
1918 dup_files ++;
1919 pthread_cleanup_pop(1);
1920
1921 return dupl_ptr;
1922 }
1923
1924
1925 struct fragment *frag_duplicate(struct file_buffer *file_buffer, char *dont_put)
1926 {
1927 struct file_info *dupl_ptr;
1928 struct file_buffer *buffer;
1929 struct file_info *dupl_start = file_buffer->dupl_start;
1930 long long file_size = file_buffer->file_size;
1931 unsigned short checksum = file_buffer->checksum;
1932 int res;
1933
1934 if(file_buffer->duplicate) {
1935 TRACE("Found duplicate file, fragment %d, size %d, offset %d, "
1936 "checksum 0x%x\n", dupl_start->fragment->index,
1937 file_size, dupl_start->fragment->offset, checksum);
1938 *dont_put = TRUE;
1939 return dupl_start->fragment;
1940 } else {
1941 *dont_put = FALSE;
1942 dupl_ptr = dupl[DUP_HASH(file_size)];
1943 }
1944
1945 for(; dupl_ptr && dupl_ptr != dupl_start; dupl_ptr = dupl_ptr->next) {
1946 if(file_size == dupl_ptr->file_size && file_size ==
1947 dupl_ptr->fragment->size) {
1948 if(get_fragment_checksum(dupl_ptr) == checksum) {
1949 buffer = get_fragment(dupl_ptr->fragment);
1950 res = memcmp(file_buffer->data, buffer->data +
1951 dupl_ptr->fragment->offset, file_size);
1952 cache_block_put(buffer);
1953 if(res == 0)
1954 break;
1955 }
1956 }
1957 }
1958
1959 if(!dupl_ptr || dupl_ptr == dupl_start)
1960 return NULL;
1961
1962 TRACE("Found duplicate file, fragment %d, size %d, offset %d, "
1963 "checksum 0x%x\n", dupl_ptr->fragment->index, file_size,
1964 dupl_ptr->fragment->offset, checksum);
1965
1966 return dupl_ptr->fragment;
1967 }
1968
1969
1970 struct file_info *duplicate(long long file_size, long long bytes,
1971 unsigned int **block_list, long long *start, struct fragment **fragment,
1972 struct file_buffer *file_buffer, int blocks, unsigned short checksum,
1973 int checksum_flag)
1974 {
1975 struct file_info *dupl_ptr = dupl[DUP_HASH(file_size)];
1976 int frag_bytes = file_buffer ? file_buffer->size : 0;
1977 unsigned short fragment_checksum = file_buffer ?
1978 file_buffer->checksum : 0;
1979
1980 for(; dupl_ptr; dupl_ptr = dupl_ptr->next)
1981 if(file_size == dupl_ptr->file_size && bytes == dupl_ptr->bytes
1982 && frag_bytes == dupl_ptr->fragment->size) {
1983 long long target_start, dup_start = dupl_ptr->start;
1984 int block;
1985
1986 if(memcmp(*block_list, dupl_ptr->block_list, blocks *
1987 sizeof(unsigned int)) != 0)
1988 continue;
1989
1990 if(checksum_flag == FALSE) {
1991 checksum = get_checksum_disk(*start, bytes,
1992 *block_list);
1993 checksum_flag = TRUE;
1994 }
1995
1996 if(!dupl_ptr->have_checksum) {
1997 dupl_ptr->checksum =
1998 get_checksum_disk(dupl_ptr->start,
1999 dupl_ptr->bytes, dupl_ptr->block_list);
2000 dupl_ptr->have_checksum = TRUE;
2001 }
2002
2003 if(checksum != dupl_ptr->checksum ||
2004 fragment_checksum !=
2005 get_fragment_checksum(dupl_ptr))
2006 continue;
2007
2008 target_start = *start;
2009 for(block = 0; block < blocks; block ++) {
2010 int size = SQUASHFS_COMPRESSED_SIZE_BLOCK
2011 ((*block_list)[block]);
2012 struct file_buffer *target_buffer = NULL;
2013 struct file_buffer *dup_buffer = NULL;
2014 char *target_data, *dup_data;
2015 int res;
2016
2017 if(size == 0)
2018 continue;
2019 target_buffer = cache_lookup(bwriter_buffer,
2020 target_start);
2021 if(target_buffer)
2022 target_data = target_buffer->data;
2023 else {
2024 target_data =
2025 read_from_disk(target_start,
2026 size);
2027 if(target_data == NULL) {
2028 ERROR("Failed to read data from"
2029 " output filesystem\n");
2030 BAD_ERROR("Output filesystem"
2031 " corrupted?\n");
2032 }
2033 }
2034
2035 dup_buffer = cache_lookup(bwriter_buffer,
2036 dup_start);
2037 if(dup_buffer)
2038 dup_data = dup_buffer->data;
2039 else {
2040 dup_data = read_from_disk2(dup_start,
2041 size);
2042 if(dup_data == NULL) {
2043 ERROR("Failed to read data from"
2044 " output filesystem\n");
2045 BAD_ERROR("Output filesystem"
2046 " corrupted?\n");
2047 }
2048 }
2049
2050 res = memcmp(target_data, dup_data, size);
2051 cache_block_put(target_buffer);
2052 cache_block_put(dup_buffer);
2053 if(res != 0)
2054 break;
2055 target_start += size;
2056 dup_start += size;
2057 }
2058 if(block == blocks) {
2059 struct file_buffer *frag_buffer =
2060 get_fragment(dupl_ptr->fragment);
2061
2062 if(frag_bytes == 0 ||
2063 memcmp(file_buffer->data,
2064 frag_buffer->data +
2065 dupl_ptr->fragment->offset,
2066 frag_bytes) == 0) {
2067 TRACE("Found duplicate file, start "
2068 "0x%llx, size %lld, checksum "
2069 "0x%x, fragment %d, size %d, "
2070 "offset %d, checksum 0x%x\n",
2071 dupl_ptr->start,
2072 dupl_ptr->bytes,
2073 dupl_ptr->checksum,
2074 dupl_ptr->fragment->index,
2075 frag_bytes,
2076 dupl_ptr->fragment->offset,
2077 fragment_checksum);
2078 *block_list = dupl_ptr->block_list;
2079 *start = dupl_ptr->start;
2080 *fragment = dupl_ptr->fragment;
2081 cache_block_put(frag_buffer);
2082 return 0;
2083 }
2084 cache_block_put(frag_buffer);
2085 }
2086 }
2087
2088
2089 return add_non_dup(file_size, bytes, *block_list, *start, *fragment,
2090 checksum, fragment_checksum, checksum_flag, TRUE);
2091 }
2092
2093
2094 static inline int is_fragment(struct inode_info *inode)
2095 {
2096 off_t file_size = inode->buf.st_size;
2097
2098 /*
2099 * If this block is to be compressed differently to the
2100 * fragment compression then it cannot be a fragment
2101 */
2102 if(inode->noF != noF)
2103 return FALSE;
2104
2105 return !inode->no_fragments && file_size && (file_size < block_size ||
2106 (inode->always_use_fragments && file_size & (block_size - 1)));
2107 }
2108
2109
2110 void put_file_buffer(struct file_buffer *file_buffer)
2111 {
2112 /*
2113 * Decide where to send the file buffer:
2114 * - compressible non-fragment blocks go to the deflate threads,
2115 * - fragments go to the process fragment threads,
2116 * - all others go directly to the main thread
2117 */
2118 if(file_buffer->error) {
2119 file_buffer->fragment = 0;
2120 seq_queue_put(to_main, file_buffer);
2121 } else if (file_buffer->file_size == 0)
2122 seq_queue_put(to_main, file_buffer);
2123 else if(file_buffer->fragment)
2124 queue_put(to_process_frag, file_buffer);
2125 else
2126 queue_put(to_deflate, file_buffer);
2127 }
2128
2129
2130 static int seq = 0;
2131 void reader_read_process(struct dir_ent *dir_ent)
2132 {
2133 long long bytes = 0;
2134 struct inode_info *inode = dir_ent->inode;
2135 struct file_buffer *prev_buffer = NULL, *file_buffer;
2136 int status, byte, res, child;
2137 int file = pseudo_exec_file(get_pseudo_file(inode->pseudo_id), &child);
2138
2139 if(!file) {
2140 file_buffer = cache_get_nohash(reader_buffer);
2141 file_buffer->sequence = seq ++;
2142 goto read_err;
2143 }
2144
2145 while(1) {
2146 file_buffer = cache_get_nohash(reader_buffer);
2147 file_buffer->sequence = seq ++;
2148 file_buffer->noD = inode->noD;
2149
2150 byte = read_bytes(file, file_buffer->data, block_size);
2151 if(byte == -1)
2152 goto read_err2;
2153
2154 file_buffer->size = byte;
2155 file_buffer->file_size = -1;
2156 file_buffer->error = FALSE;
2157 file_buffer->fragment = FALSE;
2158 bytes += byte;
2159
2160 if(byte == 0)
2161 break;
2162
2163 /*
2164 * Update progress bar size. This is done
2165 * on every block rather than waiting for all blocks to be
2166 * read incase write_file_process() is running in parallel
2167 * with this. Otherwise the current progress bar position
2168 * may get ahead of the progress bar size.
2169 */
2170 progress_bar_size(1);
2171
2172 if(prev_buffer)
2173 put_file_buffer(prev_buffer);
2174 prev_buffer = file_buffer;
2175 }
2176
2177 /*
2178 * Update inode file size now that the size of the dynamic pseudo file
2179 * is known. This is needed for the -info option.
2180 */
2181 inode->buf.st_size = bytes;
2182
2183 res = waitpid(child, &status, 0);
2184 close(file);
2185
2186 if(res == -1 || !WIFEXITED(status) || WEXITSTATUS(status) != 0)
2187 goto read_err;
2188
2189 if(prev_buffer == NULL)
2190 prev_buffer = file_buffer;
2191 else {
2192 cache_block_put(file_buffer);
2193 seq --;
2194 }
2195 prev_buffer->file_size = bytes;
2196 prev_buffer->fragment = is_fragment(inode);
2197 put_file_buffer(prev_buffer);
2198
2199 return;
2200
2201 read_err2:
2202 close(file);
2203 read_err:
2204 if(prev_buffer) {
2205 cache_block_put(file_buffer);
2206 seq --;
2207 file_buffer = prev_buffer;
2208 }
2209 file_buffer->error = TRUE;
2210 put_file_buffer(file_buffer);
2211 }
2212
2213
2214 void reader_read_file(struct dir_ent *dir_ent)
2215 {
2216 struct stat *buf = &dir_ent->inode->buf, buf2;
2217 struct file_buffer *file_buffer;
2218 int blocks, file, res;
2219 long long bytes, read_size;
2220 struct inode_info *inode = dir_ent->inode;
2221
2222 if(inode->read)
2223 return;
2224
2225 inode->read = TRUE;
2226 again:
2227 bytes = 0;
2228 read_size = buf->st_size;
2229 blocks = (read_size + block_size - 1) >> block_log;
2230
2231 file = open(pathname_reader(dir_ent), O_RDONLY);
2232 if(file == -1) {
2233 file_buffer = cache_get_nohash(reader_buffer);
2234 file_buffer->sequence = seq ++;
2235 goto read_err2;
2236 }
2237
2238 do {
2239 file_buffer = cache_get_nohash(reader_buffer);
2240 file_buffer->file_size = read_size;
2241 file_buffer->sequence = seq ++;
2242 file_buffer->noD = inode->noD;
2243 file_buffer->error = FALSE;
2244
2245 /*
2246 * Always try to read block_size bytes from the file rather
2247 * than expected bytes (which will be less than the block_size
2248 * at the file tail) to check that the file hasn't grown
2249 * since being stated. If it is longer (or shorter) than
2250 * expected, then restat, and try again. Note the special
2251 * case where the file is an exact multiple of the block_size
2252 * is dealt with later.
2253 */
2254 file_buffer->size = read_bytes(file, file_buffer->data,
2255 block_size);
2256 if(file_buffer->size == -1)
2257 goto read_err;
2258
2259 bytes += file_buffer->size;
2260
2261 if(blocks > 1) {
2262 /* non-tail block should be exactly block_size */
2263 if(file_buffer->size < block_size)
2264 goto restat;
2265
2266 file_buffer->fragment = FALSE;
2267 put_file_buffer(file_buffer);
2268 }
2269 } while(-- blocks > 0);
2270
2271 /* Overall size including tail should match */
2272 if(read_size != bytes)
2273 goto restat;
2274
2275 if(read_size && read_size % block_size == 0) {
2276 /*
2277 * Special case where we've not tried to read past the end of
2278 * the file. We expect to get EOF, i.e. the file isn't larger
2279 * than we expect.
2280 */
2281 char buffer;
2282 int res;
2283
2284 res = read_bytes(file, &buffer, 1);
2285 if(res == -1)
2286 goto read_err;
2287
2288 if(res != 0)
2289 goto restat;
2290 }
2291
2292 file_buffer->fragment = is_fragment(inode);
2293 put_file_buffer(file_buffer);
2294
2295 close(file);
2296
2297 return;
2298
2299 restat:
2300 res = fstat(file, &buf2);
2301 if(res == -1) {
2302 ERROR("Cannot stat dir/file %s because %s\n",
2303 pathname_reader(dir_ent), strerror(errno));
2304 goto read_err;
2305 }
2306
2307 if(read_size != buf2.st_size) {
2308 close(file);
2309 memcpy(buf, &buf2, sizeof(struct stat));
2310 file_buffer->error = 2;
2311 put_file_buffer(file_buffer);
2312 goto again;
2313 }
2314 read_err:
2315 close(file);
2316 read_err2:
2317 file_buffer->error = TRUE;
2318 put_file_buffer(file_buffer);
2319 }
2320
2321
2322 void reader_scan(struct dir_info *dir) {
2323 struct dir_ent *dir_ent = dir->list;
2324
2325 for(; dir_ent; dir_ent = dir_ent->next) {
2326 struct stat *buf = &dir_ent->inode->buf;
2327 if(dir_ent->inode->root_entry)
2328 continue;
2329
2330 if(IS_PSEUDO_PROCESS(dir_ent->inode)) {
2331 reader_read_process(dir_ent);
2332 continue;
2333 }
2334
2335 switch(buf->st_mode & S_IFMT) {
2336 case S_IFREG:
2337 reader_read_file(dir_ent);
2338 break;
2339 case S_IFDIR:
2340 reader_scan(dir_ent->dir);
2341 break;
2342 }
2343 }
2344 }
2345
2346
2347 void *reader(void *arg)
2348 {
2349 if(!sorted)
2350 reader_scan(queue_get(to_reader));
2351 else {
2352 int i;
2353 struct priority_entry *entry;
2354
2355 queue_get(to_reader);
2356 for(i = 65535; i >= 0; i--)
2357 for(entry = priority_list[i]; entry;
2358 entry = entry->next)
2359 reader_read_file(entry->dir);
2360 }
2361
2362 pthread_exit(NULL);
2363 }
2364
2365
2366 void *writer(void *arg)
2367 {
2368 while(1) {
2369 struct file_buffer *file_buffer = queue_get(to_writer);
2370 off_t off;
2371
2372 if(file_buffer == NULL) {
2373 queue_put(from_writer, NULL);
2374 continue;
2375 }
2376
2377 off = file_buffer->block;
2378
2379 pthread_cleanup_push((void *) pthread_mutex_unlock, &pos_mutex);
2380 pthread_mutex_lock(&pos_mutex);
2381
2382 if(lseek(fd, start_offset + off, SEEK_SET) == -1) {
2383 ERROR("writer: Lseek on destination failed because "
2384 "%s, offset=0x%llx\n", strerror(errno), start_offset + off);
2385 BAD_ERROR("Probably out of space on output "
2386 "%s\n", block_device ? "block device" :
2387 "filesystem");
2388 }
2389
2390 if(write_bytes(fd, file_buffer->data,
2391 file_buffer->size) == -1)
2392 BAD_ERROR("Failed to write to output %s\n",
2393 block_device ? "block device" : "filesystem");
2394
2395 pthread_cleanup_pop(1);
2396
2397 cache_block_put(file_buffer);
2398 }
2399 }
2400
2401
2402 int all_zero(struct file_buffer *file_buffer)
2403 {
2404 int i;
2405 long entries = file_buffer->size / sizeof(long);
2406 long *p = (long *) file_buffer->data;
2407
2408 for(i = 0; i < entries && p[i] == 0; i++);
2409
2410 if(i == entries) {
2411 for(i = file_buffer->size & ~(sizeof(long) - 1);
2412 i < file_buffer->size && file_buffer->data[i] == 0;
2413 i++);
2414
2415 return i == file_buffer->size;
2416 }
2417
2418 return 0;
2419 }
2420
2421
2422 void *deflator(void *arg)
2423 {
2424 struct file_buffer *write_buffer = cache_get_nohash(bwriter_buffer);
2425 void *stream = NULL;
2426 int res;
2427
2428 res = compressor_init(comp, &stream, block_size, 1);
2429 if(res)
2430 BAD_ERROR("deflator:: compressor_init failed\n");
2431
2432 while(1) {
2433 struct file_buffer *file_buffer = queue_get(to_deflate);
2434
2435 if(sparse_files && all_zero(file_buffer)) {
2436 file_buffer->c_byte = 0;
2437 seq_queue_put(to_main, file_buffer);
2438 } else {
2439 write_buffer->c_byte = mangle2(stream,
2440 write_buffer->data, file_buffer->data,
2441 file_buffer->size, block_size,
2442 file_buffer->noD, 1);
2443 write_buffer->sequence = file_buffer->sequence;
2444 write_buffer->file_size = file_buffer->file_size;
2445 write_buffer->block = file_buffer->block;
2446 write_buffer->size = SQUASHFS_COMPRESSED_SIZE_BLOCK
2447 (write_buffer->c_byte);
2448 write_buffer->fragment = FALSE;
2449 write_buffer->error = FALSE;
2450 cache_block_put(file_buffer);
2451 seq_queue_put(to_main, write_buffer);
2452 write_buffer = cache_get_nohash(bwriter_buffer);
2453 }
2454 }
2455 }
2456
2457
2458 void *frag_deflator(void *arg)
2459 {
2460 void *stream = NULL;
2461 int res;
2462
2463 res = compressor_init(comp, &stream, block_size, 1);
2464 if(res)
2465 BAD_ERROR("frag_deflator:: compressor_init failed\n");
2466
2467 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
2468
2469 while(1) {
2470 int c_byte, compressed_size;
2471 struct file_buffer *file_buffer = queue_get(to_frag);
2472 struct file_buffer *write_buffer =
2473 cache_get(fwriter_buffer, file_buffer->block);
2474
2475 c_byte = mangle2(stream, write_buffer->data, file_buffer->data,
2476 file_buffer->size, block_size, noF, 1);
2477 compressed_size = SQUASHFS_COMPRESSED_SIZE_BLOCK(c_byte);
2478 write_buffer->size = compressed_size;
2479 pthread_mutex_lock(&fragment_mutex);
2480 if(fragments_locked == FALSE) {
2481 fragment_table[file_buffer->block].size = c_byte;
2482 fragment_table[file_buffer->block].start_block = bytes;
2483 write_buffer->block = bytes;
2484 bytes += compressed_size;
2485 fragments_outstanding --;
2486 queue_put(to_writer, write_buffer);
2487 log_fragment(file_buffer->block, fragment_table[file_buffer->block].start_block);
2488 pthread_mutex_unlock(&fragment_mutex);
2489 TRACE("Writing fragment %lld, uncompressed size %d, "
2490 "compressed size %d\n", file_buffer->block,
2491 file_buffer->size, compressed_size);
2492 } else {
2493 add_pending_fragment(write_buffer, c_byte,
2494 file_buffer->block);
2495 pthread_mutex_unlock(&fragment_mutex);
2496 }
2497 cache_block_put(file_buffer);
2498 }
2499
2500 pthread_cleanup_pop(0);
2501 }
2502
2503
2504 void *frag_order_deflator(void *arg)
2505 {
2506 void *stream = NULL;
2507 int res;
2508
2509 res = compressor_init(comp, &stream, block_size, 1);
2510 if(res)
2511 BAD_ERROR("frag_deflator:: compressor_init failed\n");
2512
2513 while(1) {
2514 int c_byte;
2515 struct file_buffer *file_buffer = queue_get(to_frag);
2516 struct file_buffer *write_buffer =
2517 cache_get(fwriter_buffer, file_buffer->block);
2518
2519 c_byte = mangle2(stream, write_buffer->data, file_buffer->data,
2520 file_buffer->size, block_size, noF, 1);
2521 write_buffer->block = file_buffer->block;
2522 write_buffer->sequence = file_buffer->sequence;
2523 write_buffer->size = c_byte;
2524 write_buffer->fragment = FALSE;
2525 seq_queue_put(to_order, write_buffer);
2526 TRACE("Writing fragment %lld, uncompressed size %d, "
2527 "compressed size %d\n", file_buffer->block,
2528 file_buffer->size, SQUASHFS_COMPRESSED_SIZE_BLOCK(c_byte));
2529 cache_block_put(file_buffer);
2530 }
2531 }
2532
2533
2534 void *frag_orderer(void *arg)
2535 {
2536 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
2537
2538 while(1) {
2539 struct file_buffer *write_buffer = seq_queue_get(to_order);
2540 int block = write_buffer->block;
2541
2542 pthread_mutex_lock(&fragment_mutex);
2543 fragment_table[block].size = write_buffer->size;
2544 fragment_table[block].start_block = bytes;
2545 write_buffer->block = bytes;
2546 bytes += SQUASHFS_COMPRESSED_SIZE_BLOCK(write_buffer->size);
2547 write_buffer->size = SQUASHFS_COMPRESSED_SIZE_BLOCK(write_buffer->size);
2548 fragments_outstanding --;
2549 log_fragment(block, write_buffer->block);
2550 queue_put(to_writer, write_buffer);
2551 pthread_cond_signal(&fragment_waiting);
2552 pthread_mutex_unlock(&fragment_mutex);
2553 }
2554
2555 pthread_cleanup_pop(0);
2556 }
2557
2558
2559 struct file_buffer *get_file_buffer()
2560 {
2561 struct file_buffer *file_buffer = seq_queue_get(to_main);
2562
2563 return file_buffer;
2564 }
2565
2566
2567 void write_file_empty(squashfs_inode *inode, struct dir_ent *dir_ent,
2568 struct file_buffer *file_buffer, int *duplicate_file)
2569 {
2570 file_count ++;
2571 *duplicate_file = FALSE;
2572 cache_block_put(file_buffer);
2573 create_inode(inode, NULL, dir_ent, SQUASHFS_FILE_TYPE, 0, 0, 0,
2574 NULL, &empty_fragment, NULL, 0);
2575 }
2576
2577
2578 void write_file_frag(squashfs_inode *inode, struct dir_ent *dir_ent,
2579 struct file_buffer *file_buffer, int *duplicate_file)
2580 {
2581 int size = file_buffer->file_size;
2582 struct fragment *fragment;
2583 unsigned short checksum = file_buffer->checksum;
2584 char dont_put;
2585
2586 fragment = frag_duplicate(file_buffer, &dont_put);
2587 *duplicate_file = !fragment;
2588 if(!fragment) {
2589 fragment = get_and_fill_fragment(file_buffer, dir_ent);
2590 if(duplicate_checking)
2591 add_non_dup(size, 0, NULL, 0, fragment, 0, checksum,
2592 TRUE, TRUE);
2593 }
2594
2595 if(dont_put)
2596 free(file_buffer);
2597 else
2598 cache_block_put(file_buffer);
2599
2600 total_bytes += size;
2601 file_count ++;
2602
2603 inc_progress_bar();
2604
2605 create_inode(inode, NULL, dir_ent, SQUASHFS_FILE_TYPE, size, 0,
2606 0, NULL, fragment, NULL, 0);
2607
2608 if(!duplicate_checking)
2609 free_fragment(fragment);
2610 }
2611
2612
2613 void log_file(struct dir_ent *dir_ent, long long start)
2614 {
2615 if(logging && start)
2616 fprintf(log_fd, "%s, %lld\n", pathname(dir_ent), start);
2617 }
2618
2619
2620 int write_file_process(squashfs_inode *inode, struct dir_ent *dir_ent,
2621 struct file_buffer *read_buffer, int *duplicate_file)
2622 {
2623 long long read_size, file_bytes, start;
2624 struct fragment *fragment;
2625 unsigned int *block_list = NULL;
2626 int block = 0, status;
2627 long long sparse = 0;
2628 struct file_buffer *fragment_buffer = NULL;
2629
2630 *duplicate_file = FALSE;
2631
2632 if(reproducible)
2633 ensure_fragments_flushed();
2634 else
2635 lock_fragments();
2636
2637 file_bytes = 0;
2638 start = bytes;
2639 while (1) {
2640 read_size = read_buffer->file_size;
2641 if(read_buffer->fragment) {
2642 fragment_buffer = read_buffer;
2643 if(block == 0)
2644 start=0;
2645 } else {
2646 block_list = realloc(block_list, (block + 1) *
2647 sizeof(unsigned int));
2648 if(block_list == NULL)
2649 MEM_ERROR();
2650 block_list[block ++] = read_buffer->c_byte;
2651 if(read_buffer->c_byte) {
2652 read_buffer->block = bytes;
2653 bytes += read_buffer->size;
2654 cache_hash(read_buffer, read_buffer->block);
2655 file_bytes += read_buffer->size;
2656 queue_put(to_writer, read_buffer);
2657 } else {
2658 sparse += read_buffer->size;
2659 cache_block_put(read_buffer);
2660 }
2661 }
2662 inc_progress_bar();
2663
2664 if(read_size != -1)
2665 break;
2666
2667 read_buffer = get_file_buffer();
2668 if(read_buffer->error)
2669 goto read_err;
2670 }
2671
2672 if(!reproducible)
2673 unlock_fragments();
2674
2675 fragment = get_and_fill_fragment(fragment_buffer, dir_ent);
2676
2677 if(duplicate_checking)
2678 add_non_dup(read_size, file_bytes, block_list, start, fragment,
2679 0, fragment_buffer ? fragment_buffer->checksum : 0,
2680 FALSE, TRUE);
2681 cache_block_put(fragment_buffer);
2682 file_count ++;
2683 total_bytes += read_size;
2684
2685 create_inode(inode, NULL, dir_ent, SQUASHFS_FILE_TYPE, read_size, start,
2686 block, block_list, fragment, NULL, sparse);
2687 log_file(dir_ent, start);
2688
2689 if(duplicate_checking == FALSE) {
2690 free(block_list);
2691 free_fragment(fragment);
2692 }
2693
2694 return 0;
2695
2696 read_err:
2697 dec_progress_bar(block);
2698 status = read_buffer->error;
2699 bytes = start;
2700 if(!block_device) {
2701 int res;
2702
2703 queue_put(to_writer, NULL);
2704 if(queue_get(from_writer) != 0)
2705 EXIT_MKSQUASHFS();
2706 res = ftruncate(fd, bytes);
2707 if(res != 0)
2708 BAD_ERROR("Failed to truncate dest file because %s\n",
2709 strerror(errno));
2710 }
2711 if(!reproducible)
2712 unlock_fragments();
2713 free(block_list);
2714 cache_block_put(read_buffer);
2715 return status;
2716 }
2717
2718
2719 int write_file_blocks_dup(squashfs_inode *inode, struct dir_ent *dir_ent,
2720 struct file_buffer *read_buffer, int *duplicate_file)
2721 {
2722 int block, thresh;
2723 long long read_size = read_buffer->file_size;
2724 long long file_bytes, dup_start, start;
2725 struct fragment *fragment;
2726 struct file_info *dupl_ptr;
2727 int blocks = (read_size + block_size - 1) >> block_log;
2728 unsigned int *block_list, *block_listp;
2729 struct file_buffer **buffer_list;
2730 int status;
2731 long long sparse = 0;
2732 struct file_buffer *fragment_buffer = NULL;
2733
2734 block_list = malloc(blocks * sizeof(unsigned int));
2735 if(block_list == NULL)
2736 MEM_ERROR();
2737 block_listp = block_list;
2738
2739 buffer_list = malloc(blocks * sizeof(struct file_buffer *));
2740 if(buffer_list == NULL)
2741 MEM_ERROR();
2742
2743 if(reproducible)
2744 ensure_fragments_flushed();
2745 else
2746 lock_fragments();
2747
2748 file_bytes = 0;
2749 start = dup_start = bytes;
2750 thresh = blocks > bwriter_size ? blocks - bwriter_size : 0;
2751
2752 for(block = 0; block < blocks;) {
2753 if(read_buffer->fragment) {
2754 block_list[block] = 0;
2755 buffer_list[block] = NULL;
2756 fragment_buffer = read_buffer;
2757 blocks = read_size >> block_log;
2758 } else {
2759 block_list[block] = read_buffer->c_byte;
2760
2761 if(read_buffer->c_byte) {
2762 read_buffer->block = bytes;
2763 bytes += read_buffer->size;
2764 file_bytes += read_buffer->size;
2765 cache_hash(read_buffer, read_buffer->block);
2766 if(block < thresh) {
2767 buffer_list[block] = NULL;
2768 queue_put(to_writer, read_buffer);
2769 } else
2770 buffer_list[block] = read_buffer;
2771 } else {
2772 buffer_list[block] = NULL;
2773 sparse += read_buffer->size;
2774 cache_block_put(read_buffer);
2775 }
2776 }
2777 inc_progress_bar();
2778
2779 if(++block < blocks) {
2780 read_buffer = get_file_buffer();
2781 if(read_buffer->error)
2782 goto read_err;
2783 }
2784 }
2785
2786 dupl_ptr = duplicate(read_size, file_bytes, &block_listp, &dup_start,
2787 &fragment, fragment_buffer, blocks, 0, FALSE);
2788
2789 if(dupl_ptr) {
2790 *duplicate_file = FALSE;
2791 for(block = thresh; block < blocks; block ++)
2792 if(buffer_list[block])
2793 queue_put(to_writer, buffer_list[block]);
2794 fragment = get_and_fill_fragment(fragment_buffer, dir_ent);
2795 dupl_ptr->fragment = fragment;
2796 } else {
2797 *duplicate_file = TRUE;
2798 for(block = thresh; block < blocks; block ++)
2799 cache_block_put(buffer_list[block]);
2800 bytes = start;
2801 if(thresh && !block_device) {
2802 int res;
2803
2804 queue_put(to_writer, NULL);
2805 if(queue_get(from_writer) != 0)
2806 EXIT_MKSQUASHFS();
2807 res = ftruncate(fd, bytes);
2808 if(res != 0)
2809 BAD_ERROR("Failed to truncate dest file because"
2810 " %s\n", strerror(errno));
2811 }
2812 }
2813
2814 if(!reproducible)
2815 unlock_fragments();
2816 cache_block_put(fragment_buffer);
2817 free(buffer_list);
2818 file_count ++;
2819 total_bytes += read_size;
2820
2821 /*
2822 * sparse count is needed to ensure squashfs correctly reports a
2823 * a smaller block count on stat calls to sparse files. This is
2824 * to ensure intelligent applications like cp correctly handle the
2825 * file as a sparse file. If the file in the original filesystem isn't
2826 * stored as a sparse file then still store it sparsely in squashfs, but
2827 * report it as non-sparse on stat calls to preserve semantics
2828 */
2829 if(sparse && (dir_ent->inode->buf.st_blocks << 9) >= read_size)
2830 sparse = 0;
2831
2832 create_inode(inode, NULL, dir_ent, SQUASHFS_FILE_TYPE, read_size,
2833 dup_start, blocks, block_listp, fragment, NULL, sparse);
2834
2835 if(*duplicate_file == TRUE)
2836 free(block_list);
2837 else
2838 log_file(dir_ent, dup_start);
2839
2840 return 0;
2841
2842 read_err:
2843 dec_progress_bar(block);
2844 status = read_buffer->error;
2845 bytes = start;
2846 if(thresh && !block_device) {
2847 int res;
2848
2849 queue_put(to_writer, NULL);
2850 if(queue_get(from_writer) != 0)
2851 EXIT_MKSQUASHFS();
2852 res = ftruncate(fd, bytes);
2853 if(res != 0)
2854 BAD_ERROR("Failed to truncate dest file because %s\n",
2855 strerror(errno));
2856 }
2857 if(!reproducible)
2858 unlock_fragments();
2859 for(blocks = thresh; blocks < block; blocks ++)
2860 cache_block_put(buffer_list[blocks]);
2861 free(buffer_list);
2862 free(block_list);
2863 cache_block_put(read_buffer);
2864 return status;
2865 }
2866
2867
2868 int write_file_blocks(squashfs_inode *inode, struct dir_ent *dir_ent,
2869 struct file_buffer *read_buffer, int *dup)
2870 {
2871 long long read_size = read_buffer->file_size;
2872 long long file_bytes, start;
2873 struct fragment *fragment;
2874 unsigned int *block_list;
2875 int block, status;
2876 int blocks = (read_size + block_size - 1) >> block_log;
2877 long long sparse = 0;
2878 struct file_buffer *fragment_buffer = NULL;
2879
2880 if(pre_duplicate(read_size))
2881 return write_file_blocks_dup(inode, dir_ent, read_buffer, dup);
2882
2883 *dup = FALSE;
2884
2885 block_list = malloc(blocks * sizeof(unsigned int));
2886 if(block_list == NULL)
2887 MEM_ERROR();
2888
2889 if(reproducible)
2890 ensure_fragments_flushed();
2891 else
2892 lock_fragments();
2893
2894 file_bytes = 0;
2895 start = bytes;
2896 for(block = 0; block < blocks;) {
2897 if(read_buffer->fragment) {
2898 block_list[block] = 0;
2899 fragment_buffer = read_buffer;
2900 blocks = read_size >> block_log;
2901 } else {
2902 block_list[block] = read_buffer->c_byte;
2903 if(read_buffer->c_byte) {
2904 read_buffer->block = bytes;
2905 bytes += read_buffer->size;
2906 cache_hash(read_buffer, read_buffer->block);
2907 file_bytes += read_buffer->size;
2908 queue_put(to_writer, read_buffer);
2909 } else {
2910 sparse += read_buffer->size;
2911 cache_block_put(read_buffer);
2912 }
2913 }
2914 inc_progress_bar();
2915
2916 if(++block < blocks) {
2917 read_buffer = get_file_buffer();
2918 if(read_buffer->error)
2919 goto read_err;
2920 }
2921 }
2922
2923 if(!reproducible)
2924 unlock_fragments();
2925 fragment = get_and_fill_fragment(fragment_buffer, dir_ent);
2926
2927 if(duplicate_checking)
2928 add_non_dup(read_size, file_bytes, block_list, start, fragment,
2929 0, fragment_buffer ? fragment_buffer->checksum : 0,
2930 FALSE, TRUE);
2931 cache_block_put(fragment_buffer);
2932 file_count ++;
2933 total_bytes += read_size;
2934
2935 /*
2936 * sparse count is needed to ensure squashfs correctly reports a
2937 * a smaller block count on stat calls to sparse files. This is
2938 * to ensure intelligent applications like cp correctly handle the
2939 * file as a sparse file. If the file in the original filesystem isn't
2940 * stored as a sparse file then still store it sparsely in squashfs, but
2941 * report it as non-sparse on stat calls to preserve semantics
2942 */
2943 if(sparse && (dir_ent->inode->buf.st_blocks << 9) >= read_size)
2944 sparse = 0;
2945
2946 create_inode(inode, NULL, dir_ent, SQUASHFS_FILE_TYPE, read_size, start,
2947 blocks, block_list, fragment, NULL, sparse);
2948 log_file(dir_ent, start);
2949
2950 if(duplicate_checking == FALSE) {
2951 free(block_list);
2952 free_fragment(fragment);
2953 }
2954
2955 return 0;
2956
2957 read_err:
2958 dec_progress_bar(block);
2959 status = read_buffer->error;
2960 bytes = start;
2961 if(!block_device) {
2962 int res;
2963
2964 queue_put(to_writer, NULL);
2965 if(queue_get(from_writer) != 0)
2966 EXIT_MKSQUASHFS();
2967 res = ftruncate(fd, bytes);
2968 if(res != 0)
2969 BAD_ERROR("Failed to truncate dest file because %s\n",
2970 strerror(errno));
2971 }
2972 if(!reproducible)
2973 unlock_fragments();
2974 free(block_list);
2975 cache_block_put(read_buffer);
2976 return status;
2977 }
2978
2979
2980 void write_file(squashfs_inode *inode, struct dir_ent *dir, int *dup)
2981 {
2982 int status;
2983 struct file_buffer *read_buffer;
2984
2985 again:
2986 read_buffer = get_file_buffer();
2987 status = read_buffer->error;
2988
2989 if(status)
2990 cache_block_put(read_buffer);
2991 else if(read_buffer->file_size == -1)
2992 status = write_file_process(inode, dir, read_buffer, dup);
2993 else if(read_buffer->file_size == 0)
2994 write_file_empty(inode, dir, read_buffer, dup);
2995 else if(read_buffer->fragment && read_buffer->c_byte)
2996 write_file_frag(inode, dir, read_buffer, dup);
2997 else
2998 status = write_file_blocks(inode, dir, read_buffer, dup);
2999
3000 if(status == 2) {
3001 ERROR("File %s changed size while reading filesystem, "
3002 "attempting to re-read\n", pathname(dir));
3003 goto again;
3004 } else if(status == 1) {
3005 ERROR_START("Failed to read file %s", pathname(dir));
3006 ERROR_EXIT(", creating empty file\n");
3007 write_file_empty(inode, dir, NULL, dup);
3008 }
3009 }
3010
3011
3012 #define BUFF_SIZE 512
3013 char *name;
3014 char *basename_r();
3015
3016 char *getbase(char *pathname)
3017 {
3018 static char *b_buffer = NULL;
3019 static int b_size = BUFF_SIZE;
3020 char *result;
3021
3022 if(b_buffer == NULL) {
3023 b_buffer = malloc(b_size);
3024 if(b_buffer == NULL)
3025 MEM_ERROR();
3026 }
3027
3028 while(1) {
3029 if(*pathname != '/') {
3030 result = getcwd(b_buffer, b_size);
3031 if(result == NULL && errno != ERANGE)
3032 BAD_ERROR("Getcwd failed in getbase\n");
3033
3034 /* enough room for pathname + "/" + '\0' terminator? */
3035 if(result && strlen(pathname) + 2 <=
3036 b_size - strlen(b_buffer)) {
3037 strcat(strcat(b_buffer, "/"), pathname);
3038 break;
3039 }
3040 } else if(strlen(pathname) < b_size) {
3041 strcpy(b_buffer, pathname);
3042 break;
3043 }
3044
3045 /* Buffer not large enough, realloc and try again */
3046 b_buffer = realloc(b_buffer, b_size += BUFF_SIZE);
3047 if(b_buffer == NULL)
3048 MEM_ERROR();
3049 }
3050
3051 name = b_buffer;
3052 if(((result = basename_r()) == NULL) || (strcmp(result, "..") == 0))
3053 return NULL;
3054 else
3055 return result;
3056 }
3057
3058
3059 char *basename_r()
3060 {
3061 char *s;
3062 char *p;
3063 int n = 1;
3064
3065 for(;;) {
3066 s = name;
3067 if(*name == '\0')
3068 return NULL;
3069 if(*name != '/') {
3070 while(*name != '\0' && *name != '/') name++;
3071 n = name - s;
3072 }
3073 while(*name == '/') name++;
3074 if(strncmp(s, ".", n) == 0)
3075 continue;
3076 if((*name == '\0') || (strncmp(s, "..", n) == 0) ||
3077 ((p = basename_r()) == NULL)) {
3078 s[n] = '\0';
3079 return s;
3080 }
3081 if(strcmp(p, "..") == 0)
3082 continue;
3083 return p;
3084 }
3085 }
3086
3087
3088 struct inode_info *lookup_inode3(struct stat *buf, int pseudo, int id,
3089 char *symlink, int bytes)
3090 {
3091 int ino_hash = INODE_HASH(buf->st_dev, buf->st_ino);
3092 struct inode_info *inode;
3093
3094 /*
3095 * Look-up inode in hash table, if it already exists we have a
3096 * hard-link, so increment the nlink count and return it.
3097 * Don't do the look-up for directories because we don't hard-link
3098 * directories.
3099 */
3100 if ((buf->st_mode & S_IFMT) != S_IFDIR) {
3101 for(inode = inode_info[ino_hash]; inode; inode = inode->next) {
3102 if(memcmp(buf, &inode->buf, sizeof(struct stat)) == 0) {
3103 inode->nlink ++;
3104 return inode;
3105 }
3106 }
3107 }
3108
3109 inode = malloc(sizeof(struct inode_info) + bytes);
3110 if(inode == NULL)
3111 MEM_ERROR();
3112
3113 if(bytes)
3114 memcpy(&inode->symlink, symlink, bytes);
3115 memcpy(&inode->buf, buf, sizeof(struct stat));
3116 inode->read = FALSE;
3117 inode->root_entry = FALSE;
3118 inode->pseudo_file = pseudo;
3119 inode->pseudo_id = id;
3120 inode->inode = SQUASHFS_INVALID_BLK;
3121 inode->nlink = 1;
3122 inode->inode_number = 0;
3123
3124 /*
3125 * Copy filesystem wide defaults into inode, these filesystem
3126 * wide defaults may be altered on an individual inode basis by
3127 * user specified actions
3128 *
3129 */
3130 inode->no_fragments = no_fragments;
3131 inode->always_use_fragments = always_use_fragments;
3132 inode->noD = noD;
3133 inode->noF = noF;
3134
3135 inode->next = inode_info[ino_hash];
3136 inode_info[ino_hash] = inode;
3137
3138 return inode;
3139 }
3140
3141
3142 struct inode_info *lookup_inode2(struct stat *buf, int pseudo, int id)
3143 {
3144 return lookup_inode3(buf, pseudo, id, NULL, 0);
3145 }
3146
3147
3148 static inline struct inode_info *lookup_inode(struct stat *buf)
3149 {
3150 return lookup_inode2(buf, 0, 0);
3151 }
3152
3153
3154 static inline void alloc_inode_no(struct inode_info *inode, unsigned int use_this)
3155 {
3156 if (inode->inode_number == 0) {
3157 inode->inode_number = use_this ? : inode_no ++;
3158 if((inode->buf.st_mode & S_IFMT) == S_IFREG)
3159 progress_bar_size((inode->buf.st_size + block_size - 1)
3160 >> block_log);
3161 }
3162 }
3163
3164
3165 static inline struct dir_ent *create_dir_entry(char *name, char *source_name,
3166 char *nonstandard_pathname, struct dir_info *dir)
3167 {
3168 struct dir_ent *dir_ent = malloc(sizeof(struct dir_ent));
3169 if(dir_ent == NULL)
3170 MEM_ERROR();
3171
3172 dir_ent->name = name;
3173 dir_ent->source_name = source_name;
3174 dir_ent->nonstandard_pathname = nonstandard_pathname;
3175 dir_ent->our_dir = dir;
3176 dir_ent->inode = NULL;
3177 dir_ent->next = NULL;
3178
3179 return dir_ent;
3180 }
3181
3182
3183 static inline void add_dir_entry(struct dir_ent *dir_ent, struct dir_info *sub_dir,
3184 struct inode_info *inode_info)
3185 {
3186 struct dir_info *dir = dir_ent->our_dir;
3187
3188 if(sub_dir)
3189 sub_dir->dir_ent = dir_ent;
3190 dir_ent->inode = inode_info;
3191 dir_ent->dir = sub_dir;
3192
3193 dir_ent->next = dir->list;
3194 dir->list = dir_ent;
3195 dir->count++;
3196 }
3197
3198
3199 static inline void add_dir_entry2(char *name, char *source_name,
3200 char *nonstandard_pathname, struct dir_info *sub_dir,
3201 struct inode_info *inode_info, struct dir_info *dir)
3202 {
3203 struct dir_ent *dir_ent = create_dir_entry(name, source_name,
3204 nonstandard_pathname, dir);
3205
3206
3207 add_dir_entry(dir_ent, sub_dir, inode_info);
3208 }
3209
3210
3211 static inline void free_dir_entry(struct dir_ent *dir_ent)
3212 {
3213 if(dir_ent->name)
3214 free(dir_ent->name);
3215
3216 if(dir_ent->source_name)
3217 free(dir_ent->source_name);
3218
3219 if(dir_ent->nonstandard_pathname)
3220 free(dir_ent->nonstandard_pathname);
3221
3222 /* if this entry has been associated with an inode, then we need
3223 * to update the inode nlink count. Orphaned inodes are harmless, and
3224 * is easier to leave them than go to the bother of deleting them */
3225 if(dir_ent->inode && !dir_ent->inode->root_entry)
3226 dir_ent->inode->nlink --;
3227
3228 free(dir_ent);
3229 }
3230
3231
3232 static inline void add_excluded(struct dir_info *dir)
3233 {
3234 dir->excluded ++;
3235 }
3236
3237
3238 void dir_scan(squashfs_inode *inode, char *pathname,
3239 struct dir_ent *(_readdir)(struct dir_info *), int progress)
3240 {
3241 struct stat buf;
3242 struct dir_ent *dir_ent;
3243
3244 root_dir = dir_scan1(pathname, "", paths, _readdir, 1);
3245 if(root_dir == NULL)
3246 return;
3247
3248 /* Create root directory dir_ent and associated inode, and connect
3249 * it to the root directory dir_info structure */
3250 dir_ent = create_dir_entry("", NULL, pathname,
3251 scan1_opendir("", "", 0));
3252
3253 if(pathname[0] == '\0') {
3254 /*
3255 * dummy top level directory, if multiple sources specified on
3256 * command line
3257 */
3258 memset(&buf, 0, sizeof(buf));
3259 buf.st_mode = (root_mode_opt) ? root_mode | S_IFDIR : S_IRWXU | S_IRWXG | S_IRWXO | S_IFDIR;
3260 buf.st_uid = getuid();
3261 buf.st_gid = getgid();
3262 buf.st_mtime = time(NULL);
3263 buf.st_dev = 0;
3264 buf.st_ino = 0;
3265 dir_ent->inode = lookup_inode2(&buf, PSEUDO_FILE_OTHER, 0);
3266 } else {
3267 if(lstat(pathname, &buf) == -1)
3268 /* source directory has disappeared? */
3269 BAD_ERROR("Cannot stat source directory %s because %s\n",
3270 pathname, strerror(errno));
3271 if(root_mode_opt)
3272 buf.st_mode = root_mode | S_IFDIR;
3273
3274 dir_ent->inode = lookup_inode(&buf);
3275 }
3276
3277 dir_ent->dir = root_dir;
3278 root_dir->dir_ent = dir_ent;
3279
3280 /*
3281 * Process most actions and any pseudo files
3282 */
3283 if(actions() || get_pseudo())
3284 dir_scan2(root_dir, get_pseudo());
3285
3286 /*
3287 * Process move actions
3288 */
3289 if(move_actions()) {
3290 dir_scan3(root_dir);
3291 do_move_actions();
3292 }
3293
3294 /*
3295 * Process prune actions
3296 */
3297 if(prune_actions())
3298 dir_scan4(root_dir);
3299
3300 /*
3301 * Process empty actions
3302 */
3303 if(empty_actions())
3304 dir_scan5(root_dir);
3305
3306 /*
3307 * Sort directories and compute the inode numbers
3308 */
3309 dir_scan6(root_dir);
3310
3311 alloc_inode_no(dir_ent->inode, root_inode_number);
3312
3313 eval_actions(root_dir, dir_ent);
3314
3315 if(sorted)
3316 generate_file_priorities(root_dir, 0,
3317 &root_dir->dir_ent->inode->buf);
3318
3319 if(appending) {
3320 sigset_t sigmask;
3321
3322 restore_thread = init_restore_thread();
3323 sigemptyset(&sigmask);
3324 sigaddset(&sigmask, SIGINT);
3325 sigaddset(&sigmask, SIGTERM);
3326 sigaddset(&sigmask, SIGUSR1);
3327 if(pthread_sigmask(SIG_BLOCK, &sigmask, NULL) != 0)
3328 BAD_ERROR("Failed to set signal mask\n");
3329 write_destination(fd, SQUASHFS_START, 4, "\0\0\0\0");
3330 }
3331
3332 queue_put(to_reader, root_dir);
3333
3334 set_progressbar_state(progress);
3335
3336 if(sorted)
3337 sort_files_and_write(root_dir);
3338
3339 dir_scan7(inode, root_dir);
3340 dir_ent->inode->inode = *inode;
3341 dir_ent->inode->type = SQUASHFS_DIR_TYPE;
3342 }
3343
3344
3345 /*
3346 * dir_scan1 routines...
3347 * These scan the source directories into memory for processing.
3348 * Exclude actions are processed here (in contrast to the other actions)
3349 * because they affect what is scanned.
3350 */
3351 struct dir_info *scan1_opendir(char *pathname, char *subpath, int depth)
3352 {
3353 struct dir_info *dir;
3354
3355 dir = malloc(sizeof(struct dir_info));
3356 if(dir == NULL)
3357 MEM_ERROR();
3358
3359 if(pathname[0] != '\0') {
3360 dir->linuxdir = opendir(pathname);
3361 if(dir->linuxdir == NULL) {
3362 free(dir);
3363 return NULL;
3364 }
3365 }
3366
3367 dir->pathname = strdup(pathname);
3368 dir->subpath = strdup(subpath);
3369 dir->count = 0;
3370 dir->directory_count = 0;
3371 dir->dir_is_ldir = TRUE;
3372 dir->list = NULL;
3373 dir->depth = depth;
3374 dir->excluded = 0;
3375
3376 return dir;
3377 }
3378
3379
3380 struct dir_ent *scan1_encomp_readdir(struct dir_info *dir)
3381 {
3382 static int index = 0;
3383
3384 if(dir->count < old_root_entries) {
3385 int i;
3386
3387 for(i = 0; i < old_root_entries; i++) {
3388 if(old_root_entry[i].inode.type == SQUASHFS_DIR_TYPE)
3389 dir->directory_count ++;
3390 add_dir_entry2(old_root_entry[i].name, NULL, NULL, NULL,
3391 &old_root_entry[i].inode, dir);
3392 }
3393 }
3394
3395 while(index < source) {
3396 char *basename = NULL;
3397 char *dir_name = getbase(source_path[index]);
3398 int pass = 1, res;
3399
3400 if(dir_name == NULL) {
3401 ERROR_START("Bad source directory %s",
3402 source_path[index]);
3403 ERROR_EXIT(" - skipping ...\n");
3404 index ++;
3405 continue;
3406 }
3407 dir_name = strdup(dir_name);
3408 for(;;) {
3409 struct dir_ent *dir_ent = dir->list;
3410
3411 for(; dir_ent && strcmp(dir_ent->name, dir_name) != 0;
3412 dir_ent = dir_ent->next);
3413 if(dir_ent == NULL)
3414 break;
3415 ERROR("Source directory entry %s already used! - trying"
3416 " ", dir_name);
3417 if(pass == 1)
3418 basename = dir_name;
3419 else
3420 free(dir_name);
3421 res = asprintf(&dir_name, "%s_%d", basename, pass++);
3422 if(res == -1)
3423 BAD_ERROR("asprintf failed in "
3424 "scan1_encomp_readdir\n");
3425 ERROR("%s\n", dir_name);
3426 }
3427 return create_dir_entry(dir_name, basename,
3428 strdup(source_path[index ++]), dir);
3429 }
3430 return NULL;
3431 }
3432
3433
3434 struct dir_ent *scan1_single_readdir(struct dir_info *dir)
3435 {
3436 struct dirent *d_name;
3437 int i;
3438
3439 if(dir->count < old_root_entries) {
3440 for(i = 0; i < old_root_entries; i++) {
3441 if(old_root_entry[i].inode.type == SQUASHFS_DIR_TYPE)
3442 dir->directory_count ++;
3443 add_dir_entry2(old_root_entry[i].name, NULL, NULL, NULL,
3444 &old_root_entry[i].inode, dir);
3445 }
3446 }
3447
3448 if((d_name = readdir(dir->linuxdir)) != NULL) {
3449 char *basename = NULL;
3450 char *dir_name = strdup(d_name->d_name);
3451 int pass = 1, res;
3452
3453 for(;;) {
3454 struct dir_ent *dir_ent = dir->list;
3455
3456 for(; dir_ent && strcmp(dir_ent->name, dir_name) != 0;
3457 dir_ent = dir_ent->next);
3458 if(dir_ent == NULL)
3459 break;
3460 ERROR("Source directory entry %s already used! - trying"
3461 " ", dir_name);
3462 if (pass == 1)
3463 basename = dir_name;
3464 else
3465 free(dir_name);
3466 res = asprintf(&dir_name, "%s_%d", d_name->d_name, pass++);
3467 if(res == -1)
3468 BAD_ERROR("asprintf failed in "
3469 "scan1_single_readdir\n");
3470 ERROR("%s\n", dir_name);
3471 }
3472 return create_dir_entry(dir_name, basename, NULL, dir);
3473 }
3474
3475 return NULL;
3476 }
3477
3478
3479 struct dir_ent *scan1_readdir(struct dir_info *dir)
3480 {
3481 struct dirent *d_name = readdir(dir->linuxdir);
3482
3483 return d_name ?
3484 create_dir_entry(strdup(d_name->d_name), NULL, NULL, dir) :
3485 NULL;
3486 }
3487
3488
3489 void scan1_freedir(struct dir_info *dir)
3490 {
3491 if(dir->pathname[0] != '\0')
3492 closedir(dir->linuxdir);
3493 }
3494
3495
3496 struct dir_info *dir_scan1(char *filename, char *subpath,
3497 struct pathnames *paths,
3498 struct dir_ent *(_readdir)(struct dir_info *), int depth)
3499 {
3500 struct dir_info *dir = scan1_opendir(filename, subpath, depth);
3501 struct dir_ent *dir_ent;
3502
3503 if(dir == NULL) {
3504 ERROR_START("Could not open %s", filename);
3505 ERROR_EXIT(", skipping...\n");
3506 return NULL;
3507 }
3508
3509 while((dir_ent = _readdir(dir))) {
3510 struct dir_info *sub_dir;
3511 struct stat buf;
3512 struct pathnames *new = NULL;
3513 char *filename = pathname(dir_ent);
3514 char *subpath = NULL;
3515 char *dir_name = dir_ent->name;
3516
3517 if(strcmp(dir_name, ".") == 0 || strcmp(dir_name, "..") == 0) {
3518 free_dir_entry(dir_ent);
3519 continue;
3520 }
3521
3522 if(lstat(filename, &buf) == -1) {
3523 ERROR_START("Cannot stat dir/file %s because %s",
3524 filename, strerror(errno));
3525 ERROR_EXIT(", ignoring\n");
3526 free_dir_entry(dir_ent);
3527 continue;
3528 }
3529
3530 if((buf.st_mode & S_IFMT) != S_IFREG &&
3531 (buf.st_mode & S_IFMT) != S_IFDIR &&
3532 (buf.st_mode & S_IFMT) != S_IFLNK &&
3533 (buf.st_mode & S_IFMT) != S_IFCHR &&
3534 (buf.st_mode & S_IFMT) != S_IFBLK &&
3535 (buf.st_mode & S_IFMT) != S_IFIFO &&
3536 (buf.st_mode & S_IFMT) != S_IFSOCK) {
3537 ERROR_START("File %s has unrecognised filetype %d",
3538 filename, buf.st_mode & S_IFMT);
3539 ERROR_EXIT(", ignoring\n");
3540 free_dir_entry(dir_ent);
3541 continue;
3542 }
3543
3544 if((old_exclude && old_excluded(filename, &buf)) ||
3545 (!old_exclude && excluded(dir_name, paths, &new))) {
3546 add_excluded(dir);
3547 free_dir_entry(dir_ent);
3548 continue;
3549 }
3550
3551 if(exclude_actions()) {
3552 subpath = subpathname(dir_ent);
3553
3554 if(eval_exclude_actions(dir_name, filename, subpath,
3555 &buf, depth, dir_ent)) {
3556 add_excluded(dir);
3557 free_dir_entry(dir_ent);
3558 continue;
3559 }
3560 }
3561
3562 switch(buf.st_mode & S_IFMT) {
3563 case S_IFDIR:
3564 if(subpath == NULL)
3565 subpath = subpathname(dir_ent);
3566
3567 sub_dir = dir_scan1(filename, subpath, new,
3568 scan1_readdir, depth + 1);
3569 if(sub_dir) {
3570 dir->directory_count ++;
3571 add_dir_entry(dir_ent, sub_dir,
3572 lookup_inode(&buf));
3573 } else
3574 free_dir_entry(dir_ent);
3575 break;
3576 case S_IFLNK: {
3577 int byte;
3578 static char buff[65536]; /* overflow safe */
3579
3580 byte = readlink(filename, buff, 65536);
3581 if(byte == -1) {
3582 ERROR_START("Failed to read symlink %s",
3583 filename);
3584 ERROR_EXIT(", ignoring\n");
3585 } else if(byte == 65536) {
3586 ERROR_START("Symlink %s is greater than 65536 "
3587 "bytes!", filename);
3588 ERROR_EXIT(", ignoring\n");
3589 } else {
3590 /* readlink doesn't 0 terminate the returned
3591 * path */
3592 buff[byte] = '\0';
3593 add_dir_entry(dir_ent, NULL, lookup_inode3(&buf,
3594 0, 0, buff, byte + 1));
3595 }
3596 break;
3597 }
3598 default:
3599 add_dir_entry(dir_ent, NULL, lookup_inode(&buf));
3600 }
3601
3602 free(new);
3603 }
3604
3605 scan1_freedir(dir);
3606
3607 return dir;
3608 }
3609
3610
3611 /*
3612 * dir_scan2 routines...
3613 * This processes most actions and any pseudo files
3614 */
3615 struct dir_ent *scan2_readdir(struct dir_info *dir, struct dir_ent *dir_ent)
3616 {
3617 if (dir_ent == NULL)
3618 dir_ent = dir->list;
3619 else
3620 dir_ent = dir_ent->next;
3621
3622 for(; dir_ent && dir_ent->inode->root_entry; dir_ent = dir_ent->next);
3623
3624 return dir_ent;
3625 }
3626
3627
3628 struct dir_ent *scan2_lookup(struct dir_info *dir, char *name)
3629 {
3630 struct dir_ent *dir_ent = dir->list;
3631
3632 for(; dir_ent && strcmp(dir_ent->name, name) != 0;
3633 dir_ent = dir_ent->next);
3634
3635 return dir_ent;
3636 }
3637
3638
3639 void dir_scan2(struct dir_info *dir, struct pseudo *pseudo)
3640 {
3641 struct dir_ent *dir_ent = NULL;
3642 struct pseudo_entry *pseudo_ent;
3643 struct stat buf;
3644 static int pseudo_ino = 1;
3645
3646 while((dir_ent = scan2_readdir(dir, dir_ent)) != NULL) {
3647 struct inode_info *inode_info = dir_ent->inode;
3648 struct stat *buf = &inode_info->buf;
3649 char *name = dir_ent->name;
3650
3651 eval_actions(root_dir, dir_ent);
3652
3653 if((buf->st_mode & S_IFMT) == S_IFDIR)
3654 dir_scan2(dir_ent->dir, pseudo_subdir(name, pseudo));
3655 }
3656
3657 while((pseudo_ent = pseudo_readdir(pseudo)) != NULL) {
3658 dir_ent = scan2_lookup(dir, pseudo_ent->name);
3659 if(pseudo_ent->dev->type == 'm') {
3660 struct stat *buf;
3661 if(dir_ent == NULL) {
3662 ERROR_START("Pseudo modify file \"%s\" does "
3663 "not exist in source filesystem.",
3664 pseudo_ent->pathname);
3665 ERROR_EXIT(" Ignoring.\n");
3666 continue;
3667 }
3668 if(dir_ent->inode->root_entry) {
3669 ERROR_START("Pseudo modify file \"%s\" is a "
3670 "pre-existing file in the filesystem "
3671 "being appended to. It cannot be "\
3672 "modified.", pseudo_ent->pathname);
3673 ERROR_EXIT(" Ignoring.\n");
3674 continue;
3675 }
3676 buf = &dir_ent->inode->buf;
3677 buf->st_mode = (buf->st_mode & S_IFMT) |
3678 pseudo_ent->dev->mode;
3679 buf->st_uid = pseudo_ent->dev->uid;
3680 buf->st_gid = pseudo_ent->dev->gid;
3681 continue;
3682 }
3683
3684 if(dir_ent) {
3685 if(dir_ent->inode->root_entry) {
3686 ERROR_START("Pseudo file \"%s\" is a "
3687 "pre-existing file in the filesystem "
3688 "being appended to.",
3689 pseudo_ent->pathname);
3690 ERROR_EXIT(" Ignoring.\n");
3691 } else {
3692 ERROR_START("Pseudo file \"%s\" exists in "
3693 "source filesystem \"%s\".",
3694 pseudo_ent->pathname,
3695 pathname(dir_ent));
3696 ERROR_EXIT("\nIgnoring, exclude it (-e/-ef) to "
3697 "override.\n");
3698 }
3699 continue;
3700 }
3701
3702 memset(&buf, 0, sizeof(buf));
3703 buf.st_mode = pseudo_ent->dev->mode;
3704 buf.st_uid = pseudo_ent->dev->uid;
3705 buf.st_gid = pseudo_ent->dev->gid;
3706 buf.st_rdev = makedev(pseudo_ent->dev->major,
3707 pseudo_ent->dev->minor);
3708 buf.st_mtime = time(NULL);
3709 buf.st_ino = pseudo_ino ++;
3710
3711 if(pseudo_ent->dev->type == 'd') {
3712 struct dir_ent *dir_ent =
3713 create_dir_entry(pseudo_ent->name, NULL,
3714 pseudo_ent->pathname, dir);
3715 char *subpath = subpathname(dir_ent);
3716 struct dir_info *sub_dir = scan1_opendir("", subpath,
3717 dir->depth + 1);
3718 if(sub_dir == NULL) {
3719 ERROR_START("Could not create pseudo directory "
3720 "\"%s\"", pseudo_ent->pathname);
3721 ERROR_EXIT(", skipping...\n");
3722 pseudo_ino --;
3723 continue;
3724 }
3725 dir_scan2(sub_dir, pseudo_ent->pseudo);
3726 dir->directory_count ++;
3727 add_dir_entry(dir_ent, sub_dir,
3728 lookup_inode2(&buf, PSEUDO_FILE_OTHER, 0));
3729 } else if(pseudo_ent->dev->type == 'f') {
3730 add_dir_entry2(pseudo_ent->name, NULL,
3731 pseudo_ent->pathname, NULL,
3732 lookup_inode2(&buf, PSEUDO_FILE_PROCESS,
3733 pseudo_ent->dev->pseudo_id), dir);
3734 } else if(pseudo_ent->dev->type == 's') {
3735 add_dir_entry2(pseudo_ent->name, NULL,
3736 pseudo_ent->pathname, NULL,
3737 lookup_inode3(&buf, PSEUDO_FILE_OTHER, 0,
3738 pseudo_ent->dev->symlink,
3739 strlen(pseudo_ent->dev->symlink) + 1), dir);
3740 } else {
3741 add_dir_entry2(pseudo_ent->name, NULL,
3742 pseudo_ent->pathname, NULL,
3743 lookup_inode2(&buf, PSEUDO_FILE_OTHER, 0), dir);
3744 }
3745 }
3746 }
3747
3748
3749 /*
3750 * dir_scan3 routines...
3751 * This processes the move action
3752 */
3753 void dir_scan3(struct dir_info *dir)
3754 {
3755 struct dir_ent *dir_ent = NULL;
3756
3757 while((dir_ent = scan2_readdir(dir, dir_ent)) != NULL) {
3758
3759 eval_move_actions(root_dir, dir_ent);
3760
3761 if((dir_ent->inode->buf.st_mode & S_IFMT) == S_IFDIR)
3762 dir_scan3(dir_ent->dir);
3763 }
3764 }
3765
3766
3767 /*
3768 * dir_scan4 routines...
3769 * This processes the prune action. This action is designed to do fine
3770 * grained tuning of the in-core directory structure after the exclude,
3771 * move and pseudo actions have been performed. This allows complex
3772 * tests to be performed which are impossible at exclude time (i.e.
3773 * tests which rely on the in-core directory structure)
3774 */
3775 void free_dir(struct dir_info *dir)
3776 {
3777 struct dir_ent *dir_ent = dir->list;
3778
3779 while(dir_ent) {
3780 struct dir_ent *tmp = dir_ent;
3781
3782 if((dir_ent->inode->buf.st_mode & S_IFMT) == S_IFDIR)
3783 free_dir(dir_ent->dir);
3784
3785 dir_ent = dir_ent->next;
3786 free_dir_entry(tmp);
3787 }
3788
3789 free(dir->pathname);
3790 free(dir->subpath);
3791 free(dir);
3792 }
3793
3794
3795 void dir_scan4(struct dir_info *dir)
3796 {
3797 struct dir_ent *dir_ent = dir->list, *prev = NULL;
3798
3799 while(dir_ent) {
3800 if(dir_ent->inode->root_entry) {
3801 prev = dir_ent;
3802 dir_ent = dir_ent->next;
3803 continue;
3804 }
3805
3806 if((dir_ent->inode->buf.st_mode & S_IFMT) == S_IFDIR)
3807 dir_scan4(dir_ent->dir);
3808
3809 if(eval_prune_actions(root_dir, dir_ent)) {
3810 struct dir_ent *tmp = dir_ent;
3811
3812 if((dir_ent->inode->buf.st_mode & S_IFMT) == S_IFDIR) {
3813 free_dir(dir_ent->dir);
3814 dir->directory_count --;
3815 }
3816
3817 dir->count --;
3818
3819 /* remove dir_ent from list */
3820 dir_ent = dir_ent->next;
3821 if(prev)
3822 prev->next = dir_ent;
3823 else
3824 dir->list = dir_ent;
3825
3826 /* free it */
3827 free_dir_entry(tmp);
3828
3829 add_excluded(dir);
3830 continue;
3831 }
3832
3833 prev = dir_ent;
3834 dir_ent = dir_ent->next;
3835 }
3836 }
3837
3838
3839 /*
3840 * dir_scan5 routines...
3841 * This processes the empty action. This action has to be processed after
3842 * all other actions because the previous exclude and move actions and the
3843 * pseudo actions affect whether a directory is empty
3844 */
3845 void dir_scan5(struct dir_info *dir)
3846 {
3847 struct dir_ent *dir_ent = dir->list, *prev = NULL;
3848
3849 while(dir_ent) {
3850 if(dir_ent->inode->root_entry) {
3851 prev = dir_ent;
3852 dir_ent = dir_ent->next;
3853 continue;
3854 }
3855
3856 if((dir_ent->inode->buf.st_mode & S_IFMT) == S_IFDIR) {
3857 dir_scan5(dir_ent->dir);
3858
3859 if(eval_empty_actions(root_dir, dir_ent)) {
3860 struct dir_ent *tmp = dir_ent;
3861
3862 /*
3863 * delete sub-directory, this is by definition
3864 * empty
3865 */
3866 free(dir_ent->dir->pathname);
3867 free(dir_ent->dir->subpath);
3868 free(dir_ent->dir);
3869
3870 /* remove dir_ent from list */
3871 dir_ent = dir_ent->next;
3872 if(prev)
3873 prev->next = dir_ent;
3874 else
3875 dir->list = dir_ent;
3876
3877 /* free it */
3878 free_dir_entry(tmp);
3879
3880 /* update counts */
3881 dir->directory_count --;
3882 dir->count --;
3883 add_excluded(dir);
3884 continue;
3885 }
3886 }
3887
3888 prev = dir_ent;
3889 dir_ent = dir_ent->next;
3890 }
3891 }
3892
3893
3894 /*
3895 * dir_scan6 routines...
3896 * This sorts every directory and computes the inode numbers
3897 */
3898
3899 /*
3900 * Bottom up linked list merge sort.
3901 *
3902 * Qsort and other O(n log n) algorithms work well with arrays but not
3903 * linked lists. Merge sort another O(n log n) sort algorithm on the other hand
3904 * is not ideal for arrays (as it needs an additonal n storage locations
3905 * as sorting is not done in place), but it is ideal for linked lists because
3906 * it doesn't require any extra storage,
3907 */
3908 void sort_directory(struct dir_info *dir)
3909 {
3910 struct dir_ent *cur, *l1, *l2, *next;
3911 int len1, len2, stride = 1;
3912
3913 if(dir->list == NULL || dir->count < 2)
3914 return;
3915
3916 /*
3917 * We can consider our linked-list to be made up of stride length
3918 * sublists. Eacn iteration around this loop merges adjacent
3919 * stride length sublists into larger 2*stride sublists. We stop
3920 * when stride becomes equal to the entire list.
3921 *
3922 * Initially stride = 1 (by definition a sublist of 1 is sorted), and
3923 * these 1 element sublists are merged into 2 element sublists, which
3924 * are then merged into 4 element sublists and so on.
3925 */
3926 do {
3927 l2 = dir->list; /* head of current linked list */
3928 cur = NULL; /* empty output list */
3929
3930 /*
3931 * Iterate through the linked list, merging adjacent sublists.
3932 * On each interation l2 points to the next sublist pair to be
3933 * merged (if there's only one sublist left this is simply added
3934 * to the output list)
3935 */
3936 while(l2) {
3937 l1 = l2;
3938 for(len1 = 0; l2 && len1 < stride; len1 ++, l2 = l2->next);
3939 len2 = stride;
3940
3941 /*
3942 * l1 points to first sublist.
3943 * l2 points to second sublist.
3944 * Merge them onto the output list
3945 */
3946 while(len1 && l2 && len2) {
3947 if(strcmp(l1->name, l2->name) <= 0) {
3948 next = l1;
3949 l1 = l1->next;
3950 len1 --;
3951 } else {
3952 next = l2;
3953 l2 = l2->next;
3954 len2 --;
3955 }
3956
3957 if(cur) {
3958 cur->next = next;
3959 cur = next;
3960 } else
3961 dir->list = cur = next;
3962 }
3963 /*
3964 * One sublist is now empty, copy the other one onto the
3965 * output list
3966 */
3967 for(; len1; len1 --, l1 = l1->next) {
3968 if(cur) {
3969 cur->next = l1;
3970 cur = l1;
3971 } else
3972 dir->list = cur = l1;
3973 }
3974 for(; l2 && len2; len2 --, l2 = l2->next) {
3975 if(cur) {
3976 cur->next = l2;
3977 cur = l2;
3978 } else
3979 dir->list = cur = l2;
3980 }
3981 }
3982 cur->next = NULL;
3983 stride = stride << 1;
3984 } while(stride < dir->count);
3985 }
3986
3987
3988 void dir_scan6(struct dir_info *dir)
3989 {
3990 struct dir_ent *dir_ent;
3991 unsigned int byte_count = 0;
3992
3993 sort_directory(dir);
3994
3995 for(dir_ent = dir->list; dir_ent; dir_ent = dir_ent->next) {
3996 byte_count += strlen(dir_ent->name) +
3997 sizeof(struct squashfs_dir_entry);
3998
3999 if(dir_ent->inode->root_entry)
4000 continue;
4001
4002 alloc_inode_no(dir_ent->inode, 0);
4003
4004 if((dir_ent->inode->buf.st_mode & S_IFMT) == S_IFDIR)
4005 dir_scan6(dir_ent->dir);
4006 }
4007
4008 if((dir->count < 257 && byte_count < SQUASHFS_METADATA_SIZE))
4009 dir->dir_is_ldir = FALSE;
4010 }
4011
4012
4013 /*
4014 * dir_scan6 routines...
4015 * This generates the filesystem metadata and writes it out to the destination
4016 */
4017 void scan7_init_dir(struct directory *dir)
4018 {
4019 dir->buff = malloc(SQUASHFS_METADATA_SIZE);
4020 if(dir->buff == NULL)
4021 MEM_ERROR();
4022
4023 dir->size = SQUASHFS_METADATA_SIZE;
4024 dir->p = dir->index_count_p = dir->buff;
4025 dir->entry_count = 256;
4026 dir->entry_count_p = NULL;
4027 dir->index = NULL;
4028 dir->i_count = dir->i_size = 0;
4029 }
4030
4031
4032 struct dir_ent *scan7_readdir(struct directory *dir, struct dir_info *dir_info,
4033 struct dir_ent *dir_ent)
4034 {
4035 if (dir_ent == NULL)
4036 dir_ent = dir_info->list;
4037 else
4038 dir_ent = dir_ent->next;
4039
4040 for(; dir_ent && dir_ent->inode->root_entry; dir_ent = dir_ent->next)
4041 add_dir(dir_ent->inode->inode, dir_ent->inode->inode_number,
4042 dir_ent->name, dir_ent->inode->type, dir);
4043
4044 return dir_ent;
4045 }
4046
4047
4048 void scan7_freedir(struct directory *dir)
4049 {
4050 if(dir->index)
4051 free(dir->index);
4052 free(dir->buff);
4053 }
4054
4055
4056 void dir_scan7(squashfs_inode *inode, struct dir_info *dir_info)
4057 {
4058 int squashfs_type;
4059 int duplicate_file;
4060 struct directory dir;
4061 struct dir_ent *dir_ent = NULL;
4062
4063 scan7_init_dir(&dir);
4064
4065 while((dir_ent = scan7_readdir(&dir, dir_info, dir_ent)) != NULL) {
4066 struct stat *buf = &dir_ent->inode->buf;
4067
4068 update_info(dir_ent);
4069
4070 if(dir_ent->inode->inode == SQUASHFS_INVALID_BLK) {
4071 switch(buf->st_mode & S_IFMT) {
4072 case S_IFREG:
4073 squashfs_type = SQUASHFS_FILE_TYPE;
4074 write_file(inode, dir_ent,
4075 &duplicate_file);
4076 INFO("file %s, uncompressed size %lld "
4077 "bytes %s\n",
4078 subpathname(dir_ent),
4079 (long long) buf->st_size,
4080 duplicate_file ? "DUPLICATE" :
4081 "");
4082 break;
4083
4084 case S_IFDIR:
4085 squashfs_type = SQUASHFS_DIR_TYPE;
4086 dir_scan7(inode, dir_ent->dir);
4087 break;
4088
4089 case S_IFLNK:
4090 squashfs_type = SQUASHFS_SYMLINK_TYPE;
4091 create_inode(inode, NULL, dir_ent,
4092 squashfs_type, 0, 0, 0, NULL,
4093 NULL, NULL, 0);
4094 INFO("symbolic link %s inode 0x%llx\n",
4095 subpathname(dir_ent), *inode);
4096 sym_count ++;
4097 break;
4098
4099 case S_IFCHR:
4100 squashfs_type = SQUASHFS_CHRDEV_TYPE;
4101 create_inode(inode, NULL, dir_ent,
4102 squashfs_type, 0, 0, 0, NULL,
4103 NULL, NULL, 0);
4104 INFO("character device %s inode 0x%llx"
4105 "\n", subpathname(dir_ent),
4106 *inode);
4107 dev_count ++;
4108 break;
4109
4110 case S_IFBLK:
4111 squashfs_type = SQUASHFS_BLKDEV_TYPE;
4112 create_inode(inode, NULL, dir_ent,
4113 squashfs_type, 0, 0, 0, NULL,
4114 NULL, NULL, 0);
4115 INFO("block device %s inode 0x%llx\n",
4116 subpathname(dir_ent), *inode);
4117 dev_count ++;
4118 break;
4119
4120 case S_IFIFO:
4121 squashfs_type = SQUASHFS_FIFO_TYPE;
4122 create_inode(inode, NULL, dir_ent,
4123 squashfs_type, 0, 0, 0, NULL,
4124 NULL, NULL, 0);
4125 INFO("fifo %s inode 0x%llx\n",
4126 subpathname(dir_ent), *inode);
4127 fifo_count ++;
4128 break;
4129
4130 case S_IFSOCK:
4131 squashfs_type = SQUASHFS_SOCKET_TYPE;
4132 create_inode(inode, NULL, dir_ent,
4133 squashfs_type, 0, 0, 0, NULL,
4134 NULL, NULL, 0);
4135 INFO("unix domain socket %s inode "
4136 "0x%llx\n",
4137 subpathname(dir_ent), *inode);
4138 sock_count ++;
4139 break;
4140
4141 default:
4142 BAD_ERROR("%s unrecognised file type, "
4143 "mode is %x\n",
4144 subpathname(dir_ent),
4145 buf->st_mode);
4146 }
4147 dir_ent->inode->inode = *inode;
4148 dir_ent->inode->type = squashfs_type;
4149 } else {
4150 *inode = dir_ent->inode->inode;
4151 squashfs_type = dir_ent->inode->type;
4152 switch(squashfs_type) {
4153 case SQUASHFS_FILE_TYPE:
4154 if(!sorted)
4155 INFO("file %s, uncompressed "
4156 "size %lld bytes LINK"
4157 "\n",
4158 subpathname(dir_ent),
4159 (long long)
4160 buf->st_size);
4161 break;
4162 case SQUASHFS_SYMLINK_TYPE:
4163 INFO("symbolic link %s inode 0x%llx "
4164 "LINK\n", subpathname(dir_ent),
4165 *inode);
4166 break;
4167 case SQUASHFS_CHRDEV_TYPE:
4168 INFO("character device %s inode 0x%llx "
4169 "LINK\n", subpathname(dir_ent),
4170 *inode);
4171 break;
4172 case SQUASHFS_BLKDEV_TYPE:
4173 INFO("block device %s inode 0x%llx "
4174 "LINK\n", subpathname(dir_ent),
4175 *inode);
4176 break;
4177 case SQUASHFS_FIFO_TYPE:
4178 INFO("fifo %s inode 0x%llx LINK\n",
4179 subpathname(dir_ent), *inode);
4180 break;
4181 case SQUASHFS_SOCKET_TYPE:
4182 INFO("unix domain socket %s inode "
4183 "0x%llx LINK\n",
4184 subpathname(dir_ent), *inode);
4185 break;
4186 }
4187 }
4188
4189 add_dir(*inode, get_inode_no(dir_ent->inode), dir_ent->name,
4190 squashfs_type, &dir);
4191 }
4192
4193 write_dir(inode, dir_info, &dir);
4194 INFO("directory %s inode 0x%llx\n", subpathname(dir_info->dir_ent),
4195 *inode);
4196
4197 scan7_freedir(&dir);
4198 }
4199
4200
4201 unsigned int slog(unsigned int block)
4202 {
4203 int i;
4204
4205 for(i = 12; i <= 20; i++)
4206 if(block == (1 << i))
4207 return i;
4208 return 0;
4209 }
4210
4211
4212 int old_excluded(char *filename, struct stat *buf)
4213 {
4214 int i;
4215
4216 for(i = 0; i < exclude; i++)
4217 if((exclude_paths[i].st_dev == buf->st_dev) &&
4218 (exclude_paths[i].st_ino == buf->st_ino))
4219 return TRUE;
4220 return FALSE;
4221 }
4222
4223
4224 #define ADD_ENTRY(buf) \
4225 if(exclude % EXCLUDE_SIZE == 0) { \
4226 exclude_paths = realloc(exclude_paths, (exclude + EXCLUDE_SIZE) \
4227 * sizeof(struct exclude_info)); \
4228 if(exclude_paths == NULL) \
4229 MEM_ERROR(); \
4230 } \
4231 exclude_paths[exclude].st_dev = buf.st_dev; \
4232 exclude_paths[exclude++].st_ino = buf.st_ino;
4233 int old_add_exclude(char *path)
4234 {
4235 int i;
4236 char *filename;
4237 struct stat buf;
4238
4239 if(path[0] == '/' || strncmp(path, "./", 2) == 0 ||
4240 strncmp(path, "../", 3) == 0) {
4241 if(lstat(path, &buf) == -1) {
4242 ERROR_START("Cannot stat exclude dir/file %s because "
4243 "%s", path, strerror(errno));
4244 ERROR_EXIT(", ignoring\n");
4245 return TRUE;
4246 }
4247 ADD_ENTRY(buf);
4248 return TRUE;
4249 }
4250
4251 for(i = 0; i < source; i++) {
4252 int res = asprintf(&filename, "%s/%s", source_path[i], path);
4253 if(res == -1)
4254 BAD_ERROR("asprintf failed in old_add_exclude\n");
4255 if(lstat(filename, &buf) == -1) {
4256 if(!(errno == ENOENT || errno == ENOTDIR)) {
4257 ERROR_START("Cannot stat exclude dir/file %s "
4258 "because %s", filename, strerror(errno));
4259 ERROR_EXIT(", ignoring\n");
4260 }
4261 free(filename);
4262 continue;
4263 }
4264 free(filename);
4265 ADD_ENTRY(buf);
4266 }
4267 return TRUE;
4268 }
4269
4270
4271 void add_old_root_entry(char *name, squashfs_inode inode, int inode_number,
4272 int type)
4273 {
4274 old_root_entry = realloc(old_root_entry,
4275 sizeof(struct old_root_entry_info) * (old_root_entries + 1));
4276 if(old_root_entry == NULL)
4277 MEM_ERROR();
4278
4279 old_root_entry[old_root_entries].name = strdup(name);
4280 old_root_entry[old_root_entries].inode.inode = inode;
4281 old_root_entry[old_root_entries].inode.inode_number = inode_number;
4282 old_root_entry[old_root_entries].inode.type = type;
4283 old_root_entry[old_root_entries++].inode.root_entry = TRUE;
4284 }
4285
4286
4287 void initialise_threads(int readq, int fragq, int bwriteq, int fwriteq,
4288 int freelst, char *destination_file)
4289 {
4290 int i;
4291 sigset_t sigmask, old_mask;
4292 int total_mem = readq;
4293 int reader_size;
4294 int fragment_size;
4295 int fwriter_size;
4296 /*
4297 * bwriter_size is global because it is needed in
4298 * write_file_blocks_dup()
4299 */
4300
4301 /*
4302 * Never allow the total size of the queues to be larger than
4303 * physical memory
4304 *
4305 * When adding together the possibly user supplied values, make
4306 * sure they've not been deliberately contrived to overflow an int
4307 */
4308 if(add_overflow(total_mem, fragq))
4309 BAD_ERROR("Queue sizes rediculously too large\n");
4310 total_mem += fragq;
4311 if(add_overflow(total_mem, bwriteq))
4312 BAD_ERROR("Queue sizes rediculously too large\n");
4313 total_mem += bwriteq;
4314 if(add_overflow(total_mem, fwriteq))
4315 BAD_ERROR("Queue sizes rediculously too large\n");
4316 total_mem += fwriteq;
4317
4318 check_usable_phys_mem(total_mem);
4319
4320 /*
4321 * convert from queue size in Mbytes to queue size in
4322 * blocks.
4323 *
4324 * This isn't going to overflow an int unless there exists
4325 * systems with more than 8 Petabytes of RAM!
4326 */
4327 reader_size = readq << (20 - block_log);
4328 fragment_size = fragq << (20 - block_log);
4329 bwriter_size = bwriteq << (20 - block_log);
4330 fwriter_size = fwriteq << (20 - block_log);
4331
4332 /*
4333 * setup signal handlers for the main thread, these cleanup
4334 * deleting the destination file, if appending the
4335 * handlers for SIGTERM and SIGINT will be replaced with handlers
4336 * allowing the user to press ^C twice to restore the existing
4337 * filesystem.
4338 *
4339 * SIGUSR1 is an internal signal, which is used by the sub-threads
4340 * to tell the main thread to terminate, deleting the destination file,
4341 * or if necessary restoring the filesystem on appending
4342 */
4343 signal(SIGTERM, sighandler);
4344 signal(SIGINT, sighandler);
4345 signal(SIGUSR1, sighandler);
4346
4347 /* block SIGQUIT and SIGHUP, these are handled by the info thread */
4348 sigemptyset(&sigmask);
4349 sigaddset(&sigmask, SIGQUIT);
4350 sigaddset(&sigmask, SIGHUP);
4351 if(pthread_sigmask(SIG_BLOCK, &sigmask, NULL) != 0)
4352 BAD_ERROR("Failed to set signal mask in intialise_threads\n");
4353
4354 /*
4355 * temporarily block these signals, so the created sub-threads
4356 * will ignore them, ensuring the main thread handles them
4357 */
4358 sigemptyset(&sigmask);
4359 sigaddset(&sigmask, SIGINT);
4360 sigaddset(&sigmask, SIGTERM);
4361 sigaddset(&sigmask, SIGUSR1);
4362 if(pthread_sigmask(SIG_BLOCK, &sigmask, &old_mask) != 0)
4363 BAD_ERROR("Failed to set signal mask in intialise_threads\n");
4364
4365 if(processors == -1) {
4366 #ifndef linux
4367 int mib[2];
4368 size_t len = sizeof(processors);
4369
4370 mib[0] = CTL_HW;
4371 #ifdef HW_AVAILCPU
4372 mib[1] = HW_AVAILCPU;
4373 #else
4374 mib[1] = HW_NCPU;
4375 #endif
4376
4377 if(sysctl(mib, 2, &processors, &len, NULL, 0) == -1) {
4378 ERROR_START("Failed to get number of available "
4379 "processors.");
4380 ERROR_EXIT(" Defaulting to 1\n");
4381 processors = 1;
4382 }
4383 #else
4384 processors = sysconf(_SC_NPROCESSORS_ONLN);
4385 #endif
4386 }
4387
4388 if(multiply_overflow(processors, 3) ||
4389 multiply_overflow(processors * 3, sizeof(pthread_t)))
4390 BAD_ERROR("Processors too large\n");
4391
4392 deflator_thread = malloc(processors * 3 * sizeof(pthread_t));
4393 if(deflator_thread == NULL)
4394 MEM_ERROR();
4395
4396 frag_deflator_thread = &deflator_thread[processors];
4397 frag_thread = &frag_deflator_thread[processors];
4398
4399 to_reader = queue_init(1);
4400 to_deflate = queue_init(reader_size);
4401 to_process_frag = queue_init(reader_size);
4402 to_writer = queue_init(bwriter_size + fwriter_size);
4403 from_writer = queue_init(1);
4404 to_frag = queue_init(fragment_size);
4405 to_main = seq_queue_init();
4406 if(reproducible)
4407 to_order = seq_queue_init();
4408 else
4409 locked_fragment = queue_init(fragment_size);
4410 reader_buffer = cache_init(block_size, reader_size, 0, 0);
4411 bwriter_buffer = cache_init(block_size, bwriter_size, 1, freelst);
4412 fwriter_buffer = cache_init(block_size, fwriter_size, 1, freelst);
4413 fragment_buffer = cache_init(block_size, fragment_size, 1, 0);
4414 reserve_cache = cache_init(block_size, processors + 1, 1, 0);
4415 pthread_create(&reader_thread, NULL, reader, NULL);
4416 pthread_create(&writer_thread, NULL, writer, NULL);
4417 init_progress_bar();
4418 init_info();
4419
4420 for(i = 0; i < processors; i++) {
4421 if(pthread_create(&deflator_thread[i], NULL, deflator, NULL))
4422 BAD_ERROR("Failed to create thread\n");
4423 if(pthread_create(&frag_deflator_thread[i], NULL, reproducible ?
4424 frag_order_deflator : frag_deflator, NULL) != 0)
4425 BAD_ERROR("Failed to create thread\n");
4426 if(pthread_create(&frag_thread[i], NULL, frag_thrd,
4427 (void *) destination_file) != 0)
4428 BAD_ERROR("Failed to create thread\n");
4429 }
4430
4431 main_thread = pthread_self();
4432
4433 if(reproducible)
4434 pthread_create(&order_thread, NULL, frag_orderer, NULL);
4435
4436 if(!quiet)
4437 printf("Parallel mksquashfs: Using %d processor%s\n", processors,
4438 processors == 1 ? "" : "s");
4439
4440 /* Restore the signal mask for the main thread */
4441 if(pthread_sigmask(SIG_SETMASK, &old_mask, NULL) != 0)
4442 BAD_ERROR("Failed to set signal mask in intialise_threads\n");
4443 }
4444
4445
4446 long long write_inode_lookup_table()
4447 {
4448 int i, inode_number, lookup_bytes = SQUASHFS_LOOKUP_BYTES(inode_count);
4449 void *it;
4450
4451 if(inode_count == sinode_count)
4452 goto skip_inode_hash_table;
4453
4454 it = realloc(inode_lookup_table, lookup_bytes);
4455 if(it == NULL)
4456 MEM_ERROR();
4457 inode_lookup_table = it;
4458
4459 for(i = 0; i < INODE_HASH_SIZE; i ++) {
4460 struct inode_info *inode;
4461
4462 for(inode = inode_info[i]; inode; inode = inode->next) {
4463
4464 inode_number = get_inode_no(inode);
4465
4466 /* The empty action will produce orphaned inode
4467 * entries in the inode_info[] table. These
4468 * entries because they are orphaned will not be
4469 * allocated an inode number in dir_scan5(), so
4470 * skip any entries with the default dummy inode
4471 * number of 0 */
4472 if(inode_number == 0)
4473 continue;
4474
4475 SQUASHFS_SWAP_LONG_LONGS(&inode->inode,
4476 &inode_lookup_table[inode_number - 1], 1);
4477
4478 }
4479 }
4480
4481 skip_inode_hash_table:
4482 return generic_write_table(lookup_bytes, inode_lookup_table, 0, NULL,
4483 noI);
4484 }
4485
4486
4487 char *get_component(char *target, char **targname)
4488 {
4489 char *start;
4490
4491 while(*target == '/')
4492 target ++;
4493
4494 start = target;
4495 while(*target != '/' && *target != '\0')
4496 target ++;
4497
4498 *targname = strndup(start, target - start);
4499
4500 while(*target == '/')
4501 target ++;
4502
4503 return target;
4504 }
4505
4506
4507 void free_path(struct pathname *paths)
4508 {
4509 int i;
4510
4511 for(i = 0; i < paths->names; i++) {
4512 if(paths->name[i].paths)
4513 free_path(paths->name[i].paths);
4514 free(paths->name[i].name);
4515 if(paths->name[i].preg) {
4516 regfree(paths->name[i].preg);
4517 free(paths->name[i].preg);
4518 }
4519 }
4520
4521 free(paths);
4522 }
4523
4524
4525 struct pathname *add_path(struct pathname *paths, char *target, char *alltarget)
4526 {
4527 char *targname;
4528 int i, error;
4529
4530 target = get_component(target, &targname);
4531
4532 if(paths == NULL) {
4533 paths = malloc(sizeof(struct pathname));
4534 if(paths == NULL)
4535 MEM_ERROR();
4536
4537 paths->names = 0;
4538 paths->name = NULL;
4539 }
4540
4541 for(i = 0; i < paths->names; i++)
4542 if(strcmp(paths->name[i].name, targname) == 0)
4543 break;
4544
4545 if(i == paths->names) {
4546 /* allocate new name entry */
4547 paths->names ++;
4548 paths->name = realloc(paths->name, (i + 1) *
4549 sizeof(struct path_entry));
4550 if(paths->name == NULL)
4551 MEM_ERROR();
4552 paths->name[i].name = targname;
4553 paths->name[i].paths = NULL;
4554 if(use_regex) {
4555 paths->name[i].preg = malloc(sizeof(regex_t));
4556 if(paths->name[i].preg == NULL)
4557 MEM_ERROR();
4558 error = regcomp(paths->name[i].preg, targname,
4559 REG_EXTENDED|REG_NOSUB);
4560 if(error) {
4561 char str[1024]; /* overflow safe */
4562
4563 regerror(error, paths->name[i].preg, str, 1024);
4564 BAD_ERROR("invalid regex %s in export %s, "
4565 "because %s\n", targname, alltarget,
4566 str);
4567 }
4568 } else
4569 paths->name[i].preg = NULL;
4570
4571 if(target[0] == '\0')
4572 /* at leaf pathname component */
4573 paths->name[i].paths = NULL;
4574 else
4575 /* recurse adding child components */
4576 paths->name[i].paths = add_path(NULL, target,
4577 alltarget);
4578 } else {
4579 /* existing matching entry */
4580 free(targname);
4581
4582 if(paths->name[i].paths == NULL) {
4583 /* No sub-directory which means this is the leaf
4584 * component of a pre-existing exclude which subsumes
4585 * the exclude currently being added, in which case stop
4586 * adding components */
4587 } else if(target[0] == '\0') {
4588 /* at leaf pathname component and child components exist
4589 * from more specific excludes, delete as they're
4590 * subsumed by this exclude */
4591 free_path(paths->name[i].paths);
4592 paths->name[i].paths = NULL;
4593 } else
4594 /* recurse adding child components */
4595 add_path(paths->name[i].paths, target, alltarget);
4596 }
4597
4598 return paths;
4599 }
4600
4601
4602 void add_exclude(char *target)
4603 {
4604
4605 if(target[0] == '/' || strncmp(target, "./", 2) == 0 ||
4606 strncmp(target, "../", 3) == 0)
4607 BAD_ERROR("/, ./ and ../ prefixed excludes not supported with "
4608 "-wildcards or -regex options\n");
4609 else if(strncmp(target, "... ", 4) == 0)
4610 stickypath = add_path(stickypath, target + 4, target + 4);
4611 else
4612 path = add_path(path, target, target);
4613 }
4614
4615
4616 void display_path(int depth, struct pathname *paths)
4617 {
4618 int i, n;
4619
4620 if(paths == NULL)
4621 return;
4622
4623 for(i = 0; i < paths->names; i++) {
4624 for(n = 0; n < depth; n++)
4625 printf("\t");
4626 printf("%d: %s\n", depth, paths->name[i].name);
4627 display_path(depth + 1, paths->name[i].paths);
4628 }
4629 }
4630
4631
4632 void display_path2(struct pathname *paths, char *string)
4633 {
4634 int i;
4635 char *path;
4636
4637 if(paths == NULL) {
4638 printf("%s\n", string);
4639 return;
4640 }
4641
4642 for(i = 0; i < paths->names; i++) {
4643 int res = asprintf(&path, "%s/%s", string, paths->name[i].name);
4644 if(res == -1)
4645 BAD_ERROR("asprintf failed in display_path2\n");
4646 display_path2(paths->name[i].paths, path);
4647 free(path);
4648 }
4649 }
4650
4651
4652 struct pathnames *add_subdir(struct pathnames *paths, struct pathname *path)
4653 {
4654 int count = paths == NULL ? 0 : paths->count;
4655
4656 if(count % PATHS_ALLOC_SIZE == 0) {
4657 paths = realloc(paths, sizeof(struct pathnames) +
4658 (count + PATHS_ALLOC_SIZE) * sizeof(struct pathname *));
4659 if(paths == NULL)
4660 MEM_ERROR();
4661 }
4662
4663 paths->path[count] = path;
4664 paths->count = count + 1;
4665 return paths;
4666 }
4667
4668
4669 int excluded_match(char *name, struct pathname *path, struct pathnames **new)
4670 {
4671 int i;
4672
4673 for(i = 0; i < path->names; i++) {
4674 int match = use_regex ?
4675 regexec(path->name[i].preg, name, (size_t) 0,
4676 NULL, 0) == 0 :
4677 fnmatch(path->name[i].name, name,
4678 FNM_PATHNAME|FNM_PERIOD|FNM_EXTMATCH) == 0;
4679
4680 if(match) {
4681 if(path->name[i].paths == NULL || new == NULL)
4682 /* match on a leaf component, any subdirectories
4683 * in the filesystem should be excluded */
4684 return TRUE;
4685 else
4686 /* match on a non-leaf component, add any
4687 * subdirectories to the new set of
4688 * subdirectories to scan for this name */
4689 *new = add_subdir(*new, path->name[i].paths);
4690 }
4691 }
4692
4693 return FALSE;
4694 }
4695
4696
4697 int excluded(char *name, struct pathnames *paths, struct pathnames **new)
4698 {
4699 int n;
4700
4701 if(stickypath && excluded_match(name, stickypath, NULL))
4702 return TRUE;
4703
4704 for(n = 0; paths && n < paths->count; n++) {
4705 int res = excluded_match(name, paths->path[n], new);
4706 if(res) {
4707 free(*new);
4708 *new = NULL;
4709 return TRUE;
4710 }
4711 }
4712
4713 /*
4714 * Either:
4715 * - no matching names found, return empty new search set, or
4716 * - one or more matches with sub-directories found (no leaf matches),
4717 * in which case return new search set.
4718 *
4719 * In either case return FALSE as we don't want to exclude this entry
4720 */
4721 return FALSE;
4722 }
4723
4724
4725 void process_exclude_file(char *argv)
4726 {
4727 FILE *fd;
4728 char buffer[MAX_LINE + 1]; /* overflow safe */
4729 char *filename;
4730
4731 fd = fopen(argv, "r");
4732 if(fd == NULL)
4733 BAD_ERROR("Failed to open exclude file \"%s\" because %s\n",
4734 argv, strerror(errno));
4735
4736 while(fgets(filename = buffer, MAX_LINE + 1, fd) != NULL) {
4737 int len = strlen(filename);
4738
4739 if(len == MAX_LINE && filename[len - 1] != '\n')
4740 /* line too large */
4741 BAD_ERROR("Line too long when reading "
4742 "exclude file \"%s\", larger than %d "
4743 "bytes\n", argv, MAX_LINE);
4744
4745 /*
4746 * Remove '\n' terminator if it exists (the last line
4747 * in the file may not be '\n' terminated)
4748 */
4749 if(len && filename[len - 1] == '\n')
4750 filename[len - 1] = '\0';
4751
4752 /* Skip any leading whitespace */
4753 while(isspace(*filename))
4754 filename ++;
4755
4756 /* if comment line, skip */
4757 if(*filename == '#')
4758 continue;
4759
4760 /*
4761 * check for initial backslash, to accommodate
4762 * filenames with leading space or leading # character
4763 */
4764 if(*filename == '\\')
4765 filename ++;
4766
4767 /* if line is now empty after skipping characters, skip it */
4768 if(*filename == '\0')
4769 continue;
4770
4771 if(old_exclude)
4772 old_add_exclude(filename);
4773 else
4774 add_exclude(filename);
4775 }
4776
4777 if(ferror(fd))
4778 BAD_ERROR("Reading exclude file \"%s\" failed because %s\n",
4779 argv, strerror(errno));
4780
4781 fclose(fd);
4782 }
4783
4784
4785 #define RECOVER_ID "Squashfs recovery file v1.0\n"
4786 #define RECOVER_ID_SIZE 28
4787
4788 void write_recovery_data(struct squashfs_super_block *sBlk)
4789 {
4790 int res, recoverfd, bytes = sBlk->bytes_used - sBlk->inode_table_start;
4791 pid_t pid = getpid();
4792 char *metadata;
4793 char header[] = RECOVER_ID;
4794
4795 if(recover == FALSE) {
4796 printf("No recovery data option specified.\n");
4797 printf("Skipping saving recovery file.\n\n");
4798 return;
4799 }
4800
4801 metadata = malloc(bytes);
4802 if(metadata == NULL)
4803 MEM_ERROR();
4804
4805 res = read_fs_bytes(fd, sBlk->inode_table_start, bytes, metadata);
4806 if(res == 0) {
4807 ERROR("Failed to read append filesystem metadata\n");
4808 BAD_ERROR("Filesystem corrupted?\n");
4809 }
4810
4811 res = asprintf(&recovery_file, "squashfs_recovery_%s_%d",
4812 getbase(destination_file), pid);
4813 if(res == -1)
4814 MEM_ERROR();
4815
4816 recoverfd = open(recovery_file, O_CREAT | O_TRUNC | O_RDWR, S_IRWXU);
4817 if(recoverfd == -1)
4818 BAD_ERROR("Failed to create recovery file, because %s. "
4819 "Aborting\n", strerror(errno));
4820
4821 if(write_bytes(recoverfd, header, RECOVER_ID_SIZE) == -1)
4822 BAD_ERROR("Failed to write recovery file, because %s\n",
4823 strerror(errno));
4824
4825 if(write_bytes(recoverfd, sBlk, sizeof(struct squashfs_super_block)) == -1)
4826 BAD_ERROR("Failed to write recovery file, because %s\n",
4827 strerror(errno));
4828
4829 if(write_bytes(recoverfd, metadata, bytes) == -1)
4830 BAD_ERROR("Failed to write recovery file, because %s\n",
4831 strerror(errno));
4832
4833 close(recoverfd);
4834 free(metadata);
4835
4836 printf("Recovery file \"%s\" written\n", recovery_file);
4837 printf("If Mksquashfs aborts abnormally (i.e. power failure), run\n");
4838 printf("mksquashfs dummy %s -recover %s\n", destination_file,
4839 recovery_file);
4840 printf("to restore filesystem\n\n");
4841 }
4842
4843
4844 void read_recovery_data(char *recovery_file, char *destination_file)
4845 {
4846 int fd, recoverfd, bytes;
4847 struct squashfs_super_block orig_sBlk, sBlk;
4848 char *metadata;
4849 int res;
4850 struct stat buf;
4851 char header[] = RECOVER_ID;
4852 char header2[RECOVER_ID_SIZE];
4853
4854 recoverfd = open(recovery_file, O_RDONLY);
4855 if(recoverfd == -1)
4856 BAD_ERROR("Failed to open recovery file because %s\n",
4857 strerror(errno));
4858
4859 if(stat(destination_file, &buf) == -1)
4860 BAD_ERROR("Failed to stat destination file, because %s\n",
4861 strerror(errno));
4862
4863 fd = open(destination_file, O_RDWR);
4864 if(fd == -1)
4865 BAD_ERROR("Failed to open destination file because %s\n",
4866 strerror(errno));
4867
4868 res = read_bytes(recoverfd, header2, RECOVER_ID_SIZE);
4869 if(res == -1)
4870 BAD_ERROR("Failed to read recovery file, because %s\n",
4871 strerror(errno));
4872 if(res < RECOVER_ID_SIZE)
4873 BAD_ERROR("Recovery file appears to be truncated\n");
4874 if(strncmp(header, header2, RECOVER_ID_SIZE) !=0 )
4875 BAD_ERROR("Not a recovery file\n");
4876
4877 res = read_bytes(recoverfd, &sBlk, sizeof(struct squashfs_super_block));
4878 if(res == -1)
4879 BAD_ERROR("Failed to read recovery file, because %s\n",
4880 strerror(errno));
4881 if(res < sizeof(struct squashfs_super_block))
4882 BAD_ERROR("Recovery file appears to be truncated\n");
4883
4884 res = read_fs_bytes(fd, 0, sizeof(struct squashfs_super_block), &orig_sBlk);
4885 if(res == 0) {
4886 ERROR("Failed to read superblock from output filesystem\n");
4887 BAD_ERROR("Output filesystem is empty!\n");
4888 }
4889
4890 if(memcmp(((char *) &sBlk) + 4, ((char *) &orig_sBlk) + 4,
4891 sizeof(struct squashfs_super_block) - 4) != 0)
4892 BAD_ERROR("Recovery file and destination file do not seem to "
4893 "match\n");
4894
4895 bytes = sBlk.bytes_used - sBlk.inode_table_start;
4896
4897 metadata = malloc(bytes);
4898 if(metadata == NULL)
4899 MEM_ERROR();
4900
4901 res = read_bytes(recoverfd, metadata, bytes);
4902 if(res == -1)
4903 BAD_ERROR("Failed to read recovery file, because %s\n",
4904 strerror(errno));
4905 if(res < bytes)
4906 BAD_ERROR("Recovery file appears to be truncated\n");
4907
4908 write_destination(fd, 0, sizeof(struct squashfs_super_block), &sBlk);
4909
4910 write_destination(fd, sBlk.inode_table_start, bytes, metadata);
4911
4912 close(recoverfd);
4913 close(fd);
4914
4915 printf("Successfully wrote recovery file \"%s\". Exiting\n",
4916 recovery_file);
4917
4918 exit(0);
4919 }
4920
4921
4922 void write_filesystem_tables(struct squashfs_super_block *sBlk, int nopad)
4923 {
4924 int i;
4925
4926 sBlk->fragments = fragments;
4927 sBlk->no_ids = id_count;
4928 sBlk->inode_table_start = write_inodes();
4929 sBlk->directory_table_start = write_directories();
4930 sBlk->fragment_table_start = write_fragment_table();
4931 sBlk->lookup_table_start = exportable ? write_inode_lookup_table() :
4932 SQUASHFS_INVALID_BLK;
4933 sBlk->id_table_start = write_id_table();
4934 sBlk->xattr_id_table_start = write_xattrs();
4935
4936 TRACE("sBlk->inode_table_start 0x%llx\n", sBlk->inode_table_start);
4937 TRACE("sBlk->directory_table_start 0x%llx\n",
4938 sBlk->directory_table_start);
4939 TRACE("sBlk->fragment_table_start 0x%llx\n", sBlk->fragment_table_start);
4940 if(exportable)
4941 TRACE("sBlk->lookup_table_start 0x%llx\n",
4942 sBlk->lookup_table_start);
4943
4944 sBlk->bytes_used = bytes;
4945
4946 sBlk->compression = comp->id;
4947
4948 SQUASHFS_INSWAP_SUPER_BLOCK(sBlk);
4949 write_destination(fd, SQUASHFS_START, sizeof(*sBlk), sBlk);
4950
4951 if(!nopad && (i = bytes & (4096 - 1))) {
4952 char temp[4096] = {0};
4953 write_destination(fd, bytes, 4096 - i, temp);
4954 }
4955
4956 close(fd);
4957
4958 if(recovery_file)
4959 unlink(recovery_file);
4960
4961 total_bytes += total_inode_bytes + total_directory_bytes +
4962 sizeof(struct squashfs_super_block) + total_xattr_bytes;
4963
4964 if(quiet)
4965 return;
4966
4967 printf("\n%sSquashfs %d.%d filesystem, %s compressed, data block size"
4968 " %d\n", exportable ? "Exportable " : "", SQUASHFS_MAJOR,
4969 SQUASHFS_MINOR, comp->name, block_size);
4970 printf("\t%s data, %s metadata, %s fragments,\n\t%s xattrs, %s ids\n",
4971 noD ? "uncompressed" : "compressed", noI ? "uncompressed" :
4972 "compressed", no_fragments ? "no" : noF ? "uncompressed" :
4973 "compressed", no_xattrs ? "no" : noX ? "uncompressed" :
4974 "compressed", noI || noId ? "uncompressed" : "compressed");
4975 printf("\tduplicates are %sremoved\n", duplicate_checking ? "" :
4976 "not ");
4977 printf("Filesystem size %.2f Kbytes (%.2f Mbytes)\n", bytes / 1024.0,
4978 bytes / (1024.0 * 1024.0));
4979 printf("\t%.2f%% of uncompressed filesystem size (%.2f Kbytes)\n",
4980 ((float) bytes / total_bytes) * 100.0, total_bytes / 1024.0);
4981 printf("Inode table size %d bytes (%.2f Kbytes)\n",
4982 inode_bytes, inode_bytes / 1024.0);
4983 printf("\t%.2f%% of uncompressed inode table size (%d bytes)\n",
4984 ((float) inode_bytes / total_inode_bytes) * 100.0,
4985 total_inode_bytes);
4986 printf("Directory table size %d bytes (%.2f Kbytes)\n",
4987 directory_bytes, directory_bytes / 1024.0);
4988 printf("\t%.2f%% of uncompressed directory table size (%d bytes)\n",
4989 ((float) directory_bytes / total_directory_bytes) * 100.0,
4990 total_directory_bytes);
4991 if(total_xattr_bytes) {
4992 printf("Xattr table size %d bytes (%.2f Kbytes)\n",
4993 xattr_bytes, xattr_bytes / 1024.0);
4994 printf("\t%.2f%% of uncompressed xattr table size (%d bytes)\n",
4995 ((float) xattr_bytes / total_xattr_bytes) * 100.0,
4996 total_xattr_bytes);
4997 }
4998 if(duplicate_checking)
4999 printf("Number of duplicate files found %d\n", file_count -
5000 dup_files);
5001 else
5002 printf("No duplicate files removed\n");
5003 printf("Number of inodes %d\n", inode_count);
5004 printf("Number of files %d\n", file_count);
5005 if(!no_fragments)
5006 printf("Number of fragments %d\n", fragments);
5007 printf("Number of symbolic links %d\n", sym_count);
5008 printf("Number of device nodes %d\n", dev_count);
5009 printf("Number of fifo nodes %d\n", fifo_count);
5010 printf("Number of socket nodes %d\n", sock_count);
5011 printf("Number of directories %d\n", dir_count);
5012 printf("Number of ids (unique uids + gids) %d\n", id_count);
5013 printf("Number of uids %d\n", uid_count);
5014
5015 for(i = 0; i < id_count; i++) {
5016 if(id_table[i]->flags & ISA_UID) {
5017 struct passwd *user = getpwuid(id_table[i]->id);
5018 printf("\t%s (%d)\n", user == NULL ? "unknown" :
5019 user->pw_name, id_table[i]->id);
5020 }
5021 }
5022
5023 printf("Number of gids %d\n", guid_count);
5024
5025 for(i = 0; i < id_count; i++) {
5026 if(id_table[i]->flags & ISA_GID) {
5027 struct group *group = getgrgid(id_table[i]->id);
5028 printf("\t%s (%d)\n", group == NULL ? "unknown" :
5029 group->gr_name, id_table[i]->id);
5030 }
5031 }
5032 }
5033
5034
5035 int _parse_numberll(char *start, long long *res, int size, int base)
5036 {
5037 char *end;
5038 long long number;
5039
5040 errno = 0; /* To distinguish success/failure after call */
5041
5042 number = strtoll(start, &end, base);
5043
5044 /*
5045 * check for strtoll underflow or overflow in conversion, and other
5046 * errors.
5047 */
5048 if((errno == ERANGE && (number == LLONG_MIN || number == LLONG_MAX)) ||
5049 (errno != 0 && number == 0))
5050 return 0;
5051
5052 /* reject negative numbers as invalid */
5053 if(number < 0)
5054 return 0;
5055
5056 if(size) {
5057 /*
5058 * Check for multiplier and trailing junk.
5059 * But first check that a number exists before the
5060 * multiplier
5061 */
5062 if(end == start)
5063 return 0;
5064
5065 switch(end[0]) {
5066 case 'g':
5067 case 'G':
5068 if(multiply_overflowll(number, 1073741824))
5069 return 0;
5070 number *= 1073741824;
5071
5072 if(end[1] != '\0')
5073 /* trailing junk after multiplier, but
5074 * allow it to be "bytes" */
5075 if(strcmp(end + 1, "bytes"))
5076 return 0;
5077
5078 break;
5079 case 'm':
5080 case 'M':
5081 if(multiply_overflowll(number, 1048576))
5082 return 0;
5083 number *= 1048576;
5084
5085 if(end[1] != '\0')
5086 /* trailing junk after multiplier, but
5087 * allow it to be "bytes" */
5088 if(strcmp(end + 1, "bytes"))
5089 return 0;
5090
5091 break;
5092 case 'k':
5093 case 'K':
5094 if(multiply_overflowll(number, 1024))
5095 return 0;
5096 number *= 1024;
5097
5098 if(end[1] != '\0')
5099 /* trailing junk after multiplier, but
5100 * allow it to be "bytes" */
5101 if(strcmp(end + 1, "bytes"))
5102 return 0;
5103
5104 break;
5105 case '\0':
5106 break;
5107 default:
5108 /* trailing junk after number */
5109 return 0;
5110 }
5111 } else if(end[0] != '\0')
5112 /* trailing junk after number */
5113 return 0;
5114
5115 *res = number;
5116 return 1;
5117 }
5118
5119
5120 int parse_numberll(char *start, long long *res, int size)
5121 {
5122 return _parse_numberll(start, res, size, 10);
5123 }
5124
5125
5126 int parse_number(char *start, int *res, int size)
5127 {
5128 long long number;
5129
5130 if(!_parse_numberll(start, &number, size, 10))
5131 return 0;
5132
5133 /* check if long result will overflow signed int */
5134 if(number > INT_MAX)
5135 return 0;
5136
5137 *res = (int) number;
5138 return 1;
5139 }
5140
5141
5142 int parse_number_unsigned(char *start, unsigned int *res, int size)
5143 {
5144 long long number;
5145
5146 if(!_parse_numberll(start, &number, size, 10))
5147 return 0;
5148
5149 /* check if long result will overflow unsigned int */
5150 if(number > UINT_MAX)
5151 return 0;
5152
5153 *res = (unsigned int) number;
5154 return 1;
5155 }
5156
5157
5158 int parse_num(char *arg, int *res)
5159 {
5160 return parse_number(arg, res, 0);
5161 }
5162
5163
5164 int parse_num_unsigned(char *arg, unsigned int *res)
5165 {
5166 return parse_number_unsigned(arg, res, 0);
5167 }
5168
5169
5170 int parse_mode(char *arg, mode_t *res)
5171 {
5172 long long number;
5173
5174 if(!_parse_numberll(arg, &number, 0, 8))
5175 return 0;
5176
5177 if(number > 07777)
5178 return 0;
5179
5180 *res = (mode_t) number;
5181 return 1;
5182 }
5183
5184
5185 int get_physical_memory()
5186 {
5187 /*
5188 * Long longs are used here because with PAE, a 32-bit
5189 * machine can have more than 4GB of physical memory
5190 *
5191 * sysconf(_SC_PHYS_PAGES) relies on /proc being mounted.
5192 * If it fails use sysinfo, if that fails return 0
5193 */
5194 long long num_pages = sysconf(_SC_PHYS_PAGES);
5195 long long page_size = sysconf(_SC_PAGESIZE);
5196 int phys_mem;
5197
5198 if(num_pages == -1 || page_size == -1) {
5199 struct sysinfo sys;
5200 int res = sysinfo(&sys);
5201
5202 if(res == -1)
5203 return 0;
5204
5205 num_pages = sys.totalram;
5206 page_size = sys.mem_unit;
5207 }
5208
5209 phys_mem = num_pages * page_size >> 20;
5210
5211 if(phys_mem < SQUASHFS_LOWMEM)
5212 BAD_ERROR("Mksquashfs requires more physical memory than is "
5213 "available!\n");
5214
5215 return phys_mem;
5216 }
5217
5218
5219 void check_usable_phys_mem(int total_mem)
5220 {
5221 /*
5222 * We want to allow users to use as much of their physical
5223 * memory as they wish. However, for practical reasons there are
5224 * limits which need to be imposed, to protect users from themselves
5225 * and to prevent people from using Mksquashfs as a DOS attack by using
5226 * all physical memory. Mksquashfs uses memory to cache data from disk
5227 * to optimise performance. It is pointless to ask it to use more
5228 * than 75% of physical memory, as this causes thrashing and it is thus
5229 * self-defeating.
5230 */
5231 int mem = get_physical_memory();
5232
5233 mem = (mem >> 1) + (mem >> 2); /* 75% */
5234
5235 if(total_mem > mem && mem) {
5236 ERROR("Total memory requested is more than 75%% of physical "
5237 "memory.\n");
5238 ERROR("Mksquashfs uses memory to cache data from disk to "
5239 "optimise performance.\n");
5240 ERROR("It is pointless to ask it to use more than this amount "
5241 "of memory, as this\n");
5242 ERROR("causes thrashing and it is thus self-defeating.\n");
5243 BAD_ERROR("Requested memory size too large\n");
5244 }
5245
5246 if(sizeof(void *) == 4 && total_mem > 2048) {
5247 /*
5248 * If we're running on a kernel with PAE or on a 64-bit kernel,
5249 * then the 75% physical memory limit can still easily exceed
5250 * the addressable memory by this process.
5251 *
5252 * Due to the typical kernel/user-space split (1GB/3GB, or
5253 * 2GB/2GB), we have to conservatively assume the 32-bit
5254 * processes can only address 2-3GB. So refuse if the user
5255 * tries to allocate more than 2GB.
5256 */
5257 ERROR("Total memory requested may exceed maximum "
5258 "addressable memory by this process\n");
5259 BAD_ERROR("Requested memory size too large\n");
5260 }
5261 }
5262
5263
5264 int get_default_phys_mem()
5265 {
5266 /*
5267 * get_physical_memory() relies on /proc being mounted.
5268 * If it fails, issue a warning, and use
5269 * SQUASHFS_LOWMEM / SQUASHFS_TAKE as default,
5270 * and allow a larger value to be set with -mem.
5271 */
5272 int mem = get_physical_memory();
5273
5274 if(mem == 0) {
5275 mem = SQUASHFS_LOWMEM / SQUASHFS_TAKE;
5276
5277 ERROR("Warning: Cannot get size of physical memory, probably "
5278 "because /proc is missing.\n");
5279 ERROR("Warning: Defaulting to minimal use of %d Mbytes, use "
5280 "-mem to set a better value,\n", mem);
5281 ERROR("Warning: or fix /proc.\n");
5282 } else
5283 mem /= SQUASHFS_TAKE;
5284
5285 if(sizeof(void *) == 4 && mem > 640) {
5286 /*
5287 * If we're running on a kernel with PAE or on a 64-bit kernel,
5288 * the default memory usage can exceed the addressable
5289 * memory by this process.
5290 * Due to the typical kernel/user-space split (1GB/3GB, or
5291 * 2GB/2GB), we have to conservatively assume the 32-bit
5292 * processes can only address 2-3GB. So limit the default
5293 * usage to 640M, which gives room for other data.
5294 */
5295 mem = 640;
5296 }
5297
5298 return mem;
5299 }
5300
5301
5302 void calculate_queue_sizes(int mem, int *readq, int *fragq, int *bwriteq,
5303 int *fwriteq)
5304 {
5305 *readq = mem / SQUASHFS_READQ_MEM;
5306 *bwriteq = mem / SQUASHFS_BWRITEQ_MEM;
5307 *fwriteq = mem / SQUASHFS_FWRITEQ_MEM;
5308 *fragq = mem - *readq - *bwriteq - *fwriteq;
5309 }
5310
5311
5312 void open_log_file(char *filename)
5313 {
5314 log_fd=fopen(filename, "w");
5315 if(log_fd == NULL)
5316 BAD_ERROR("Failed to open log file \"%s\" because %s\n", filename, strerror(errno));
5317
5318 logging=TRUE;
5319 }
5320
5321
5322 void check_env_var()
5323 {
5324 char *time_string = getenv("SOURCE_DATE_EPOCH");
5325 unsigned int time;
5326
5327 if(time_string != NULL) {
5328 /*
5329 * We cannot have both command-line options and environment
5330 * variable trying to set the timestamp(s) at the same
5331 * time. Semantically both are FORCE options which cannot be
5332 * over-ridden elsewhere (otherwise they can't be relied on).
5333 *
5334 * So refuse to continue if both are set.
5335 */
5336 if(mkfs_time_opt || all_time_opt)
5337 BAD_ERROR("SOURCE_DATE_EPOCH and command line options "
5338 "can't be used at the same time to set "
5339 "timestamp(s)\n");
5340
5341 if(!parse_num_unsigned(time_string, &time)) {
5342 ERROR("Env Var SOURCE_DATE_EPOCH has invalid time value\n");
5343 EXIT_MKSQUASHFS();
5344 }
5345
5346 all_time = mkfs_time = time;
5347 all_time_opt = mkfs_time_opt = TRUE;
5348 }
5349 }
5350
5351
5352 #define VERSION() \
5353 printf("mksquashfs version 4.4 (2019/08/29)\n");\
5354 printf("copyright (C) 2019 Phillip Lougher "\
5355 "<phillip@squashfs.org.uk>\n\n"); \
5356 printf("This program is free software; you can redistribute it and/or"\
5357 "\n");\
5358 printf("modify it under the terms of the GNU General Public License"\
5359 "\n");\
5360 printf("as published by the Free Software Foundation; either version "\
5361 "2,\n");\
5362 printf("or (at your option) any later version.\n\n");\
5363 printf("This program is distributed in the hope that it will be "\
5364 "useful,\n");\
5365 printf("but WITHOUT ANY WARRANTY; without even the implied warranty "\
5366 "of\n");\
5367 printf("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"\
5368 "\n");\
5369 printf("GNU General Public License for more details.\n");
5370 int main(int argc, char *argv[])
5371 {
5372 struct stat buf, source_buf;
5373 int res, i;
5374 char *b, *root_name = NULL;
5375 int keep_as_directory = FALSE;
5376 squashfs_inode inode;
5377 int readq;
5378 int fragq;
5379 int bwriteq;
5380 int fwriteq;
5381 int total_mem = get_default_phys_mem();
5382 int progress = TRUE;
5383 int force_progress = FALSE;
5384 struct file_buffer **fragment = NULL;
5385
5386 if(argc > 1 && strcmp(argv[1], "-version") == 0) {
5387 VERSION();
5388 exit(0);
5389 }
5390
5391 block_log = slog(block_size);
5392 calculate_queue_sizes(total_mem, &readq, &fragq, &bwriteq, &fwriteq);
5393
5394 for(i = 1; i < argc && argv[i][0] != '-'; i++);
5395 if(i < 3)
5396 goto printOptions;
5397 source_path = argv + 1;
5398 source = i - 2;
5399
5400 /*
5401 * Scan the command line for -comp xxx option, this is to ensure
5402 * any -X compressor specific options are passed to the
5403 * correct compressor
5404 */
5405 for(; i < argc; i++) {
5406 struct compressor *prev_comp = comp;
5407
5408 if(strcmp(argv[i], "-comp") == 0) {
5409 if(++i == argc) {
5410 ERROR("%s: -comp missing compression type\n",
5411 argv[0]);
5412 exit(1);
5413 }
5414 comp = lookup_compressor(argv[i]);
5415 if(!comp->supported) {
5416 ERROR("%s: Compressor \"%s\" is not supported!"
5417 "\n", argv[0], argv[i]);
5418 ERROR("%s: Compressors available:\n", argv[0]);
5419 display_compressors("", COMP_DEFAULT);
5420 exit(1);
5421 }
5422 if(prev_comp != NULL && prev_comp != comp) {
5423 ERROR("%s: -comp multiple conflicting -comp"
5424 " options specified on command line"
5425 ", previously %s, now %s\n", argv[0],
5426 prev_comp->name, comp->name);
5427 exit(1);
5428 }
5429 compressor_opt_parsed = 1;
5430
5431 } else if(strcmp(argv[i], "-e") == 0)
5432 break;
5433 else if(strcmp(argv[i], "-root-becomes") == 0 ||
5434 strcmp(argv[i], "-ef") == 0 ||
5435 strcmp(argv[i], "-pf") == 0 ||
5436 strcmp(argv[i], "-vaf") == 0 ||
5437 strcmp(argv[i], "-log") == 0)
5438 i++;
5439 }
5440
5441 /*
5442 * if no -comp option specified lookup default compressor. Note the
5443 * Makefile ensures the default compressor has been built, and so we
5444 * don't need to to check for failure here
5445 */
5446 if(comp == NULL)
5447 comp = lookup_compressor(COMP_DEFAULT);
5448
5449 for(i = source + 2; i < argc; i++) {
5450 if(strcmp(argv[i], "-mkfs-time") == 0 ||
5451 strcmp(argv[i], "-fstime") == 0) {
5452 if((++i == argc) || !parse_num_unsigned(argv[i], &mkfs_time)) {
5453 ERROR("%s: %s missing or invalid time value\n", argv[0], argv[i - 1]);
5454 exit(1);
5455 }
5456 mkfs_time_opt = TRUE;
5457 } else if(strcmp(argv[i], "-all-time") == 0) {
5458 if((++i == argc) || !parse_num_unsigned(argv[i], &all_time)) {
5459 ERROR("%s: %s missing or invalid time value\n", argv[0], argv[i - 1]);
5460 exit(1);
5461 }
5462 all_time_opt = TRUE;
5463 clamping = FALSE;
5464 } else if(strcmp(argv[i], "-reproducible") == 0)
5465 reproducible = TRUE;
5466 else if(strcmp(argv[i], "-not-reproducible") == 0)
5467 reproducible = FALSE;
5468 else if(strcmp(argv[i], "-root-mode") == 0) {
5469 if((++i == argc) || !parse_mode(argv[i], &root_mode)) {
5470 ERROR("%s: -root-mode missing or invalid mode,"
5471 " octal number <= 07777 expected\n", argv[0]);
5472 exit(1);
5473 }
5474 root_mode_opt = TRUE;
5475 } else if(strcmp(argv[i], "-log") == 0) {
5476 if(++i == argc) {
5477 ERROR("%s: %s missing log file\n",
5478 argv[0], argv[i - 1]);
5479 exit(1);
5480 }
5481 open_log_file(argv[i]);
5482
5483 } else if(strcmp(argv[i], "-action") == 0 ||
5484 strcmp(argv[i], "-a") ==0) {
5485 if(++i == argc) {
5486 ERROR("%s: %s missing action\n",
5487 argv[0], argv[i - 1]);
5488 exit(1);
5489 }
5490 res = parse_action(argv[i], ACTION_LOG_NONE);
5491 if(res == 0)
5492 exit(1);
5493
5494 } else if(strcmp(argv[i], "-verbose-action") == 0 ||
5495 strcmp(argv[i], "-va") ==0) {
5496 if(++i == argc) {
5497 ERROR("%s: %s missing action\n",
5498 argv[0], argv[i - 1]);
5499 exit(1);
5500 }
5501 res = parse_action(argv[i], ACTION_LOG_VERBOSE);
5502 if(res == 0)
5503 exit(1);
5504
5505 } else if(strcmp(argv[i], "-true-action") == 0 ||
5506 strcmp(argv[i], "-ta") ==0) {
5507 if(++i == argc) {
5508 ERROR("%s: %s missing action\n",
5509 argv[0], argv[i - 1]);
5510 exit(1);
5511 }
5512 res = parse_action(argv[i], ACTION_LOG_TRUE);
5513 if(res == 0)
5514 exit(1);
5515
5516 } else if(strcmp(argv[i], "-false-action") == 0 ||
5517 strcmp(argv[i], "-fa") ==0) {
5518 if(++i == argc) {
5519 ERROR("%s: %s missing action\n",
5520 argv[0], argv[i - 1]);
5521 exit(1);
5522 }
5523 res = parse_action(argv[i], ACTION_LOG_FALSE);
5524 if(res == 0)
5525 exit(1);
5526
5527 } else if(strcmp(argv[i], "-action-file") == 0 ||
5528 strcmp(argv[i], "-af") ==0) {
5529 if(++i == argc) {
5530 ERROR("%s: %s missing filename\n", argv[0],
5531 argv[i - 1]);
5532 exit(1);
5533 }
5534 if(read_action_file(argv[i], ACTION_LOG_NONE) == FALSE)
5535 exit(1);
5536
5537 } else if(strcmp(argv[i], "-verbose-action-file") == 0 ||
5538 strcmp(argv[i], "-vaf") ==0) {
5539 if(++i == argc) {
5540 ERROR("%s: %s missing filename\n", argv[0],
5541 argv[i - 1]);
5542 exit(1);
5543 }
5544 if(read_action_file(argv[i], ACTION_LOG_VERBOSE) == FALSE)
5545 exit(1);
5546
5547 } else if(strcmp(argv[i], "-true-action-file") == 0 ||
5548 strcmp(argv[i], "-taf") ==0) {
5549 if(++i == argc) {
5550 ERROR("%s: %s missing filename\n", argv[0],
5551 argv[i - 1]);
5552 exit(1);
5553 }
5554 if(read_action_file(argv[i], ACTION_LOG_TRUE) == FALSE)
5555 exit(1);
5556
5557 } else if(strcmp(argv[i], "-false-action-file") == 0 ||
5558 strcmp(argv[i], "-faf") ==0) {
5559 if(++i == argc) {
5560 ERROR("%s: %s missing filename\n", argv[0],
5561 argv[i - 1]);
5562 exit(1);
5563 }
5564 if(read_action_file(argv[i], ACTION_LOG_FALSE) == FALSE)
5565 exit(1);
5566
5567 } else if(strcmp(argv[i], "-comp") == 0)
5568 /* parsed previously */
5569 i++;
5570
5571 else if(strncmp(argv[i], "-X", 2) == 0) {
5572 int args;
5573
5574 if(strcmp(argv[i] + 2, "help") == 0)
5575 goto print_compressor_options;
5576
5577 args = compressor_options(comp, argv + i, argc - i);
5578 if(args < 0) {
5579 if(args == -1) {
5580 ERROR("%s: Unrecognised compressor"
5581 " option %s\n", argv[0],
5582 argv[i]);
5583 if(!compressor_opt_parsed)
5584 ERROR("%s: Did you forget to"
5585 " specify -comp?\n",
5586 argv[0]);
5587 print_compressor_options:
5588 ERROR("%s: selected compressor \"%s\""
5589 ". Options supported: %s\n",
5590 argv[0], comp->name,
5591 comp->usage ? "" : "none");
5592 if(comp->usage)
5593 comp->usage();
5594 }
5595 exit(1);
5596 }
5597 i += args;
5598
5599 } else if(strcmp(argv[i], "-pf") == 0) {
5600 if(++i == argc) {
5601 ERROR("%s: -pf missing filename\n", argv[0]);
5602 exit(1);
5603 }
5604 if(read_pseudo_file(argv[i]) == FALSE)
5605 exit(1);
5606 } else if(strcmp(argv[i], "-p") == 0) {
5607 if(++i == argc) {
5608 ERROR("%s: -p missing pseudo file definition\n",
5609 argv[0]);
5610 exit(1);
5611 }
5612 if(read_pseudo_def(argv[i]) == FALSE)
5613 exit(1);
5614 } else if(strcmp(argv[i], "-recover") == 0) {
5615 if(++i == argc) {
5616 ERROR("%s: -recover missing recovery file\n",
5617 argv[0]);
5618 exit(1);
5619 }
5620 read_recovery_data(argv[i], argv[source + 1]);
5621 } else if(strcmp(argv[i], "-no-recovery") == 0)
5622 recover = FALSE;
5623 else if(strcmp(argv[i], "-wildcards") == 0) {
5624 old_exclude = FALSE;
5625 use_regex = FALSE;
5626 } else if(strcmp(argv[i], "-regex") == 0) {
5627 old_exclude = FALSE;
5628 use_regex = TRUE;
5629 } else if(strcmp(argv[i], "-no-sparse") == 0)
5630 sparse_files = FALSE;
5631 else if(strcmp(argv[i], "-no-progress") == 0)
5632 progress = FALSE;
5633 else if(strcmp(argv[i], "-progress") == 0)
5634 force_progress = TRUE;
5635 else if(strcmp(argv[i], "-no-exports") == 0)
5636 exportable = FALSE;
5637 else if(strcmp(argv[i], "-offset") == 0 || strcmp(argv[i], "-o") == 0) {
5638 if((++i == argc) || !parse_numberll(argv[i], &start_offset, 1)) {
5639 ERROR("%s: %s missing or invalid offset size\n", argv[0], argv[i - 1]);
5640 exit(1);
5641 }
5642 } else if(strcmp(argv[i], "-processors") == 0) {
5643 if((++i == argc) || !parse_num(argv[i], &processors)) {
5644 ERROR("%s: -processors missing or invalid "
5645 "processor number\n", argv[0]);
5646 exit(1);
5647 }
5648 if(processors < 1) {
5649 ERROR("%s: -processors should be 1 or larger\n",
5650 argv[0]);
5651 exit(1);
5652 }
5653 } else if(strcmp(argv[i], "-read-queue") == 0) {
5654 if((++i == argc) || !parse_num(argv[i], &readq)) {
5655 ERROR("%s: -read-queue missing or invalid "
5656 "queue size\n", argv[0]);
5657 exit(1);
5658 }
5659 if(readq < 1) {
5660 ERROR("%s: -read-queue should be 1 megabyte or "
5661 "larger\n", argv[0]);
5662 exit(1);
5663 }
5664 } else if(strcmp(argv[i], "-write-queue") == 0) {
5665 if((++i == argc) || !parse_num(argv[i], &bwriteq)) {
5666 ERROR("%s: -write-queue missing or invalid "
5667 "queue size\n", argv[0]);
5668 exit(1);
5669 }
5670 if(bwriteq < 2) {
5671 ERROR("%s: -write-queue should be 2 megabytes "
5672 "or larger\n", argv[0]);
5673 exit(1);
5674 }
5675 fwriteq = bwriteq >> 1;
5676 bwriteq -= fwriteq;
5677 } else if(strcmp(argv[i], "-fragment-queue") == 0) {
5678 if((++i == argc) || !parse_num(argv[i], &fragq)) {
5679 ERROR("%s: -fragment-queue missing or invalid "
5680 "queue size\n", argv[0]);
5681 exit(1);
5682 }
5683 if(fragq < 1) {
5684 ERROR("%s: -fragment-queue should be 1 "
5685 "megabyte or larger\n", argv[0]);
5686 exit(1);
5687 }
5688 } else if(strcmp(argv[i], "-mem") == 0) {
5689 long long number;
5690
5691 if((++i == argc) ||
5692 !parse_numberll(argv[i], &number, 1)) {
5693 ERROR("%s: -mem missing or invalid mem size\n",
5694 argv[0]);
5695 exit(1);
5696 }
5697
5698 /*
5699 * convert from bytes to Mbytes, ensuring the value
5700 * does not overflow a signed int
5701 */
5702 if(number >= (1LL << 51)) {
5703 ERROR("%s: -mem invalid mem size\n", argv[0]);
5704 exit(1);
5705 }
5706
5707 total_mem = number / 1048576;
5708 if(total_mem < (SQUASHFS_LOWMEM / SQUASHFS_TAKE)) {
5709 ERROR("%s: -mem should be %d Mbytes or "
5710 "larger\n", argv[0],
5711 SQUASHFS_LOWMEM / SQUASHFS_TAKE);
5712 exit(1);
5713 }
5714 calculate_queue_sizes(total_mem, &readq, &fragq,
5715 &bwriteq, &fwriteq);
5716 } else if(strcmp(argv[i], "-b") == 0) {
5717 if(++i == argc) {
5718 ERROR("%s: -b missing block size\n", argv[0]);
5719 exit(1);
5720 }
5721 if(!parse_number(argv[i], &block_size, 1)) {
5722 ERROR("%s: -b invalid block size\n", argv[0]);
5723 exit(1);
5724 }
5725 if((block_log = slog(block_size)) == 0) {
5726 ERROR("%s: -b block size not power of two or "
5727 "not between 4096 and 1Mbyte\n",
5728 argv[0]);
5729 exit(1);
5730 }
5731 } else if(strcmp(argv[i], "-ef") == 0) {
5732 if(++i == argc) {
5733 ERROR("%s: -ef missing filename\n", argv[0]);
5734 exit(1);
5735 }
5736 } else if(strcmp(argv[i], "-no-duplicates") == 0)
5737 duplicate_checking = FALSE;
5738
5739 else if(strcmp(argv[i], "-no-fragments") == 0)
5740 no_fragments = TRUE;
5741
5742 else if(strcmp(argv[i], "-always-use-fragments") == 0)
5743 always_use_fragments = TRUE;
5744
5745 else if(strcmp(argv[i], "-sort") == 0) {
5746 if(++i == argc) {
5747 ERROR("%s: -sort missing filename\n", argv[0]);
5748 exit(1);
5749 }
5750 } else if(strcmp(argv[i], "-all-root") == 0 ||
5751 strcmp(argv[i], "-root-owned") == 0)
5752 global_uid = global_gid = 0;
5753
5754 else if(strcmp(argv[i], "-force-uid") == 0) {
5755 if(++i == argc) {
5756 ERROR("%s: -force-uid missing uid or user\n",
5757 argv[0]);
5758 exit(1);
5759 }
5760 if((global_uid = strtoll(argv[i], &b, 10)), *b =='\0') {
5761 if(global_uid < 0 || global_uid >
5762 (((long long) 1 << 32) - 1)) {
5763 ERROR("%s: -force-uid uid out of range"
5764 "\n", argv[0]);
5765 exit(1);
5766 }
5767 } else {
5768 struct passwd *uid = getpwnam(argv[i]);
5769 if(uid)
5770 global_uid = uid->pw_uid;
5771 else {
5772 ERROR("%s: -force-uid invalid uid or "
5773 "unknown user\n", argv[0]);
5774 exit(1);
5775 }
5776 }
5777 } else if(strcmp(argv[i], "-force-gid") == 0) {
5778 if(++i == argc) {
5779 ERROR("%s: -force-gid missing gid or group\n",
5780 argv[0]);
5781 exit(1);
5782 }
5783 if((global_gid = strtoll(argv[i], &b, 10)), *b =='\0') {
5784 if(global_gid < 0 || global_gid >
5785 (((long long) 1 << 32) - 1)) {
5786 ERROR("%s: -force-gid gid out of range"
5787 "\n", argv[0]);
5788 exit(1);
5789 }
5790 } else {
5791 struct group *gid = getgrnam(argv[i]);
5792 if(gid)
5793 global_gid = gid->gr_gid;
5794 else {
5795 ERROR("%s: -force-gid invalid gid or "
5796 "unknown group\n", argv[0]);
5797 exit(1);
5798 }
5799 }
5800 } else if(strcmp(argv[i], "-noI") == 0 ||
5801 strcmp(argv[i], "-noInodeCompression") == 0)
5802 noI = TRUE;
5803
5804 else if(strcmp(argv[i], "-noId") == 0 ||
5805 strcmp(argv[i], "-noIdTableCompression") == 0)
5806 noId = TRUE;
5807
5808 else if(strcmp(argv[i], "-noD") == 0 ||
5809 strcmp(argv[i], "-noDataCompression") == 0)
5810 noD = TRUE;
5811
5812 else if(strcmp(argv[i], "-noF") == 0 ||
5813 strcmp(argv[i], "-noFragmentCompression") == 0)
5814 noF = TRUE;
5815
5816 else if(strcmp(argv[i], "-noX") == 0 ||
5817 strcmp(argv[i], "-noXattrCompression") == 0)
5818 noX = TRUE;
5819
5820 else if(strcmp(argv[i], "-no-xattrs") == 0)
5821 no_xattrs = TRUE;
5822
5823 else if(strcmp(argv[i], "-xattrs") == 0)
5824 no_xattrs = FALSE;
5825
5826 else if(strcmp(argv[i], "-nopad") == 0)
5827 nopad = TRUE;
5828
5829 else if(strcmp(argv[i], "-info") == 0)
5830 silent = FALSE;
5831
5832 else if(strcmp(argv[i], "-e") == 0)
5833 break;
5834
5835 else if(strcmp(argv[i], "-noappend") == 0)
5836 delete = TRUE;
5837
5838 else if(strcmp(argv[i], "-quiet") == 0)
5839 quiet = TRUE;
5840
5841 else if(strcmp(argv[i], "-keep-as-directory") == 0)
5842 keep_as_directory = TRUE;
5843
5844 else if(strcmp(argv[i], "-exit-on-error") == 0)
5845 exit_on_error = TRUE;
5846
5847 else if(strcmp(argv[i], "-root-becomes") == 0) {
5848 if(++i == argc) {
5849 ERROR("%s: -root-becomes: missing name\n",
5850 argv[0]);
5851 exit(1);
5852 }
5853 root_name = argv[i];
5854 } else if(strcmp(argv[i], "-version") == 0) {
5855 VERSION();
5856 } else {
5857 ERROR("%s: invalid option\n\n", argv[0]);
5858 printOptions:
5859 ERROR("SYNTAX:%s source1 source2 ... dest [options] "
5860 "[-e list of exclude\ndirs/files]\n", argv[0]);
5861 ERROR("\nFilesystem build options:\n");
5862 ERROR("-comp <comp>\t\tselect <comp> compression\n");
5863 ERROR("\t\t\tCompressors available:\n");
5864 display_compressors("\t\t\t", COMP_DEFAULT);
5865 ERROR("-b <block_size>\t\tset data block to "
5866 "<block_size>. Default 128 Kbytes\n");
5867 ERROR("\t\t\tOptionally a suffix of K or M can be"
5868 " given to specify\n\t\t\tKbytes or Mbytes"
5869 " respectively\n");
5870 ERROR("-reproducible\t\tbuild images that are reproducible"
5871 REP_STR "\n");
5872 ERROR("-not-reproducible\tbuild images that are not reproducible"
5873 NOREP_STR "\n");
5874 ERROR("-mkfs-time <time>\tset mkfs time to <time> which is an unsigned int\n");
5875 ERROR("-fstime <time>\t\tsynonym for mkfs-time\n");
5876 ERROR("-all-time <time>\tset all inode times to <time> which is an unsigned int\n");
5877 ERROR("-no-exports\t\tdon't make the filesystem "
5878 "exportable via NFS\n");
5879 ERROR("-no-sparse\t\tdon't detect sparse files\n");
5880 ERROR("-no-xattrs\t\tdon't store extended attributes"
5881 NOXOPT_STR "\n");
5882 ERROR("-xattrs\t\t\tstore extended attributes" XOPT_STR
5883 "\n");
5884 ERROR("-noI\t\t\tdo not compress inode table\n");
5885 ERROR("-noId\t\t\tdo not compress the uid/gid table"
5886 " (implied by -noI)\n");
5887 ERROR("-noD\t\t\tdo not compress data blocks\n");
5888 ERROR("-noF\t\t\tdo not compress fragment blocks\n");
5889 ERROR("-noX\t\t\tdo not compress extended "
5890 "attributes\n");
5891 ERROR("-no-fragments\t\tdo not use fragments\n");
5892 ERROR("-always-use-fragments\tuse fragment blocks for "
5893 "files larger than block size\n");
5894 ERROR("-no-duplicates\t\tdo not perform duplicate "
5895 "checking\n");
5896 ERROR("-all-root\t\tmake all files owned by root\n");
5897 ERROR("-root-mode <mode>\tset root directory permissions to octal <mode>\n");
5898 ERROR("-force-uid <uid>\tset all file uids to <uid>\n");
5899 ERROR("-force-gid <gid>\tset all file gids to <gid>\n");
5900 ERROR("-nopad\t\t\tdo not pad filesystem to a multiple "
5901 "of 4K\n");
5902 ERROR("-keep-as-directory\tif one source directory is "
5903 "specified, create a root\n");
5904 ERROR("\t\t\tdirectory containing that directory, "
5905 "rather than the\n");
5906 ERROR("\t\t\tcontents of the directory\n");
5907 ERROR("\nFilesystem filter options:\n");
5908 ERROR("-p <pseudo-definition>\tAdd pseudo file "
5909 "definition\n");
5910 ERROR("-pf <pseudo-file>\tAdd list of pseudo file "
5911 "definitions\n");
5912 ERROR("\t\t\tPseudo definitions should be of the "
5913 "format\n");
5914 ERROR("\t\t\t\tfilename d mode uid gid\n");
5915 ERROR("\t\t\t\tfilename m mode uid gid\n");
5916 ERROR("\t\t\t\tfilename b mode uid gid major minor\n");
5917 ERROR("\t\t\t\tfilename c mode uid gid major minor\n");
5918 ERROR("\t\t\t\tfilename f mode uid gid command\n");
5919 ERROR("\t\t\t\tfilename s mode uid gid symlink\n");
5920 ERROR("-sort <sort_file>\tsort files according to "
5921 "priorities in <sort_file>. One\n");
5922 ERROR("\t\t\tfile or dir with priority per line. "
5923 "Priority -32768 to\n");
5924 ERROR("\t\t\t32767, default priority 0\n");
5925 ERROR("-ef <exclude_file>\tlist of exclude dirs/files."
5926 " One per line\n");
5927 ERROR("-wildcards\t\tAllow extended shell wildcards "
5928 "(globbing) to be used in\n\t\t\texclude "
5929 "dirs/files\n");
5930 ERROR("-regex\t\t\tAllow POSIX regular expressions to "
5931 "be used in exclude\n\t\t\tdirs/files\n");
5932 ERROR("\nFilesystem append options:\n");
5933 ERROR("-noappend\t\tdo not append to existing "
5934 "filesystem\n");
5935 ERROR("-root-becomes <name>\twhen appending source "
5936 "files/directories, make the\n");
5937 ERROR("\t\t\toriginal root become a subdirectory in "
5938 "the new root\n");
5939 ERROR("\t\t\tcalled <name>, rather than adding the new "
5940 "source items\n");
5941 ERROR("\t\t\tto the original root\n");
5942 ERROR("\nMksquashfs runtime options:\n");
5943 ERROR("-version\t\tprint version, licence and "
5944 "copyright message\n");
5945 ERROR("-exit-on-error\t\ttreat normally ignored errors "
5946 "as fatal\n");
5947 ERROR("-recover <name>\t\trecover filesystem data "
5948 "using recovery file <name>\n");
5949 ERROR("-no-recovery\t\tdon't generate a recovery "
5950 "file\n");
5951 ERROR("-quiet\t\t\tno verbose output\n");
5952 ERROR("-info\t\t\tprint files written to filesystem\n");
5953 ERROR("-no-progress\t\tdon't display the progress "
5954 "bar\n");
5955 ERROR("-progress\t\tdisplay progress bar when using "
5956 "the -info option\n");
5957 ERROR("-processors <number>\tUse <number> processors."
5958 " By default will use number of\n");
5959 ERROR("\t\t\tprocessors available\n");
5960 ERROR("-mem <size>\t\tUse <size> physical memory. "
5961 "Currently set to %dM\n", total_mem);
5962 ERROR("\t\t\tOptionally a suffix of K, M or G can be"
5963 " given to specify\n\t\t\tKbytes, Mbytes or"
5964 " Gbytes respectively\n");
5965 ERROR("\nMiscellaneous options:\n");
5966 ERROR("-root-owned\t\talternative name for -all-root"
5967 "\n");
5968 ERROR("-offset <offset>\tSkip <offset> bytes at the "
5969 "beginning of <dest>.\n");
5970 ERROR("\t\t\tOptionally a suffix of K, M or G can be"
5971 " given to specify\n\t\t\tKbytes, Mbytes or"
5972 " Gbytes respectively.\n");
5973 ERROR("\t\t\tDefault 0 bytes.\n");
5974 ERROR("-o <offset>\t\tsynonym for -offset\n");
5975 ERROR("-noInodeCompression\talternative name for -noI"
5976 "\n");
5977 ERROR("-noIdTableCompression\talternative name for -noId"
5978 "\n");
5979 ERROR("-noDataCompression\talternative name for -noD"
5980 "\n");
5981 ERROR("-noFragmentCompression\talternative name for "
5982 "-noF\n");
5983 ERROR("-noXattrCompression\talternative name for "
5984 "-noX\n");
5985 ERROR("\n-Xhelp\t\t\tprint compressor options for"
5986 " selected compressor\n");
5987 ERROR("\nCompressors available and compressor specific "
5988 "options:\n");
5989 display_compressor_usage(COMP_DEFAULT);
5990 exit(1);
5991 }
5992 }
5993
5994 check_env_var();
5995
5996 /*
5997 * The -noI option implies -noId for backwards compatibility, so reset noId
5998 * if both have been specified
5999 */
6000 if(noI && noId)
6001 noId = FALSE;
6002
6003 /*
6004 * Some compressors may need the options to be checked for validity
6005 * once all the options have been processed
6006 */
6007 res = compressor_options_post(comp, block_size);
6008 if(res)
6009 EXIT_MKSQUASHFS();
6010
6011 /*
6012 * If the -info option has been selected then disable the
6013 * progress bar unless it has been explicitly enabled with
6014 * the -progress option
6015 */
6016 if(!silent)
6017 progress = force_progress;
6018
6019 #ifdef SQUASHFS_TRACE
6020 /*
6021 * Disable progress bar if full debug tracing is enabled.
6022 * The progress bar in this case just gets in the way of the
6023 * debug trace output
6024 */
6025 progress = FALSE;
6026 #endif
6027
6028 for(i = 0; i < source; i++)
6029 if(lstat(source_path[i], &source_buf) == -1) {
6030 fprintf(stderr, "Cannot stat source directory \"%s\" "
6031 "because %s\n", source_path[i],
6032 strerror(errno));
6033 EXIT_MKSQUASHFS();
6034 }
6035
6036 destination_file = argv[source + 1];
6037 if(stat(argv[source + 1], &buf) == -1) {
6038 if(errno == ENOENT) { /* Does not exist */
6039 fd = open(argv[source + 1], O_CREAT | O_TRUNC | O_RDWR,
6040 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
6041 if(fd == -1) {
6042 perror("Could not create destination file");
6043 exit(1);
6044 }
6045 delete = TRUE;
6046 } else {
6047 perror("Could not stat destination file");
6048 exit(1);
6049 }
6050
6051 } else {
6052 if(S_ISBLK(buf.st_mode)) {
6053 if((fd = open(argv[source + 1], O_RDWR)) == -1) {
6054 perror("Could not open block device as "
6055 "destination");
6056 exit(1);
6057 }
6058 block_device = 1;
6059
6060 } else if(S_ISREG(buf.st_mode)) {
6061 fd = open(argv[source + 1], (delete ? O_TRUNC : 0) |
6062 O_RDWR);
6063 if(fd == -1) {
6064 perror("Could not open regular file for "
6065 "writing as destination");
6066 exit(1);
6067 }
6068 }
6069 else {
6070 ERROR("Destination not block device or regular file\n");
6071 exit(1);
6072 }
6073
6074 }
6075
6076 /*
6077 * process the exclude files - must be done afer destination file has
6078 * been possibly created
6079 */
6080 for(i = source + 2; i < argc; i++)
6081 if(strcmp(argv[i], "-ef") == 0)
6082 /*
6083 * Note presence of filename arg has already
6084 * been checked
6085 */
6086 process_exclude_file(argv[++i]);
6087 else if(strcmp(argv[i], "-e") == 0)
6088 break;
6089 else if(strcmp(argv[i], "-root-becomes") == 0 ||
6090 strcmp(argv[i], "-sort") == 0 ||
6091 strcmp(argv[i], "-pf") == 0 ||
6092 strcmp(argv[i], "-af") == 0 ||
6093 strcmp(argv[i], "-vaf") == 0 ||
6094 strcmp(argv[i], "-comp") == 0 ||
6095 strcmp(argv[i], "-log") == 0)
6096 i++;
6097
6098 if(i != argc) {
6099 if(++i == argc) {
6100 ERROR("%s: -e missing arguments\n", argv[0]);
6101 EXIT_MKSQUASHFS();
6102 }
6103 while(i < argc)
6104 if(old_exclude)
6105 old_add_exclude(argv[i++]);
6106 else
6107 add_exclude(argv[i++]);
6108 }
6109
6110 /* process the sort files - must be done afer the exclude files */
6111 for(i = source + 2; i < argc; i++)
6112 if(strcmp(argv[i], "-sort") == 0) {
6113 int res = read_sort_file(argv[++i], source,
6114 source_path);
6115 if(res == FALSE)
6116 BAD_ERROR("Failed to read sort file\n");
6117 sorted ++;
6118 } else if(strcmp(argv[i], "-e") == 0)
6119 break;
6120 else if(strcmp(argv[i], "-root-becomes") == 0 ||
6121 strcmp(argv[i], "-ef") == 0 ||
6122 strcmp(argv[i], "-pf") == 0 ||
6123 strcmp(argv[i], "-af") == 0 ||
6124 strcmp(argv[i], "-vaf") == 0 ||
6125 strcmp(argv[i], "-comp") == 0 ||
6126 strcmp(argv[i], "-log") == 0)
6127 i++;
6128
6129 if(!delete) {
6130 comp = read_super(fd, &sBlk, argv[source + 1]);
6131 if(comp == NULL) {
6132 ERROR("Failed to read existing filesystem - will not "
6133 "overwrite - ABORTING!\n");
6134 ERROR("To force Mksquashfs to write to this block "
6135 "device or file use -noappend\n");
6136 EXIT_MKSQUASHFS();
6137 }
6138
6139 block_log = slog(block_size = sBlk.block_size);
6140 noI = SQUASHFS_UNCOMPRESSED_INODES(sBlk.flags);
6141 noD = SQUASHFS_UNCOMPRESSED_DATA(sBlk.flags);
6142 noF = SQUASHFS_UNCOMPRESSED_FRAGMENTS(sBlk.flags);
6143 noX = SQUASHFS_UNCOMPRESSED_XATTRS(sBlk.flags);
6144 noId = SQUASHFS_UNCOMPRESSED_IDS(sBlk.flags);
6145 no_fragments = SQUASHFS_NO_FRAGMENTS(sBlk.flags);
6146 always_use_fragments = SQUASHFS_ALWAYS_FRAGMENTS(sBlk.flags);
6147 duplicate_checking = SQUASHFS_DUPLICATES(sBlk.flags);
6148 exportable = SQUASHFS_EXPORTABLE(sBlk.flags);
6149 no_xattrs = SQUASHFS_NO_XATTRS(sBlk.flags);
6150 comp_opts = SQUASHFS_COMP_OPTS(sBlk.flags);
6151 }
6152
6153 initialise_threads(readq, fragq, bwriteq, fwriteq, delete,
6154 destination_file);
6155
6156 res = compressor_init(comp, &stream, SQUASHFS_METADATA_SIZE, 0);
6157 if(res)
6158 BAD_ERROR("compressor_init failed\n");
6159
6160 if(delete) {
6161 int size;
6162 void *comp_data = compressor_dump_options(comp, block_size,
6163 &size);
6164
6165 if(!quiet)
6166 printf("Creating %d.%d filesystem on %s, block size %d.\n",
6167 SQUASHFS_MAJOR, SQUASHFS_MINOR,
6168 argv[source + 1], block_size);
6169
6170 /*
6171 * store any compressor specific options after the superblock,
6172 * and set the COMP_OPT flag to show that the filesystem has
6173 * compressor specfic options
6174 */
6175 if(comp_data) {
6176 unsigned short c_byte = size | SQUASHFS_COMPRESSED_BIT;
6177
6178 SQUASHFS_INSWAP_SHORTS(&c_byte, 1);
6179 write_destination(fd, sizeof(struct squashfs_super_block),
6180 sizeof(c_byte), &c_byte);
6181 write_destination(fd, sizeof(struct squashfs_super_block) +
6182 sizeof(c_byte), size, comp_data);
6183 bytes = sizeof(struct squashfs_super_block) + sizeof(c_byte)
6184 + size;
6185 comp_opts = TRUE;
6186 } else
6187 bytes = sizeof(struct squashfs_super_block);
6188 } else {
6189 unsigned int last_directory_block, inode_dir_offset,
6190 inode_dir_file_size, root_inode_size,
6191 inode_dir_start_block, uncompressed_data,
6192 compressed_data, inode_dir_inode_number,
6193 inode_dir_parent_inode;
6194 unsigned int root_inode_start =
6195 SQUASHFS_INODE_BLK(sBlk.root_inode),
6196 root_inode_offset =
6197 SQUASHFS_INODE_OFFSET(sBlk.root_inode);
6198
6199 if((bytes = read_filesystem(root_name, fd, &sBlk, &inode_table,
6200 &data_cache, &directory_table,
6201 &directory_data_cache, &last_directory_block,
6202 &inode_dir_offset, &inode_dir_file_size,
6203 &root_inode_size, &inode_dir_start_block,
6204 &file_count, &sym_count, &dev_count, &dir_count,
6205 &fifo_count, &sock_count, &total_bytes,
6206 &total_inode_bytes, &total_directory_bytes,
6207 &inode_dir_inode_number,
6208 &inode_dir_parent_inode, add_old_root_entry,
6209 &fragment_table, &inode_lookup_table)) == 0) {
6210 ERROR("Failed to read existing filesystem - will not "
6211 "overwrite - ABORTING!\n");
6212 ERROR("To force Mksquashfs to write to this block "
6213 "device or file use -noappend\n");
6214 EXIT_MKSQUASHFS();
6215 }
6216 if((append_fragments = fragments = sBlk.fragments)) {
6217 fragment_table = realloc((char *) fragment_table,
6218 ((fragments + FRAG_SIZE - 1) & ~(FRAG_SIZE - 1))
6219 * sizeof(struct squashfs_fragment_entry));
6220 if(fragment_table == NULL)
6221 BAD_ERROR("Out of memory in save filesystem state\n");
6222 }
6223
6224 printf("Appending to existing %d.%d filesystem on %s, block "
6225 "size %d\n", SQUASHFS_MAJOR, SQUASHFS_MINOR, argv[source + 1],
6226 block_size);
6227 printf("All -b, -noI, -noD, -noF, -noX, -noId, -no-duplicates, "
6228 "-no-fragments,\n-always-use-fragments, -exportable and "
6229 "-comp options ignored\n");
6230 printf("\nIf appending is not wanted, please re-run with "
6231 "-noappend specified!\n\n");
6232
6233 compressed_data = (inode_dir_offset + inode_dir_file_size) &
6234 ~(SQUASHFS_METADATA_SIZE - 1);
6235 uncompressed_data = (inode_dir_offset + inode_dir_file_size) &
6236 (SQUASHFS_METADATA_SIZE - 1);
6237
6238 /* save original filesystem state for restoring ... */
6239 sfragments = fragments;
6240 sbytes = bytes;
6241 sinode_count = sBlk.inodes;
6242 scache_bytes = root_inode_offset + root_inode_size;
6243 sdirectory_cache_bytes = uncompressed_data;
6244 sdata_cache = malloc(scache_bytes);
6245 if(sdata_cache == NULL)
6246 BAD_ERROR("Out of memory in save filesystem state\n");
6247 sdirectory_data_cache = malloc(sdirectory_cache_bytes);
6248 if(sdirectory_data_cache == NULL)
6249 BAD_ERROR("Out of memory in save filesystem state\n");
6250 memcpy(sdata_cache, data_cache, scache_bytes);
6251 memcpy(sdirectory_data_cache, directory_data_cache +
6252 compressed_data, sdirectory_cache_bytes);
6253 sinode_bytes = root_inode_start;
6254 stotal_bytes = total_bytes;
6255 stotal_inode_bytes = total_inode_bytes;
6256 stotal_directory_bytes = total_directory_bytes +
6257 compressed_data;
6258 sfile_count = file_count;
6259 ssym_count = sym_count;
6260 sdev_count = dev_count;
6261 sdir_count = dir_count + 1;
6262 sfifo_count = fifo_count;
6263 ssock_count = sock_count;
6264 sdup_files = dup_files;
6265 sid_count = id_count;
6266 write_recovery_data(&sBlk);
6267 save_xattrs();
6268 appending = TRUE;
6269
6270 /*
6271 * set the filesystem state up to be able to append to the
6272 * original filesystem. The filesystem state differs depending
6273 * on whether we're appending to the original root directory, or
6274 * if the original root directory becomes a sub-directory
6275 * (root-becomes specified on command line, here root_name !=
6276 * NULL)
6277 */
6278 inode_bytes = inode_size = root_inode_start;
6279 directory_size = last_directory_block;
6280 cache_size = root_inode_offset + root_inode_size;
6281 directory_cache_size = inode_dir_offset + inode_dir_file_size;
6282 if(root_name) {
6283 sdirectory_bytes = last_directory_block;
6284 sdirectory_compressed_bytes = 0;
6285 root_inode_number = inode_dir_parent_inode;
6286 inode_no = sBlk.inodes + 2;
6287 directory_bytes = last_directory_block;
6288 directory_cache_bytes = uncompressed_data;
6289 memmove(directory_data_cache, directory_data_cache +
6290 compressed_data, uncompressed_data);
6291 cache_bytes = root_inode_offset + root_inode_size;
6292 add_old_root_entry(root_name, sBlk.root_inode,
6293 inode_dir_inode_number, SQUASHFS_DIR_TYPE);
6294 total_directory_bytes += compressed_data;
6295 dir_count ++;
6296 } else {
6297 sdirectory_compressed_bytes = last_directory_block -
6298 inode_dir_start_block;
6299 sdirectory_compressed =
6300 malloc(sdirectory_compressed_bytes);
6301 if(sdirectory_compressed == NULL)
6302 BAD_ERROR("Out of memory in save filesystem "
6303 "state\n");
6304 memcpy(sdirectory_compressed, directory_table +
6305 inode_dir_start_block,
6306 sdirectory_compressed_bytes);
6307 sdirectory_bytes = inode_dir_start_block;
6308 root_inode_number = inode_dir_inode_number;
6309 inode_no = sBlk.inodes + 1;
6310 directory_bytes = inode_dir_start_block;
6311 directory_cache_bytes = inode_dir_offset;
6312 cache_bytes = root_inode_offset;
6313 }
6314
6315 inode_count = file_count + dir_count + sym_count + dev_count +
6316 fifo_count + sock_count;
6317 }
6318
6319 if(path)
6320 paths = add_subdir(paths, path);
6321
6322 dump_actions();
6323 dump_pseudos();
6324
6325 if(delete && !keep_as_directory && source == 1 &&
6326 S_ISDIR(source_buf.st_mode))
6327 dir_scan(&inode, source_path[0], scan1_readdir, progress);
6328 else if(!keep_as_directory && source == 1 &&
6329 S_ISDIR(source_buf.st_mode))
6330 dir_scan(&inode, source_path[0], scan1_single_readdir, progress);
6331 else
6332 dir_scan(&inode, "", scan1_encomp_readdir, progress);
6333 sBlk.root_inode = inode;
6334 sBlk.inodes = inode_count;
6335 sBlk.s_magic = SQUASHFS_MAGIC;
6336 sBlk.s_major = SQUASHFS_MAJOR;
6337 sBlk.s_minor = SQUASHFS_MINOR;
6338 sBlk.block_size = block_size;
6339 sBlk.block_log = block_log;
6340 sBlk.flags = SQUASHFS_MKFLAGS(noI, noD, noF, noX, noId, no_fragments,
6341 always_use_fragments, duplicate_checking, exportable,
6342 no_xattrs, comp_opts);
6343 sBlk.mkfs_time = mkfs_time_opt ? mkfs_time : time(NULL);
6344
6345 disable_info();
6346
6347 while((fragment = get_frag_action(fragment)))
6348 write_fragment(*fragment);
6349 if(!reproducible)
6350 unlock_fragments();
6351 pthread_cleanup_push((void *) pthread_mutex_unlock, &fragment_mutex);
6352 pthread_mutex_lock(&fragment_mutex);
6353 while(fragments_outstanding) {
6354 pthread_mutex_unlock(&fragment_mutex);
6355 pthread_testcancel();
6356 sched_yield();
6357 pthread_mutex_lock(&fragment_mutex);
6358 }
6359 pthread_cleanup_pop(1);
6360
6361 queue_put(to_writer, NULL);
6362 if(queue_get(from_writer) != 0)
6363 EXIT_MKSQUASHFS();
6364
6365 set_progressbar_state(FALSE);
6366 write_filesystem_tables(&sBlk, nopad);
6367
6368 if(logging)
6369 fclose(log_fd);
6370
6371 return 0;
6372 }